Merge remote-tracking branch 'pnacl/master' into merge-pnacl-mar-13-2015

Conflicts:
	lib/Driver/ToolChains.h
diff --git a/.clang-tidy b/.clang-tidy
new file mode 100644
index 0000000..3186da4
--- /dev/null
+++ b/.clang-tidy
@@ -0,0 +1 @@
+Checks: '-*,clang-diagnostic-*,llvm-*,misc-*'
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 02374e2..35d8d69 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -240,7 +240,7 @@
 
 # Add appropriate flags for GCC
 if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-common -Woverloaded-virtual -Wcast-qual -fno-strict-aliasing")
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-common -Woverloaded-virtual -fno-strict-aliasing")
 
   # Enable -pedantic for Clang even if it's not enabled for LLVM.
   if (NOT LLVM_ENABLE_PEDANTIC)
@@ -253,6 +253,26 @@
   endif()
 endif ()
 
+# Determine HOST_LINK_VERSION on Darwin.
+set(HOST_LINK_VERSION)
+if (APPLE)
+  set(LD_V_OUTPUT)
+  execute_process(
+    COMMAND sh -c "${CMAKE_LINKER} -v 2>&1 | head -1"
+    RESULT_VARIABLE HAD_ERROR
+    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})
+    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}")
+  endif()
+endif()
+
 configure_file(
   ${CLANG_SOURCE_DIR}/include/clang/Config/config.h.cmake
   ${CLANG_BINARY_DIR}/include/clang/Config/config.h)
@@ -337,6 +357,7 @@
         ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX}
         RUNTIME DESTINATION bin)
     endif()
+    set_property(GLOBAL APPEND PROPERTY CLANG_EXPORTS ${name})
   else()
     # Add empty "phony" target
     add_custom_target(${name})
@@ -478,3 +499,27 @@
 
 set(CLANG_ORDER_FILE "" CACHE FILEPATH
   "Order file to use when compiling clang in order to improve startup time.")
+
+if (CLANG_BUILT_STANDALONE)
+  # Generate a list of CMake library targets so that other CMake projects can
+  # link against them. LLVM calls its version of this file LLVMExports.cmake, but
+  # the usual CMake convention seems to be ${Project}Targets.cmake.
+  set(CLANG_INSTALL_PACKAGE_DIR share/clang/cmake)
+  set(clang_cmake_builddir "${CMAKE_BINARY_DIR}/${CLANG_INSTALL_PACKAGE_DIR}")
+  get_property(CLANG_EXPORTS GLOBAL PROPERTY CLANG_EXPORTS)
+  export(TARGETS ${CLANG_EXPORTS} FILE ${clang_cmake_builddir}/ClangTargets.cmake)
+
+  # Install a <prefix>/share/clang/cmake/ClangConfig.cmake file so that
+  # find_package(Clang) works. Install the target list with it.
+  install(FILES
+    ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/ClangConfig.cmake
+    ${CLANG_BINARY_DIR}/share/clang/cmake/ClangTargets.cmake
+    DESTINATION share/clang/cmake)
+
+  # Also copy ClangConfig.cmake to the build directory so that dependent projects
+  # can build against a build directory of Clang more easily.
+  configure_file(
+    ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/ClangConfig.cmake
+    ${CLANG_BINARY_DIR}/share/clang/cmake/ClangConfig.cmake
+    COPYONLY)
+endif ()
diff --git a/CODE_OWNERS.TXT b/CODE_OWNERS.TXT
index bbd3142..b58014f 100644
--- a/CODE_OWNERS.TXT
+++ b/CODE_OWNERS.TXT
@@ -22,6 +22,7 @@
 D: Debug Information, autotools/configure/make build, inline assembly
 
 N: Doug Gregor
+E: dgregor@apple.com
 D: All parts of Clang not covered by someone else
 
 N: Anton Korobeynikov
@@ -29,6 +30,7 @@
 D: Exception handling, Windows codegen, ARM EABI
 
 N: Ted Kremenek
+E: kremenek@apple.com
 D: Clang Static Analyzer
 
 N: John McCall
@@ -37,7 +39,7 @@
 
 N: Chad Rosier
 E: mcrosier@codeaurora.org
-D: MS-inline asm, and the compiler driver
+D: Compiler driver
 
 N: Richard Smith
 E: richard@metafoo.co.uk
diff --git a/bindings/python/clang/cindex.py b/bindings/python/clang/cindex.py
index 517b3c1..5792eff 100644
--- a/bindings/python/clang/cindex.py
+++ b/bindings/python/clang/cindex.py
@@ -496,24 +496,28 @@
         setattr(TokenKind, name, kind)
 
 ### Cursor Kinds ###
-
-class CursorKind(object):
+class BaseEnumeration(object):
     """
-    A CursorKind describes the kind of entity that a cursor points to.
-    """
+    Common base class for named enumerations held in sync with Index.h values.
 
-    # The unique kind objects, indexed by id.
+    Subclasses must define their own _kinds and _name_map members, as:
     _kinds = []
     _name_map = None
+    These values hold the per-subclass instances and value-to-name mappings,
+    respectively.
+
+    """
 
     def __init__(self, value):
-        if value >= len(CursorKind._kinds):
-            CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1)
-        if CursorKind._kinds[value] is not None:
-            raise ValueError,'CursorKind already loaded'
+        if value >= len(self.__class__._kinds):
+            self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1)
+        if self.__class__._kinds[value] is not None:
+            raise ValueError,'{0} value {1} already loaded'.format(
+                str(self.__class__), value)
         self.value = value
-        CursorKind._kinds[value] = self
-        CursorKind._name_map = None
+        self.__class__._kinds[value] = self
+        self.__class__._name_map = None
+
 
     def from_param(self):
         return self.value
@@ -523,16 +527,29 @@
         """Get the enumeration name of this cursor kind."""
         if self._name_map is None:
             self._name_map = {}
-            for key,value in CursorKind.__dict__.items():
-                if isinstance(value,CursorKind):
+            for key, value in self.__class__.__dict__.items():
+                if isinstance(value, self.__class__):
                     self._name_map[value] = key
         return self._name_map[self]
 
-    @staticmethod
-    def from_id(id):
-        if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None:
-            raise ValueError,'Unknown cursor kind %d' % id
-        return CursorKind._kinds[id]
+    @classmethod
+    def from_id(cls, id):
+        if id >= len(cls._kinds) or cls._kinds[id] is None:
+            raise ValueError,'Unknown template argument kind %d' % id
+        return cls._kinds[id]
+
+    def __repr__(self):
+        return '%s.%s' % (self.__class__, self.name,)
+
+
+class CursorKind(BaseEnumeration):
+    """
+    A CursorKind describes the kind of entity that a cursor points to.
+    """
+
+    # The required BaseEnumeration declarations.
+    _kinds = []
+    _name_map = None
 
     @staticmethod
     def get_all_kinds():
@@ -578,11 +595,6 @@
     def __repr__(self):
         return 'CursorKind.%s' % (self.name,)
 
-# FIXME: Is there a nicer way to expose this enumeration? We could potentially
-# represent the nested structure, or even build a class hierarchy. The main
-# things we want for sure are (a) simple external access to kinds, (b) a place
-# to hang a description and name, (c) easy to keep in sync with Index.h.
-
 ###
 # Declaration Kinds
 
@@ -1086,6 +1098,7 @@
 CursorKind.CUDADEVICE_ATTR = CursorKind(413)
 CursorKind.CUDAGLOBAL_ATTR = CursorKind(414)
 CursorKind.CUDAHOST_ATTR = CursorKind(415)
+CursorKind.CUDASHARED_ATTR = CursorKind(416)
 
 ###
 # Preprocessing
@@ -1100,6 +1113,24 @@
 # A module import declaration.
 CursorKind.MODULE_IMPORT_DECL = CursorKind(600)
 
+
+### Template Argument Kinds ###
+class TemplateArgumentKind(BaseEnumeration):
+    """
+    A TemplateArgumentKind describes the kind of entity that a template argument
+    represents.
+    """
+
+    # The required BaseEnumeration declarations.
+    _kinds = []
+    _name_map = None
+
+TemplateArgumentKind.NULL = TemplateArgumentKind(0)
+TemplateArgumentKind.TYPE = TemplateArgumentKind(1)
+TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2)
+TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3)
+TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4)
+
 ### Cursors ###
 
 class Cursor(Structure):
@@ -1176,9 +1207,9 @@
         """
         Return the display name for the entity referenced by this cursor.
 
-        The display name contains extra information that helps identify the cursor,
-        such as the parameters of a function or template or the arguments of a
-        class template specialization.
+        The display name contains extra information that helps identify the
+        cursor, such as the parameters of a function or template or the
+        arguments of a class template specialization.
         """
         if not hasattr(self, '_displayname'):
             self._displayname = conf.lib.clang_getCursorDisplayName(self)
@@ -1186,6 +1217,14 @@
         return self._displayname
 
     @property
+    def mangled_name(self):
+        """Return the mangled name for the entity referenced by this cursor."""
+        if not hasattr(self, '_mangled_name'):
+            self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
+
+        return self._mangled_name
+
+    @property
     def location(self):
         """
         Return the source location (the starting character) of the entity
@@ -1208,6 +1247,17 @@
         return self._extent
 
     @property
+    def storage_class(self):
+        """
+        Retrieves the storage class (if any) of the entity pointed at by the
+        cursor.
+        """
+        if not hasattr(self, '_storage_class'):
+            self._storage_class = conf.lib.clang_Cursor_getStorageClass(self)
+
+        return StorageClass.from_id(self._storage_class)
+
+    @property
     def access_specifier(self):
         """
         Retrieves the access specifier (if any) of the entity pointed at by the
@@ -1369,6 +1419,27 @@
         for i in range(0, num_args):
             yield conf.lib.clang_Cursor_getArgument(self, i)
 
+    def get_num_template_arguments(self):
+        """Returns the number of template args associated with this cursor."""
+        return conf.lib.clang_Cursor_getNumTemplateArguments(self)
+
+    def get_template_argument_kind(self, num):
+        """Returns the TemplateArgumentKind for the indicated template
+        argument."""
+        return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num)
+
+    def get_template_argument_type(self, num):
+        """Returns the CXType for the indicated template argument."""
+        return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
+
+    def get_template_argument_value(self, num):
+        """Returns the value of the indicated arg as a signed 64b integer."""
+        return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num)
+
+    def get_template_argument_unsigned_value(self, num):
+        """Returns the value of the indicated arg as an unsigned 64b integer."""
+        return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num)
+
     def get_children(self):
         """Return an iterator for accessing the children of this cursor."""
 
@@ -1450,9 +1521,59 @@
         res._tu = args[0]._tu
         return res
 
+class StorageClass(object):
+    """
+    Describes the storage class of a declaration
+    """
+
+    # The unique kind objects, index by id.
+    _kinds = []
+    _name_map = None
+
+    def __init__(self, value):
+        if value >= len(StorageClass._kinds):
+            StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1)
+        if StorageClass._kinds[value] is not None:
+            raise ValueError,'StorageClass already loaded'
+        self.value = value
+        StorageClass._kinds[value] = self
+        StorageClass._name_map = None
+
+    def from_param(self):
+        return self.value
+
+    @property
+    def name(self):
+        """Get the enumeration name of this storage class."""
+        if self._name_map is None:
+            self._name_map = {}
+            for key,value in StorageClass.__dict__.items():
+                if isinstance(value,StorageClass):
+                    self._name_map[value] = key
+        return self._name_map[self]
+
+    @staticmethod
+    def from_id(id):
+        if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
+            raise ValueError,'Unknown storage class %d' % id
+        return StorageClass._kinds[id]
+
+    def __repr__(self):
+        return 'StorageClass.%s' % (self.name,)
+
+StorageClass.INVALID = StorageClass(0)
+StorageClass.NONE = StorageClass(1)
+StorageClass.EXTERN = StorageClass(2)
+StorageClass.STATIC = StorageClass(3)
+StorageClass.PRIVATEEXTERN = StorageClass(4)
+StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5)
+StorageClass.AUTO = StorageClass(6)
+StorageClass.REGISTER = StorageClass(7)
+
+
 ### C++ access specifiers ###
 
-class AccessSpecifier(object):
+class AccessSpecifier(BaseEnumeration):
     """
     Describes the access of a C++ class member
     """
@@ -1461,34 +1582,9 @@
     _kinds = []
     _name_map = None
 
-    def __init__(self, value):
-        if value >= len(AccessSpecifier._kinds):
-            AccessSpecifier._kinds += [None] * (value - len(AccessSpecifier._kinds) + 1)
-        if AccessSpecifier._kinds[value] is not None:
-            raise ValueError,'AccessSpecifier already loaded'
-        self.value = value
-        AccessSpecifier._kinds[value] = self
-        AccessSpecifier._name_map = None
-
     def from_param(self):
         return self.value
 
-    @property
-    def name(self):
-        """Get the enumeration name of this access specifier."""
-        if self._name_map is None:
-            self._name_map = {}
-            for key,value in AccessSpecifier.__dict__.items():
-                if isinstance(value,AccessSpecifier):
-                    self._name_map[value] = key
-        return self._name_map[self]
-
-    @staticmethod
-    def from_id(id):
-        if id >= len(AccessSpecifier._kinds) or not AccessSpecifier._kinds[id]:
-            raise ValueError,'Unknown access specifier %d' % id
-        return AccessSpecifier._kinds[id]
-
     def __repr__(self):
         return 'AccessSpecifier.%s' % (self.name,)
 
@@ -1500,7 +1596,7 @@
 
 ### Type Kinds ###
 
-class TypeKind(object):
+class TypeKind(BaseEnumeration):
     """
     Describes the kind of type.
     """
@@ -1509,39 +1605,11 @@
     _kinds = []
     _name_map = None
 
-    def __init__(self, value):
-        if value >= len(TypeKind._kinds):
-            TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
-        if TypeKind._kinds[value] is not None:
-            raise ValueError,'TypeKind already loaded'
-        self.value = value
-        TypeKind._kinds[value] = self
-        TypeKind._name_map = None
-
-    def from_param(self):
-        return self.value
-
-    @property
-    def name(self):
-        """Get the enumeration name of this cursor kind."""
-        if self._name_map is None:
-            self._name_map = {}
-            for key,value in TypeKind.__dict__.items():
-                if isinstance(value,TypeKind):
-                    self._name_map[value] = key
-        return self._name_map[self]
-
     @property
     def spelling(self):
         """Retrieve the spelling of this TypeKind."""
         return conf.lib.clang_getTypeKindSpelling(self.value)
 
-    @staticmethod
-    def from_id(id):
-        if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
-            raise ValueError,'Unknown type kind %d' % id
-        return TypeKind._kinds[id]
-
     def __repr__(self):
         return 'TypeKind.%s' % (self.name,)
 
@@ -1594,43 +1662,16 @@
 TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
 TypeKind.MEMBERPOINTER = TypeKind(117)
 
-class RefQualifierKind(object):
+class RefQualifierKind(BaseEnumeration):
     """Describes a specific ref-qualifier of a type."""
 
     # The unique kind objects, indexed by id.
     _kinds = []
     _name_map = None
 
-    def __init__(self, value):
-        if value >= len(RefQualifierKind._kinds):
-            num_kinds = value - len(RefQualifierKind._kinds) + 1
-            RefQualifierKind._kinds += [None] * num_kinds
-        if RefQualifierKind._kinds[value] is not None:
-            raise ValueError, 'RefQualifierKind already loaded'
-        self.value = value
-        RefQualifierKind._kinds[value] = self
-        RefQualifierKind._name_map = None
-
     def from_param(self):
         return self.value
 
-    @property
-    def name(self):
-        """Get the enumeration name of this kind."""
-        if self._name_map is None:
-            self._name_map = {}
-            for key, value in RefQualifierKind.__dict__.items():
-                if isinstance(value, RefQualifierKind):
-                    self._name_map[value] = key
-        return self._name_map[self]
-
-    @staticmethod
-    def from_id(id):
-        if (id >= len(RefQualifierKind._kinds) or
-                RefQualifierKind._kinds[id] is None):
-            raise ValueError, 'Unknown type kind %d' % id
-        return RefQualifierKind._kinds[id]
-
     def __repr__(self):
         return 'RefQualifierKind.%s' % (self.name,)
 
@@ -2973,6 +3014,11 @@
    _CXString,
    _CXString.from_result),
 
+  ("clang_Cursor_getMangling",
+   [Cursor],
+   _CXString,
+   _CXString.from_result),
+
 # ("clang_getCXTUResourceUsage",
 #  [TranslationUnit],
 #  CXTUResourceUsage),
@@ -3300,6 +3346,27 @@
    Cursor,
    Cursor.from_result),
 
+  ("clang_Cursor_getNumTemplateArguments",
+   [Cursor],
+   c_int),
+
+  ("clang_Cursor_getTemplateArgumentKind",
+   [Cursor, c_uint],
+   TemplateArgumentKind.from_id),
+
+  ("clang_Cursor_getTemplateArgumentType",
+   [Cursor, c_uint],
+   Type,
+   Type.from_result),
+
+  ("clang_Cursor_getTemplateArgumentValue",
+   [Cursor, c_uint],
+   c_longlong),
+
+  ("clang_Cursor_getTemplateArgumentUnsignedValue",
+   [Cursor, c_uint],
+   c_ulonglong),
+
   ("clang_Cursor_isBitField",
    [Cursor],
    bool),
diff --git a/bindings/python/tests/cindex/test_cursor.py b/bindings/python/tests/cindex/test_cursor.py
index 4315045..a5224aa 100644
--- a/bindings/python/tests/cindex/test_cursor.py
+++ b/bindings/python/tests/cindex/test_cursor.py
@@ -1,6 +1,8 @@
+import ctypes
 import gc
 
 from clang.cindex import CursorKind
+from clang.cindex import TemplateArgumentKind
 from clang.cindex import TranslationUnit
 from clang.cindex import TypeKind
 from .util import get_cursor
@@ -244,6 +246,48 @@
     assert arguments[0].spelling == "i"
     assert arguments[1].spelling == "j"
 
+kTemplateArgTest = """\
+        template <int kInt, typename T, bool kBool>
+        void foo();
+
+        template<>
+        void foo<-7, float, true>();
+    """
+
+def test_get_num_template_arguments():
+    tu = get_tu(kTemplateArgTest, lang='cpp')
+    foos = get_cursors(tu, 'foo')
+
+    assert foos[1].get_num_template_arguments() == 3
+
+def test_get_template_argument_kind():
+    tu = get_tu(kTemplateArgTest, lang='cpp')
+    foos = get_cursors(tu, 'foo')
+
+    assert foos[1].get_template_argument_kind(0) == TemplateArgumentKind.INTEGRAL
+    assert foos[1].get_template_argument_kind(1) == TemplateArgumentKind.TYPE
+    assert foos[1].get_template_argument_kind(2) == TemplateArgumentKind.INTEGRAL
+
+def test_get_template_argument_type():
+    tu = get_tu(kTemplateArgTest, lang='cpp')
+    foos = get_cursors(tu, 'foo')
+
+    assert foos[1].get_template_argument_type(1).kind == TypeKind.FLOAT
+
+def test_get_template_argument_value():
+    tu = get_tu(kTemplateArgTest, lang='cpp')
+    foos = get_cursors(tu, 'foo')
+
+    assert foos[1].get_template_argument_value(0) == -7
+    assert foos[1].get_template_argument_value(2) == True
+
+def test_get_template_argument_unsigned_value():
+    tu = get_tu(kTemplateArgTest, lang='cpp')
+    foos = get_cursors(tu, 'foo')
+
+    assert foos[1].get_template_argument_unsigned_value(0) == 2 ** 32 - 7
+    assert foos[1].get_template_argument_unsigned_value(2) == True
+
 def test_referenced():
     tu = get_tu('void foo(); void bar() { foo(); }')
     foo = get_cursor(tu, 'foo')
@@ -252,3 +296,17 @@
         if c.kind == CursorKind.CALL_EXPR:
             assert c.referenced.spelling == foo.spelling
             break
+
+def test_mangled_name():
+    kInputForMangling = """\
+    int foo(int, int);
+    """
+    tu = get_tu(kInputForMangling, lang='cpp')
+    foo = get_cursor(tu, 'foo')
+
+    # Since libclang does not link in targets, we cannot pass a triple to it
+    # and force the target. To enable this test to pass on all platforms, accept
+    # all valid manglings.
+    # [c-index-test handles this by running the source through clang, emitting
+    #  an AST file and running libclang on that AST file]
+    assert foo.mangled_name in ('_Z3fooii', '__Z3fooii', '?foo@@YAHHH')
diff --git a/cmake/modules/ClangConfig.cmake b/cmake/modules/ClangConfig.cmake
new file mode 100644
index 0000000..f052bb9
--- /dev/null
+++ b/cmake/modules/ClangConfig.cmake
@@ -0,0 +1,8 @@
+# This file allows users to call find_package(Clang) and pick up our targets.
+
+# Clang doesn't have any CMake configuration settings yet because it mostly
+# uses LLVM's. When it does, we should move this file to ClangConfig.cmake.in
+# and call configure_file() on it.
+
+# Provide all our library targets to users.
+include("${CMAKE_CURRENT_LIST_DIR}/ClangTargets.cmake")
diff --git a/docs/AddressSanitizer.rst b/docs/AddressSanitizer.rst
index 93a6a0e..122b31a 100644
--- a/docs/AddressSanitizer.rst
+++ b/docs/AddressSanitizer.rst
@@ -165,9 +165,9 @@
     # Disable out-of-bound checks for global:
     global:bad_array
     # Disable out-of-bound checks for global instances of a given class ...
-    type:class.Namespace::BadClassName
+    type:Namespace::BadClassName
     # ... or a given struct. Use wildcard to deal with anonymous namespace.
-    type:struct.Namespace2::*::BadStructName
+    type:Namespace2::*::BadStructName
     # Disable initialization-order checks for globals:
     global:bad_init_global=init
     type:*BadInitClassSubstring*=init
diff --git a/docs/ClangFormat.rst b/docs/ClangFormat.rst
index 86c5ec5..45ea327 100644
--- a/docs/ClangFormat.rst
+++ b/docs/ClangFormat.rst
@@ -96,8 +96,8 @@
 
 .. code-block:: vim
 
-  map <C-K> :pyf <path-to-this-file>/clang-format.py<CR>
-  imap <C-K> <ESC>:pyf <path-to-this-file>/clang-format.py<CR>i
+  map <C-K> :pyf <path-to-this-file>/clang-format.py<cr>
+  imap <C-K> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
 
 The first line enables :program:`clang-format` for NORMAL and VISUAL mode, the
 second line adds support for INSERT mode. Change "C-K" to another binding if
diff --git a/docs/ClangFormatStyleOptions.rst b/docs/ClangFormatStyleOptions.rst
index 07febaf..cef3f24 100644
--- a/docs/ClangFormatStyleOptions.rst
+++ b/docs/ClangFormatStyleOptions.rst
@@ -33,6 +33,43 @@
   # A comment.
   ...
 
+The configuration file can consist of several sections each having different
+``Language:`` parameter denoting the programming language this section of the
+configuration is targeted at. See the description of the **Language** option
+below for the list of supported languages. The first section may have no
+language set, it will set the default style options for all lanugages.
+Configuration sections for specific language will override options set in the
+default section.
+
+When :program:`clang-format` formats a file, it auto-detects the language using
+the file name. When formatting standard input or a file that doesn't have the
+extension corresponding to its language, ``-assume-filename=`` option can be
+used to override the file name :program:`clang-format` uses to detect the
+language.
+
+An example of a configuration file for multiple languages:
+
+.. code-block:: yaml
+
+  ---
+  # We'll use defaults from the LLVM style, but with 4 columns indentation.
+  BasedOnStyle: LLVM
+  IndentWidth: 4
+  ---
+  Language: Cpp
+  # Force pointers to the type for C++.
+  DerivePointerAlignment: false
+  PointerAlignment: Left
+  ---
+  Language: JavaScript
+  # Use 100 columns for JS.
+  ColumnLimit: 100
+  ---
+  Language: Proto
+  # Don't format .proto files.
+  DisableFormat: true
+  ...
+
 An easy way to get a valid ``.clang-format`` file containing all configuration
 options of a certain predefined style is:
 
@@ -48,6 +85,24 @@
   -style='{key1: value1, key2: value2, ...}'
 
 
+Disabling Formatting on a Piece of Code
+=======================================
+
+Clang-format understands also special comments that switch formatting in a
+delimited range. The code between a comment ``// clang-format off`` or
+``/* clang-format off */`` up to a comment ``// clang-format on`` or
+``/* clang-format on */`` will not be formatted. The comments themselves
+will be formatted (aligned) normally.
+
+.. code-block:: c++
+
+  int formatted_code;
+  // clang-format off
+      void    unformatted_code  ;
+  // clang-format on
+  void formatted_code_again;
+
+
 Configuring Style in Code
 =========================
 
@@ -111,6 +166,9 @@
 
   E.g., this allows ``if (a) { return; }`` to be put on a single line.
 
+**AllowShortCaseLabelsOnASingleLine** (``bool``)
+  If ``true``, short case labels will be contracted to a single line.
+
 **AllowShortFunctionsOnASingleLine** (``ShortFunctionStyle``)
   Dependent on the value, ``int f() { return 0; }`` can be put
   on a single line.
@@ -133,6 +191,13 @@
   If ``true``, ``while (true) continue;`` can be put on a
   single line.
 
+**AlwaysBreakAfterDefinitionReturnType** (``bool``)
+  If ``true``, always break after function definition return types.
+
+  More truthfully called 'break before the identifier following the type
+  in a function definition'. PenaltyReturnTypeOnItsOwnLine becomes
+  irrelevant.
+
 **AlwaysBreakBeforeMultilineStrings** (``bool``)
   If ``true``, always break before multiline string literals.
 
@@ -140,12 +205,26 @@
   If ``true``, always break after the ``template<...>`` of a
   template declaration.
 
-**BinPackParameters** (``bool``)
-  If ``false``, a function call's or function definition's parameters
-  will either all be on the same line or will have one line each.
+**BinPackArguments** (``bool``)
+  If ``false``, a function call's arguments will either be all on the
+  same line or will have one line each.
 
-**BreakBeforeBinaryOperators** (``bool``)
-  If ``true``, binary operators will be placed after line breaks.
+**BinPackParameters** (``bool``)
+  If ``false``, a function declaration's or function definition's
+  parameters will either all be on the same line or will have one line each.
+
+**BreakBeforeBinaryOperators** (``BinaryOperatorStyle``)
+  The way to wrap binary operators.
+
+  Possible values:
+
+  * ``BOS_None`` (in configuration: ``None``)
+    Break after operators.
+  * ``BOS_NonAssignment`` (in configuration: ``NonAssignment``)
+    Break before operators that aren't assignments.
+  * ``BOS_All`` (in configuration: ``All``)
+    Break before operators.
+
 
 **BreakBeforeBraces** (``BraceBreakingStyle``)
   The brace breaking style to use.
@@ -158,7 +237,7 @@
     Like ``Attach``, but break before braces on function, namespace and
     class definitions.
   * ``BS_Stroustrup`` (in configuration: ``Stroustrup``)
-    Like ``Attach``, but break before function definitions.
+    Like ``Attach``, but break before function definitions, and 'else'.
   * ``BS_Allman`` (in configuration: ``Allman``)
     Always break before braces.
   * ``BS_GNU`` (in configuration: ``GNU``)
@@ -267,6 +346,8 @@
     Do not use.
   * ``LK_Cpp`` (in configuration: ``Cpp``)
     Should be used for C, C++, ObjectiveC, ObjectiveC++.
+  * ``LK_Java`` (in configuration: ``Java``)
+    Should be used for Java.
   * ``LK_JavaScript`` (in configuration: ``JavaScript``)
     Should be used for JavaScript.
   * ``LK_Proto`` (in configuration: ``Proto``)
@@ -290,6 +371,9 @@
     Indent in all namespaces.
 
 
+**ObjCBlockIndentWidth** (``unsigned``)
+  The number of characters to use for indentation of ObjC blocks.
+
 **ObjCSpaceAfterProperty** (``bool``)
   Add a space after ``@property`` in Objective-C, i.e. use
   ``\@property (readonly)`` instead of ``\@property(readonly)``.
@@ -330,6 +414,9 @@
     Align pointer in the middle.
 
 
+**SpaceAfterCStyleCast** (``bool``)
+  If ``true``, a space may be inserted after C style casts.
+
 **SpaceBeforeAssignmentOperators** (``bool``)
   If ``false``, spaces will be removed before assignment operators.
 
@@ -374,6 +461,9 @@
 **SpacesInParentheses** (``bool``)
   If ``true``, spaces will be inserted after '(' and before ')'.
 
+**SpacesInSquareBrackets** (``bool``)
+  If ``true``, spaces will be inserted after '[' and before ']'.
+
 **Standard** (``LanguageStandard``)
   Format compatible with this standard, e.g. use
   ``A<A<int> >`` instead of ``A<A<int>>`` for LS_Cpp03.
diff --git a/docs/CrossCompilation.rst b/docs/CrossCompilation.rst
index 89f8777..fd42856 100644
--- a/docs/CrossCompilation.rst
+++ b/docs/CrossCompilation.rst
@@ -201,4 +201,3 @@
 The same is true if you're compiling for different ABIs, like ``gnueabi``
 and ``androideabi``, and might even link and run, but produce run-time
 errors, which are much harder to track down and fix.
-
diff --git a/docs/InternalsManual.rst b/docs/InternalsManual.rst
index 8e047db..50a1943 100644
--- a/docs/InternalsManual.rst
+++ b/docs/InternalsManual.rst
@@ -1396,10 +1396,7 @@
 .. code-block:: c++
 
   Stmt *FooBody = ...
-  CFG *FooCFG = CFG::buildCFG(FooBody);
-
-It is the responsibility of the caller of ``CFG::buildCFG`` to ``delete`` the
-returned ``CFG*`` when the CFG is no longer needed.
+  std::unique_ptr<CFG> FooCFG = CFG::buildCFG(FooBody);
 
 Along with providing an interface to iterate over its ``CFGBlocks``, the
 ``CFG`` class also provides methods that are useful for debugging and
diff --git a/docs/LanguageExtensions.rst b/docs/LanguageExtensions.rst
index 35f759f..ae298af 100644
--- a/docs/LanguageExtensions.rst
+++ b/docs/LanguageExtensions.rst
@@ -109,6 +109,36 @@
 the same name.  For instance, ``__cxx_rvalue_references__`` can be used instead
 of ``cxx_rvalue_references``.
 
+``__has_cpp_attribute``
+-----------------------
+
+This function-like macro takes a single argument that is the name of a
+C++11-style attribute. The argument can either be a single identifier, or a
+scoped identifier. If the attribute is supported, a nonzero value is returned.
+If the attribute is a standards-based attribute, this macro returns a nonzero
+value based on the year and month in which the attribute was voted into the
+working draft. If the attribute is not supported by the current compliation
+target, this macro evaluates to 0.  It can be used like this:
+
+.. code-block:: c++
+
+  #ifndef __has_cpp_attribute         // Optional of course.
+    #define __has_cpp_attribute(x) 0  // Compatibility with non-clang compilers.
+  #endif
+
+  ...
+  #if __has_cpp_attribute(clang::fallthrough)
+  #define FALLTHROUGH [[clang::fallthrough]]
+  #else
+  #define FALLTHROUGH
+  #endif
+  ...
+
+The attribute identifier (but not scope) can also be specified with a preceding
+and following ``__`` (double underscore) to avoid interference from a macro with
+the same name.  For instance, ``gnu::__const__`` can be used instead of
+``gnu::const``.
+
 ``__has_attribute``
 -------------------
 
@@ -357,23 +387,27 @@
 dash indicates that an operation is not accepted according to a corresponding
 specification.
 
-============================== ====== ======= === ====
-         Opeator               OpenCL AltiVec GCC NEON
-============================== ====== ======= === ====
-[]                              yes     yes   yes  --
-unary operators +, --           yes     yes   yes  --
-++, -- --                       yes     yes   yes  --
-+,--,*,/,%                      yes     yes   yes  --
-bitwise operators &,|,^,~       yes     yes   yes  --
->>,<<                           yes     yes   yes  --
-!, &&, ||                       no      --    --   --
-==, !=, >, <, >=, <=            yes     yes   --   --
-=                               yes     yes   yes yes
-:?                              yes     --    --   --
-sizeof                          yes     yes   yes yes
-============================== ====== ======= === ====
+============================== ======= ======= ======= =======
+         Opeator               OpenCL  AltiVec   GCC    NEON
+============================== ======= ======= ======= =======
+[]                               yes     yes     yes     --
+unary operators +, --            yes     yes     yes     --
+++, -- --                        yes     yes     yes     --
++,--,*,/,%                       yes     yes     yes     --
+bitwise operators &,|,^,~        yes     yes     yes     --
+>>,<<                            yes     yes     yes     --
+!, &&, ||                        yes     --      --      --
+==, !=, >, <, >=, <=             yes     yes     --      --
+=                                yes     yes     yes     yes
+:?                               yes     --      --      --
+sizeof                           yes     yes     yes     yes
+C-style cast                     yes     yes     yes     no
+reinterpret_cast                 yes     no      yes     no
+static_cast                      yes     no      yes     no
+const_cast                       no      no      no      no
+============================== ======= ======= ======= =======
 
-See also :ref:`langext-__builtin_shufflevector`.
+See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
 
 Messages on ``deprecated`` and ``unavailable`` Attributes
 =========================================================
@@ -454,6 +488,13 @@
 language features are available as an extension when compiling for a standard
 which does not provide them.  The features which can be tested are listed here.
 
+Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
+These are macros with names of the form ``__cpp_<feature_name>``, and are
+intended to be a portable way to query the supported features of the compiler.
+See `the C++ status page <http://clang.llvm.org/cxx_status.html#ts>`_ for
+information on the version of SD-6 supported by each Clang release, and the
+macros provided by that revision of the recommendations.
+
 C++98
 -----
 
@@ -747,6 +788,13 @@
 ``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
 for default initializers in aggregate members is enabled.
 
+C++1y digit separators
+^^^^^^^^^^^^^^^^^^^^^^
+
+Use ``__cpp_digit_separators`` to determine if support for digit separators
+using single quotes (for instance, ``10'000``) is enabled. At this time, there
+is no corresponding ``__has_feature`` name
+
 C++1y generalized lambda capture
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
@@ -815,7 +863,16 @@
 Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
 if support for atomic types using ``_Atomic`` is enabled.  Clang also provides
 :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
-the ``<stdatomic.h>`` operations on ``_Atomic`` types.
+the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
+``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
+is available.
+
+Clang will use the system's ``<stdatomic.h>`` header when one is available, and
+will otherwise use its own. When using its own, implementations of the atomic
+operations are provided as macros. In the cases where C11 also requires a real
+function, this header provides only the declaration of that function (along
+with a shadowing macro implementation), and you must link to a library which
+provides a definition of the function if you use it instead of the macro.
 
 C11 generic selections
 ^^^^^^^^^^^^^^^^^^^^^^
@@ -1224,8 +1281,9 @@
 Clang supports a number of builtin library functions with the same syntax as
 GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
 ``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
-``__sync_fetch_and_add``, etc.  In addition to the GCC builtins, Clang supports
-a number of builtins that GCC does not, which are listed here.
+``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc.  In addition to
+the GCC builtins, Clang supports a number of builtins that GCC does not, which
+are listed here.
 
 Please note that Clang does not and will not support all of the GCC builtins
 for vector operations.  Instead of using builtins, you should use the functions
@@ -1235,6 +1293,42 @@
 <langext-vectors>` instead of builtins, in order to reduce the number of
 builtins that we need to implement.
 
+``__builtin_assume``
+------------------------------
+
+``__builtin_assume`` is used to provide the optimizer with a boolean
+invariant that is defined to be true.
+
+**Syntax**:
+
+.. code-block:: c++
+
+  __builtin_assume(bool)
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  int foo(int x) {
+    __builtin_assume(x != 0);
+
+    // The optimizer may short-circuit this check using the invariant.
+    if (x == 0)
+      return do_something();
+
+    return do_something_else();
+  }
+
+**Description**:
+
+The boolean argument to this function is defined to be true. The optimizer may
+analyze the form of the expression provided as the argument and deduce from
+that information used to optimize the program. If the condition is violated
+during execution, the behavior is undefined. The argument itself is never
+evaluated, so any side effects of the expression will be discarded.
+
+Query for this feature with ``__has_builtin(__builtin_assume)``.
+
 ``__builtin_readcyclecounter``
 ------------------------------
 
@@ -1324,6 +1418,8 @@
 
 Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
 
+.. _langext-__builtin_convertvector:
+
 ``__builtin_convertvector``
 ---------------------------
 
@@ -1354,7 +1450,7 @@
   // convert from a vector of 4 shorts to a vector of 4 floats.
   __builtin_convertvector(vs, vector4float)
   // equivalent to:
-  (vector4float) { (float) vf[0], (float) vf[1], (float) vf[2], (float) vf[3] }
+  (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
 
 **Description**:
 
@@ -1554,12 +1650,14 @@
 Clang provides a set of builtins which are intended to be used to implement
 C11's ``<stdatomic.h>`` header.  These builtins provide the semantics of the
 ``_explicit`` form of the corresponding C11 operation, and are named with a
-``__c11_`` prefix.  The supported operations are:
+``__c11_`` prefix.  The supported operations, and the differences from
+the corresponding C11 operations, are:
 
 * ``__c11_atomic_init``
 * ``__c11_atomic_thread_fence``
 * ``__c11_atomic_signal_fence``
-* ``__c11_atomic_is_lock_free``
+* ``__c11_atomic_is_lock_free`` (The argument is the size of the
+  ``_Atomic(...)`` object, instead of its address)
 * ``__c11_atomic_store``
 * ``__c11_atomic_load``
 * ``__c11_atomic_exchange``
@@ -1571,6 +1669,11 @@
 * ``__c11_atomic_fetch_or``
 * ``__c11_atomic_fetch_xor``
 
+The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
+``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
+provided, with values corresponding to the enumerators of C11's
+``memory_order`` enumeration.
+
 Low-level ARM exclusive memory builtins
 ---------------------------------------
 
@@ -1780,15 +1883,17 @@
 these two instantiations, ``twice`` will be optimized (because its definition
 was outside the region) and ``thrice`` will not be optimized.
 
-.. _langext-pragma-loop:
-
 Extensions for loop hint optimizations
 ======================================
 
 The ``#pragma clang loop`` directive is used to specify hints for optimizing the
 subsequent for, while, do-while, or c++11 range-based for loop. The directive
-provides options for vectorization and interleaving. Loop hints can be specified
-before any loop and will be ignored if the optimization is not safe to apply.
+provides options for vectorization, interleaving, and unrolling. Loop hints can
+be specified before any loop and will be ignored if the optimization is not safe
+to apply.
+
+Vectorization and Interleaving
+------------------------------
 
 A vectorized loop performs multiple iterations of the original loop
 in parallel using vector instructions. The instruction set of the target
@@ -1831,6 +1936,46 @@
 Specifying a width/count of 1 disables the optimization, and is equivalent to
 ``vectorize(disable)`` or ``interleave(disable)``.
 
+Loop Unrolling
+--------------
+
+Unrolling a loop reduces the loop control overhead and exposes more
+opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
+eliminates the loop and replaces it with an enumerated sequence of loop
+iterations. Full unrolling is only possible if the loop trip count is known at
+compile time. Partial unrolling replicates the loop body within the loop and
+reduces the trip count.
+
+If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
+loop if the trip count is known at compile time. If the loop count is not known
+or the fully unrolled code size is greater than the limit specified by the
+`-pragma-unroll-threshold` command line option the loop will be partially
+unrolled subject to the same limit.
+
+.. code-block:: c++
+
+  #pragma clang loop unroll(full)
+  for(...) {
+    ...
+  }
+
+The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
+_value_ is a positive integer. If this value is greater than the trip count the
+loop will be fully unrolled. Otherwise the loop is partially unrolled subject
+to the `-pragma-unroll-threshold` limit.
+
+.. code-block:: c++
+
+  #pragma clang loop unroll_count(8)
+  for(...) {
+    ...
+  }
+
+Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
+
+Additional Information
+----------------------
+
 For convenience multiple loop hints can be specified on a single line.
 
 .. code-block:: c++
diff --git a/docs/LibASTMatchersReference.html b/docs/LibASTMatchersReference.html
index 4988053..e70d1ec 100644
--- a/docs/LibASTMatchersReference.html
+++ b/docs/LibASTMatchersReference.html
@@ -246,6 +246,16 @@
 </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('linkageSpecDecl0')"><a name="linkageSpecDecl0Anchor">linkageSpecDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LinkageSpecDecl.html">LinkageSpecDecl</a>&gt;...</td></tr>
+<tr><td colspan="4" class="doc" id="linkageSpecDecl0"><pre>Matches a declaration of a linkage specification.
+
+Given
+  extern "C" {}
+linkageSpecDecl()
+  matches "extern "C" {}"
+</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('methodDecl0')"><a name="methodDecl0Anchor">methodDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;...</td></tr>
 <tr><td colspan="4" class="doc" id="methodDecl0"><pre>Matches method declarations.
 
@@ -297,6 +307,16 @@
 </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.
 
@@ -319,6 +339,25 @@
   matches using X::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('usingDirectiveDecl0')"><a name="usingDirectiveDecl0Anchor">usingDirectiveDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UsingDirectiveDecl.html">UsingDirectiveDecl</a>&gt;...</td></tr>
+<tr><td colspan="4" class="doc" id="usingDirectiveDecl0"><pre>Matches using namespace declarations.
+
+Given
+  namespace X { int x; }
+  using namespace X;
+usingDirectiveDecl()
+  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.
 
@@ -355,6 +394,14 @@
 </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('CUDAKernelCallExpr0')"><a name="CUDAKernelCallExpr0Anchor">CUDAKernelCallExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CUDAKernelCallExpr.html">CUDAKernelCallExpr</a>&gt;...</td></tr>
+<tr><td colspan="4" class="doc" id="CUDAKernelCallExpr0"><pre>Matches CUDA kernel call expression.
+
+Example matches,
+  kernel&lt;&lt;&lt;i,j&gt;&gt;&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('arraySubscriptExpr0')"><a name="arraySubscriptExpr0Anchor">arraySubscriptExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArraySubscriptExpr.html">ArraySubscriptExpr</a>&gt;...</td></tr>
 <tr><td colspan="4" class="doc" id="arraySubscriptExpr0"><pre>Matches array subscript expressions.
 
@@ -711,7 +758,7 @@
   int a[] = { 1, 2 };
   struct B { int x, y; };
   B b = { 5, 6 };
-initList()
+initListExpr()
   matches "{ 1, 2 }" and "{ 5, 6 }"
 </pre></td></tr>
 
@@ -876,6 +923,18 @@
 </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('substNonTypeTemplateParmExpr0')"><a name="substNonTypeTemplateParmExpr0Anchor">substNonTypeTemplateParmExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1SubstNonTypeTemplateParmExpr.html">SubstNonTypeTemplateParmExpr</a>&gt;...</td></tr>
+<tr><td colspan="4" class="doc" id="substNonTypeTemplateParmExpr0"><pre>Matches substitutions of non-type template parameters.
+
+Given
+  template &lt;int N&gt;
+  struct A { static const int n = N; };
+  struct B : public A&lt;42&gt; {};
+substNonTypeTemplateParmExpr()
+  matches "N" in the right-hand side of "static const int n = N;"
+</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('switchCase0')"><a name="switchCase0Anchor">switchCase</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1SwitchCase.html">SwitchCase</a>&gt;...</td></tr>
 <tr><td colspan="4" class="doc" id="switchCase0"><pre>Matches case and default statements inside switch statements.
 
@@ -980,6 +1039,17 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('templateArgument0')"><a name="templateArgument0Anchor">templateArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;...</td></tr>
+<tr><td colspan="4" class="doc" id="templateArgument0"><pre>Matches template arguments.
+
+Given
+  template &lt;typename T&gt; struct C {};
+  C&lt;int&gt; c;
+templateArgument()
+  matches 'int' in C&lt;int&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('typeLoc0')"><a name="typeLoc0Anchor">typeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;...</td></tr>
 <tr><td colspan="4" class="doc" id="typeLoc0"><pre>Matches TypeLocs in the clang AST.
 </pre></td></tr>
@@ -1269,6 +1339,7 @@
     int a[] = { 2, 3 }
     int b[42];
     int c[a[0]];
+  }
 variableArrayType()
   matches "int c[a[0]]"
 </pre></td></tr>
@@ -1381,26 +1452,6 @@
 </pre></td></tr>
 
 
-<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('hasOverloadedOperatorName0')"><a name="hasOverloadedOperatorName0Anchor">hasOverloadedOperatorName</a></td><td>StringRef Name</td></tr>
-<tr><td colspan="4" class="doc" id="hasOverloadedOperatorName0"><pre>Matches overloaded operator names.
-
-Matches overloaded operator names specified in strings without the
-"operator" prefix: e.g. "&lt;&lt;".
-
-Given:
-  class A { int operator*(); };
-  const A &amp;operator&lt;&lt;(const A &amp;a, const A &amp;b);
-  A a;
-  a &lt;&lt; a;   &lt;-- This matches
-
-operatorCallExpr(hasOverloadedOperatorName("&lt;&lt;"))) matches the specified
-line and recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches
-the declaration of A.
-
-Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXOperatorCallExpr.html">CXXOperatorCallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;
-</pre></td></tr>
-
-
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('isConst0')"><a name="isConst0Anchor">isConst</a></td><td></td></tr>
 <tr><td colspan="4" class="doc" id="isConst0"><pre>Matches if the given method declaration is const.
 
@@ -1470,7 +1521,7 @@
 line and recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches
 the declaration of A.
 
-Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXOperatorCallExpr.html">CXXOperatorCallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXOperatorCallExpr.html">CXXOperatorCallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;
 </pre></td></tr>
 
 
@@ -1541,6 +1592,17 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ClassTemplateSpecializationDecl.html">ClassTemplateSpecializationDecl</a>&gt;</td><td class="name" onclick="toggle('templateArgumentCountIs0')"><a name="templateArgumentCountIs0Anchor">templateArgumentCountIs</a></td><td>unsigned N</td></tr>
+<tr><td colspan="4" class="doc" id="templateArgumentCountIs0"><pre>Matches if the number of template arguments equals N.
+
+Given
+  template&lt;typename T&gt; struct C {};
+  C&lt;int&gt; c;
+classTemplateSpecializationDecl(templateArgumentCountIs(1))
+  matches C&lt;int&gt;.
+</pre></td></tr>
+
+
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CompoundStmt.html">CompoundStmt</a>&gt;</td><td class="name" onclick="toggle('statementCountIs0')"><a name="statementCountIs0Anchor">statementCountIs</a></td><td>unsigned N</td></tr>
 <tr><td colspan="4" class="doc" id="statementCountIs0"><pre>Checks that a compound statement contains a specific number of
 child statements.
@@ -1601,10 +1663,55 @@
 </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('equalsNode0')"><a name="equalsNode0Anchor">equalsNode</a></td><td>Decl *Node</td></tr>
-<tr><td colspan="4" class="doc" id="equalsNode0"><pre>Matches if a node equals another node.
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('hasAttr0')"><a name="hasAttr0Anchor">hasAttr</a></td><td>attr::Kind AttrKind</td></tr>
+<tr><td colspan="4" class="doc" id="hasAttr0"><pre>Matches declaration that has a given attribute.
 
-Decl has pointer identity in the AST.
+Given
+  __attribute__((device)) void f() { ... }
+decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
+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('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('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.
+
+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>
 
 
@@ -1614,6 +1721,19 @@
 </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.
+
+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<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isPrivate0')"><a name="isPrivate0Anchor">isPrivate</a></td><td></td></tr>
 <tr><td colspan="4" class="doc" id="isPrivate0"><pre>Matches private C++ declarations.
 
@@ -1667,6 +1787,26 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('hasOverloadedOperatorName0')"><a name="hasOverloadedOperatorName0Anchor">hasOverloadedOperatorName</a></td><td>StringRef Name</td></tr>
+<tr><td colspan="4" class="doc" id="hasOverloadedOperatorName0"><pre>Matches overloaded operator names.
+
+Matches overloaded operator names specified in strings without the
+"operator" prefix: e.g. "&lt;&lt;".
+
+Given:
+  class A { int operator*(); };
+  const A &amp;operator&lt;&lt;(const A &amp;a, const A &amp;b);
+  A a;
+  a &lt;&lt; a;   &lt;-- This matches
+
+operatorCallExpr(hasOverloadedOperatorName("&lt;&lt;"))) matches the specified
+line and recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches
+the declaration of A.
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXOperatorCallExpr.html">CXXOperatorCallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;
+</pre></td></tr>
+
+
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('isDefinition2')"><a name="isDefinition2Anchor">isDefinition</a></td><td></td></tr>
 <tr><td colspan="4" class="doc" id="isDefinition2"><pre>Matches if a declaration has a body attached.
 
@@ -1682,6 +1822,17 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('isDeleted0')"><a name="isDeleted0Anchor">isDeleted</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isDeleted0"><pre>Matches deleted function declarations.
+
+Given:
+  void Func();
+  void DeletedFunc() = delete;
+functionDecl(isDeleted())
+  matches the declaration of DeletedFunc, but not Func.
+</pre></td></tr>
+
+
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('isExplicitTemplateSpecialization0')"><a name="isExplicitTemplateSpecialization0Anchor">isExplicitTemplateSpecialization</a></td><td></td></tr>
 <tr><td colspan="4" class="doc" id="isExplicitTemplateSpecialization0"><pre>Matches explicit template specializations of function, class, or
 static member variable template instantiations.
@@ -1768,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
@@ -1900,11 +2051,61 @@
 </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('equalsNode1')"><a name="equalsNode1Anchor">equalsNode</a></td><td>Stmt *Node</td></tr>
-<tr><td colspan="4" class="doc" id="equalsNode1"><pre>Matches if a node equals another node.
+<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.
 
-Stmt has pointer identity in the AST.
+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>
+
+
+<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.
+
+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>
 
 
@@ -1923,6 +2124,88 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('equalsIntegralValue0')"><a name="equalsIntegralValue0Anchor">equalsIntegralValue</a></td><td>std::string Value</td></tr>
+<tr><td colspan="4" class="doc" id="equalsIntegralValue0"><pre>Matches a TemplateArgument of integral type with a given value.
+
+Note that 'Value' is a string as the template argument's value is
+an arbitrary precision integer. 'Value' must be euqal to the canonical
+representation of that integral value in base 10.
+
+Given
+  template&lt;int T&gt; struct A {};
+  C&lt;42&gt; c;
+classTemplateSpecializationDecl(
+  hasAnyTemplateArgument(equalsIntegralValue("42")))
+  matches the implicit instantiation of C in C&lt;42&gt;.
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('isIntegral0')"><a name="isIntegral0Anchor">isIntegral</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isIntegral0"><pre>Matches a TemplateArgument that is an integral value.
+
+Given
+  template&lt;int T&gt; struct A {};
+  C&lt;42&gt; c;
+classTemplateSpecializationDecl(
+  hasAnyTemplateArgument(isIntegral()))
+  matches the implicit instantiation of C in C&lt;42&gt;
+  with isIntegral() matching 42.
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;</td><td class="name" onclick="toggle('templateArgumentCountIs1')"><a name="templateArgumentCountIs1Anchor">templateArgumentCountIs</a></td><td>unsigned N</td></tr>
+<tr><td colspan="4" class="doc" id="templateArgumentCountIs1"><pre>Matches if the number of template arguments equals N.
+
+Given
+  template&lt;typename T&gt; struct C {};
+  C&lt;int&gt; c;
+classTemplateSpecializationDecl(templateArgumentCountIs(1))
+  matches C&lt;int&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('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.
 
@@ -2550,7 +2833,7 @@
 
 Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
   class Y { public: void x(); };
-  void z() { Y y; y.x();
+  void z() { Y y; y.x(); }
 </pre></td></tr>
 
 
@@ -3448,6 +3731,7 @@
     void a(X b) {
       X &amp;x = b;
       const X &amp;y = b;
+    }
   };
 </pre></td></tr>
 
@@ -3582,6 +3866,18 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('refersToIntegralType0')"><a name="refersToIntegralType0Anchor">refersToIntegralType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr>
+<tr><td colspan="4" class="doc" id="refersToIntegralType0"><pre>Matches a TemplateArgument that referes to an integral type.
+
+Given
+  template&lt;int T&gt; struct A {};
+  C&lt;42&gt; c;
+classTemplateSpecializationDecl(
+  hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
+  matches the implicit instantiation of C in C&lt;42&gt;.
+</pre></td></tr>
+
+
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('refersToType0')"><a name="refersToType0Anchor">refersToType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr>
 <tr><td colspan="4" class="doc" id="refersToType0"><pre>Matches a TemplateArgument that refers to a certain type.
 
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/Modules.rst b/docs/Modules.rst
index ce1e717..1575ce6 100644
--- a/docs/Modules.rst
+++ b/docs/Modules.rst
@@ -2,10 +2,6 @@
 Modules
 =======
 
-.. warning::
-   The functionality described on this page is supported for C and
-   Objective-C. C++ support is experimental.
-
 .. contents::
    :local:
 
@@ -104,7 +100,7 @@
 
 Using Modules
 =============
-To enable modules, pass the command-line flag ``-fmodules`` [#]_. This will make any modules-enabled software libraries available as modules as well as introducing any modules-specific syntax. Additional `command-line parameters`_ are described in a separate section later.
+To enable modules, pass the command-line flag ``-fmodules``. This will make any modules-enabled software libraries available as modules as well as introducing any modules-specific syntax. Additional `command-line parameters`_ are described in a separate section later.
 
 Objective-C Import declaration
 ------------------------------
@@ -114,7 +110,7 @@
 
   @import std;
 
-The @import declaration above imports the entire contents of the ``std`` module (which would contain, e.g., the entire C or C++ standard library) and make its API available within the current translation unit. To import only part of a module, one may use dot syntax to specific a particular submodule, e.g.,
+The ``@import`` declaration above imports the entire contents of the ``std`` module (which would contain, e.g., the entire C or C++ standard library) and make its API available within the current translation unit. To import only part of a module, one may use dot syntax to specific a particular submodule, e.g.,
 
 .. parsed-literal::
 
@@ -140,6 +136,19 @@
 
   The automatic mapping of ``#include`` to ``import`` also solves an implementation problem: importing a module with a definition of some entity (say, a ``struct Point``) and then parsing a header containing another definition of ``struct Point`` would cause a redefinition error, even if it is the same ``struct Point``. By mapping ``#include`` to ``import``, the compiler can guarantee that it always sees just the already-parsed definition from the module.
 
+While building a module, ``#include_next`` is also supported, with one caveat.
+The usual behavior of ``#include_next`` is to search for the specified filename
+in the list of include paths, starting from the path *after* the one
+in which the current file was found.
+Because files listed in module maps are not found through include paths, a
+different strategy is used for ``#include_next`` directives in such files: the
+list of include paths is searched for the specified header name, to find the
+first include path that would refer to the current file. ``#include_next`` is
+interpreted as if the current file had been found in that path.
+If this search finds a file named by a module map, the ``#include_next``
+directive is translated into an import, just like for a ``#include``
+directive.``
+
 Module maps
 -----------
 The crucial link between modules and headers is described by a *module map*, which describes how a collection of existing headers maps on to the (logical) structure of a module. For example, one could imagine a module ``std`` covering the C standard library. Each of the C standard library headers (``<stdio.h>``, ``<stdlib.h>``, ``<math.h>``, etc.) would contribute to the ``std`` module, by placing their respective APIs into the corresponding submodule (``std.io``, ``std.lib``, ``std.math``, etc.). Having a list of the headers that are part of the ``std`` module allows the compiler to build the ``std`` module as a standalone entity, and having the mapping from header names to (sub)modules allows the automatic translation of ``#include`` directives to module imports.
@@ -163,13 +172,10 @@
 Command-line parameters
 -----------------------
 ``-fmodules``
-  Enable the modules feature (EXPERIMENTAL).
-
-``-fcxx-modules``
-  Enable the modules feature for C++ (EXPERIMENTAL and VERY BROKEN).
+  Enable the modules feature.
 
 ``-fmodule-maps``
-  Enable interpretation of module maps (EXPERIMENTAL). This option is implied by ``-fmodules``.
+  Enable interpretation of module maps. This option is implied by ``-fmodules``.
 
 ``-fmodules-cache-path=<directory>``
   Specify the path to the modules cache. If not provided, Clang will select a system-appropriate default.
@@ -201,6 +207,9 @@
 ``-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.
+
 Module Semantics
 ================
 
@@ -208,7 +217,7 @@
 
 .. note::
 
-  This behavior is currently only approximated when building a module. Entities within a submodule that has already been built are visible when building later submodules in that module. This can lead to fragile modules that depend on the build order used for the submodules of the module, and should not be relied upon.
+  This behavior is currently only approximated when building a module with submodules. Entities within a submodule that has already been built are visible when building later submodules in that module. This can lead to fragile modules that depend on the build order used for the submodules of the module, and should not be relied upon. This behavior is subject to change.
 
 As an example, in C, this implies that if two structs are defined in different submodules with the same name, those two types are distinct types (but may be *compatible* types if their definitions match. In C++, two structs defined with the same name in different submodules are the *same* type, and must be equivalent under C++'s One Definition Rule.
 
@@ -216,6 +225,8 @@
 
   Clang currently only performs minimal checking for violations of the One Definition Rule.
 
+If any submodule of a module is imported into any part of a program, the entire top-level module is considered to be part of the program. As a consequence of this, Clang may diagnose conflicts between an entity declared in an unimported submodule and an entity declared in the current translation unit, and Clang may inline or devirtualize based on knowledge from unimported submodules.
+
 Macros
 ------
 
@@ -238,6 +249,10 @@
 Module Map Language
 ===================
 
+.. warning::
+
+  The module map language is not currently guaranteed to be stable between major revisions of Clang.
+
 The module map language describes the mapping from header files to the
 logical structure of modules. To enable support for using a library as
 a module, one must write a ``module.modulemap`` file for that library. The
@@ -255,6 +270,12 @@
 .. parsed-literal::
 
   module std [system] [extern_c] {
+    module assert {
+      textual header "assert.h"
+      header "bits/assert-decls.h"
+      export *
+    }
+
     module complex {
       header "complex.h"
       export *
@@ -287,11 +308,11 @@
 
 .. parsed-literal::
 
-  ``config_macros`` ``export``     ``module``
+  ``config_macros`` ``export``     ``private``
   ``conflict``      ``framework``  ``requires``
-  ``exclude``       ``header``     ``private``
+  ``exclude``       ``header``     ``textual``
   ``explicit``      ``link``       ``umbrella``
-  ``extern``        ``use``
+  ``extern``        ``module``     ``use``
 
 Module map file
 ---------------
@@ -319,7 +340,7 @@
     ``explicit``:sub:`opt` ``framework``:sub:`opt` ``module`` *module-id* *attributes*:sub:`opt` '{' *module-member** '}'
     ``extern`` ``module`` *module-id* *string-literal*
 
-The *module-id* should consist of only a single *identifier*, which provides the name of the module being defined. Each module shall have a single definition. 
+The *module-id* should consist of only a single *identifier*, which provides the name of the module being defined. Each module shall have a single definition.
 
 The ``explicit`` qualifier can only be applied to a submodule, i.e., a module that is nested within another module. The contents of explicit submodules are only made available when the submodule itself was explicitly named in an import declaration or was re-exported from an imported module.
 
@@ -427,11 +448,11 @@
 .. parsed-literal::
 
   *header-declaration*:
-    ``umbrella``:sub:`opt` ``header`` *string-literal*
-    ``private`` ``header`` *string-literal*
+    ``private``:sub:`opt` ``textual``:sub:`opt` ``header`` *string-literal*
+    ``umbrella`` ``header`` *string-literal*
     ``exclude`` ``header`` *string-literal*
 
-A header declaration that does not contain ``exclude`` specifies a header that contributes to the enclosing module. Specifically, when the module is built, the named header will be parsed and its declarations will be (logically) placed into the enclosing submodule.
+A header declaration that does not contain ``exclude`` nor ``textual`` specifies a header that contributes to the enclosing module. Specifically, when the module is built, the named header will be parsed and its declarations will be (logically) placed into the enclosing submodule.
 
 A header with the ``umbrella`` specifier is called an umbrella header. An umbrella header includes all of the headers within its directory (and any subdirectories), and is typically used (in the ``#include`` world) to easily access the full API provided by a particular library. With modules, an umbrella header is a convenient shortcut that eliminates the need to write out ``header`` declarations for every library header. A given directory can only contain a single umbrella header.
 
@@ -443,14 +464,16 @@
 
 A header with the ``private`` specifier may not be included from outside the module itself.
 
-A header with the ``exclude`` specifier is excluded from the module. It will not be included when the module is built, nor will it be considered to be part of the module.
+A header with the ``textual`` specifier will not be included when the module is built, and will be textually included if it is named by a ``#include`` directive. However, it is considered to be part of the module for the purpose of checking *use-declaration*\s.
 
-**Example**: The C header ``assert.h`` is an excellent candidate for an excluded header, because it is meant to be included multiple times (possibly with different ``NDEBUG`` settings).
+A header with the ``exclude`` specifier is excluded from the module. It will not be included when the module is built, nor will it be considered to be part of the module, even if an ``umbrella`` header or directory would otherwise make it part of the module.
+
+**Example**: The C header ``assert.h`` is an excellent candidate for a textual header, because it is meant to be included multiple times (possibly with different ``NDEBUG`` settings). However, declarations within it should typically be split into a separate modular header.
 
 .. parsed-literal::
 
   module std [system] {
-    exclude header "assert.h"
+    textual header "assert.h"
   }
 
 A given header shall not be referenced by more than one *header-declaration*.
@@ -824,20 +847,17 @@
 
 Future Directions
 =================
-Modules is an experimental feature, and there is much work left to do to make it both real and useful. Here are a few ideas:
+Modules support is under active development, and there are many opportunities remaining to improve it. Here are a few ideas:
 
 **Detect unused module imports**
   Unlike with ``#include`` directives, it should be fairly simple to track whether a directly-imported module has ever been used. By doing so, Clang can emit ``unused import`` or ``unused #include`` diagnostics, including Fix-Its to remove the useless imports/includes.
 
 **Fix-Its for missing imports**
-  It's fairly common for one to make use of some API while writing code, only to get a compiler error about "unknown type" or "no function named" because the corresponding header has not been included. Clang should detect such cases and auto-import the required module (with a Fix-It!).
+  It's fairly common for one to make use of some API while writing code, only to get a compiler error about "unknown type" or "no function named" because the corresponding header has not been included. Clang can detect such cases and auto-import the required module, but should provide a Fix-It to add the import.
 
 **Improve modularize**
   The modularize tool is both extremely important (for deployment) and extremely crude. It needs better UI, better detection of problems (especially for C++), and perhaps an assistant mode to help write module maps for you.
 
-**C++ Support**
-  Modules clearly has to work for C++, or we'll never get to use it for the Clang code base.
-
 Where To Learn More About Modules
 =================================
 The Clang source code provides additional information about modules:
@@ -859,8 +879,6 @@
 
 .. [#] Automatic linking against the libraries of modules requires specific linker support, which is not widely available.
 
-.. [#] Modules are only available in C and Objective-C; a separate flag ``-fcxx-modules`` enables modules support for C++, which is even more experimental and broken.
-
 .. [#] There are certain anti-patterns that occur in headers, particularly system headers, that cause problems for modules. The section `Modularizing a Platform`_ describes some of them.
 
 .. [#] The second instance is actually a new thread within the current process, not a separate process. However, the original compiler instance is blocked on the execution of this thread.
diff --git a/docs/RAVFrontendAction.rst b/docs/RAVFrontendAction.rst
index 2f60ce9..ec5d5d5 100644
--- a/docs/RAVFrontendAction.rst
+++ b/docs/RAVFrontendAction.rst
@@ -25,9 +25,10 @@
 
       class FindNamedClassAction : public clang::ASTFrontendAction {
       public:
-        virtual clang::ASTConsumer *CreateASTConsumer(
+        virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
           clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
-          return new FindNamedClassConsumer;
+          return std::unique_ptr<clang::ASTConsumer>(
+              new FindNamedClassConsumer);
         }
       };
 
@@ -111,9 +112,10 @@
 
 ::
 
-      virtual clang::ASTConsumer *CreateASTConsumer(
+      virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
         clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
-        return new FindNamedClassConsumer(&Compiler.getASTContext());
+        return std::unique_ptr<clang::ASTConsumer>(
+            new FindNamedClassConsumer(&Compiler.getASTContext()));
       }
 
 Now that the ASTContext is available in the RecursiveASTVisitor, we can
@@ -185,9 +187,10 @@
 
       class FindNamedClassAction : public clang::ASTFrontendAction {
       public:
-        virtual clang::ASTConsumer *CreateASTConsumer(
+        virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
           clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
-          return new FindNamedClassConsumer(&Compiler.getASTContext());
+          return std::unique_ptr<clang::ASTConsumer>(
+              new FindNamedClassConsumer(&Compiler.getASTContext()));
         }
       };
 
diff --git a/docs/ReleaseNotes.rst b/docs/ReleaseNotes.rst
index 5ff136e..daab804 100644
--- a/docs/ReleaseNotes.rst
+++ b/docs/ReleaseNotes.rst
@@ -1,6 +1,6 @@
-=======================
-Clang 3.5 Release Notes
-=======================
+=====================================
+Clang 3.6 (In-Progress) Release Notes
+=====================================
 
 .. contents::
    :local:
@@ -8,11 +8,17 @@
 
 Written by the `LLVM Team <http://llvm.org/>`_
 
+.. warning::
+
+   These are in-progress notes for the upcoming Clang 3.6 release. You may
+   prefer the `Clang 3.5 Release Notes
+   <http://llvm.org/releases/3.5/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.5. Here we
+frontend, part of the LLVM Compiler Infrastructure, release 3.6. 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
@@ -30,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.5?
+What's New in Clang 3.6?
 ========================
 
 Some of the major new features and improvements to Clang are listed
@@ -41,213 +47,100 @@
 Major New Features
 ------------------
 
-- Clang uses the new MingW ABI
-  GCC 4.7 changed the mingw ABI. Clang 3.4 and older use the GCC 4.6
-  ABI. Clang 3.5 and newer use the GCC 4.7 abi.
+- A big one.
 
-- The __has_attribute feature test is now target-aware. Older versions of Clang
-  would return true when the attribute spelling was known, regardless of whether
-  the attribute was available to the specific target. Clang now returns true
-  only when the attribute pertains to the current compilation target.
-  
-- Clang 3.5 now has parsing and semantic-analysis support for all OpenMP 3.1
-  pragmas (except atomics and ordered). LLVM's OpenMP runtime library,
-  originally developed by Intel, has been modified to work on ARM, PowerPC,
-  as well as X86. Code generation support is minimal at this point and will
-  continue to be developed for 3.6, along with the rest of OpenMP 3.1.
-  Support for OpenMP 4.0 features, such as SIMD and target accelerator
-  directives, is also in progress. Contributors to this work include AMD,
-  Argonne National Lab., IBM, Intel, Texas Instruments, University of Houston
-  and many others.
 
 Improvements to Clang's diagnostics
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Clang's diagnostics are constantly being improved to catch more issues,
 explain them more clearly, and provide more accurate source information
-about them. The improvements since the 3.4 release include:
-
-- GCC compatibility: Clang displays a warning on unsupported gcc
-  optimization flags instead of an error.
-
-- Remarks system: Clang supports `-R` flags for enabling remarks. These are
-  diagnostic messages that provide information about the compilation process,
-  but don't suggest that a problem has been detected. As such, they cannot
-  be upgraded to errors with `-Werror` or `-Rerror`. A `-Reverything` flag
-  is provided (paralleling `-Weverything`) to turn on all remarks.
-
-- New remark `-Rpass`: Clang provides information about decisions made by
-  optimization passes during compilation. See :ref:`opt_rpass`.
-
-- New warning `-Wabsolute-value`: Clang warns about incorrect or useless usage
-  of the absolute functions (`abs`, `fabsf`, etc).
-
-  .. code-block:: c
-
-    #include <stdlib.h>
-    void foo() {
-     unsigned int i=0;
-     abs(i);
-    }
-
-  returns
-  `warning: taking the absolute value of unsigned type 'unsigned int' has no effect [-Wabsolute-value]`
-
-  or
-
-  .. code-block:: c
-
-    #include <stdlib.h>
-    void plop() {
-      long long i=0;
-      abs(i);
-    }
-
-  returns
-  `warning: absolute value function 'abs' given an argument of type 'long long' but has parameter of type 'int' which may cause truncation of value [-Wabsolute-value] use function 'llabs' instead`
-
-- New warning `-Wtautological-pointer-compare`:
-
-  .. code-block:: c++
-
-    #include <stddef.h>
-    void foo() {
-     int arr[5];
-     int x;
-     // warn on these conditionals
-     if (foo);
-     if (arr);
-     if (&x);
-     if (foo == NULL);
-     if (arr == NULL);
-     if (&x == NULL);
-    }
-
-  returns
-  `warning: comparison of address of 'x' equal to a null pointer is always false [-Wtautological-pointer-compare]`
-
-- New warning `-Wtautological-undefined-compare`: 
-
-  .. code-block:: c++
-
-    #include <stddef.h>
-    void f(int &x) {
-       if (&x == nullptr) { }
-    }
-
-  returns
-  `warning: reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to always evaluate to false [-Wtautological-undefined-compare]`
+about them. The improvements since the 3.5 release include:
 
 -  ...
 
 New Compiler Flags
 ------------------
 
-The integrated assembler is now turned on by default on ARM (and Thumb),
-so the use of the option `-fintegrated-as` is now redundant on those
-architectures. This is an important move to both *eat our own dog food*
-and to ease cross-compilation tremendously.
-
-We are aware of the problems that this may cause for code bases that
-rely on specific GNU syntax or extensions, and we're working towards
-getting them all fixed. Please, report bugs or feature requests if
-you find anything. In the meantime, use `-fno-integrated-as` to revert
-back the call to GNU assembler.
-
-In order to provide better diagnostics, the integrated assembler validates
-inline assembly when the integrated assembler is enabled.  Because this is
-considered a feature of the compiler, it is controlled via the `fintegrated-as`
-and `fno-integrated-as` flags which enable and disable the integrated assembler
-respectively.  `-integrated-as` and `-no-integrated-as` are now considered
-legacy flags (but are available as an alias to prevent breaking existing users),
-and users are encouraged to switch to the equivalent new feature flag.
-
-Deprecated flags `-faddress-sanitizer`, `-fthread-sanitizer`,
-`-fcatch-undefined-behavior` and `-fbounds-checking` were removed in favor of
-`-fsanitize=` family of flags.
-
-It is now possible to get optimization reports from the major transformation
-passes via three new flags: `-Rpass`, `-Rpass-missed` and `-Rpass-analysis`.
-These flags take a POSIX regular expression which indicates the name
-of the pass (or passes) that should emit optimization remarks.
-
-Options `-u` and `-z` are forwarded to the linker on gnutools toolchains.
+The option ....
 
 
 New Pragmas in Clang
 -----------------------
 
-Loop optimization hints can be specified using the new `#pragma clang loop`
-directive just prior to the desired loop. The directive allows vectorization and
-interleaving to be enabled or disabled. Vector width as well as interleave count
-can be manually specified.  See :ref:`langext-pragma-loop` for details.
+Clang now supports the ...
+
+Windows Support
+---------------
+
+Clang's support for building native Windows programs ...
+
+
+C Language Changes in Clang
+---------------------------
+
+...
+
+C11 Feature Support
+^^^^^^^^^^^^^^^^^^^
+
+...
 
 C++ Language Changes in Clang
 -----------------------------
 
-- Reference parameters and return values from functions are more aggressively
-  assumed to refer to valid objects when optimizing. Clang will attempt to
-  issue a warning by default if it sees null checks being performed on
-  references, and `-fsanitize=null` can be used to detect null references
-  being formed at runtime.
+- ...
 
-C++17 Feature Support
+C++11 Feature Support
 ^^^^^^^^^^^^^^^^^^^^^
 
-Clang has experimental support for some proposed C++1z (tentatively, C++17)
-features. This support can be enabled using the `-std=c++1z` flag. The
-supported features are:
+...
 
-- `static_assert(expr)` with no message
+Objective-C Language Changes in Clang
+-------------------------------------
 
-- `for (identifier : range)` as a synonym for `for (auto &&identifier : range)`
+...
 
-- `template<template<...> typename>` as a synonym for `template<template<...> class>`
+OpenCL C Language Changes in Clang
+----------------------------------
 
-Additionally, trigraphs are not recognized by default in this mode.
-`-ftrigraphs` can be used if you need to parse legacy code that uses trigraphs.
-Note that these features may be changed or removed in future Clang releases
-without notice.
-
-OpenMP C/C++ Language Changes in Clang
---------------------------------------
-
-- `Status of supported OpenMP constructs 
-  <https://github.com/clang-omp/clang/wiki/Status-of-supported-OpenMP-constructs>`_.
-
+...
 
 Internal API Changes
 --------------------
 
-These are major API changes that have happened since the 3.4 release of
+These are major API changes that have happened since the 3.5 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.
 
-- Clang uses `std::unique_ptr<T>` in many places where it used to use
-  raw `T *` pointers.
+...
+
+libclang
+--------
+
+...
 
 Static Analyzer
 ---------------
 
-Check for code testing a variable for 0 after using it as a denominator.
-This new checker, alpha.core.TestAfterDivZero, catches issues like this:
+...
 
-.. code-block:: c
+Core Analysis Improvements
+==========================
 
-  int sum = ...
-  int avg = sum / count; // potential division by zero...
-  if (count == 0) { ... } // ...caught here
+- ...
 
+New Issues Found
+================
 
-The `-analyzer-config` options are now passed from scan-build through to
-ccc-analyzer and then to Clang.
+- ...
 
-With the option `-analyzer-config stable-report-filename=true`,
-instead of `report-XXXXXX.html`, scan-build/clang analyzer generate
-`report-<filename>-<function, method name>-<function position>-<id>.html`.
-(id = i++ for several issues found in the same function/method).
+Python Binding Changes
+----------------------
 
-List the function/method name in the index page of scan-build.
+The following methods have been added:
+
+-  ...
 
 Significant Known Problems
 ==========================
diff --git a/docs/ThreadSafetyAnalysis.rst b/docs/ThreadSafetyAnalysis.rst
index dfef80b..0a1b804 100644
--- a/docs/ThreadSafetyAnalysis.rst
+++ b/docs/ThreadSafetyAnalysis.rst
@@ -10,8 +10,8 @@
 potential race conditions in code.  The analysis is completely static (i.e.
 compile-time); there is no run-time overhead.  The analysis is still
 under active development, but it is mature enough to be deployed in an
-industrial setting.  It being developed by Google, and is used extensively
-on their internal code base.
+industrial setting.  It is being developed by Google, in collaboration with
+CERT/SEI, and is used extensively in Google's internal code base.
 
 Thread safety analysis works very much like a type system for multi-threaded
 programs.  In addition to declaring the *type* of data (e.g. ``int``, ``float``,
@@ -21,7 +21,7 @@
 a piece of code reads or writes to ``foo`` without first locking ``mu``.
 Similarly, if there are particular routines that should only be called by
 the GUI thread, then the analysis will warn if other threads call those
-routines. 
+routines.
 
 Getting Started
 ----------------
@@ -34,21 +34,21 @@
   private:
     Mutex mu;
     int   balance GUARDED_BY(mu);
-  
+
     void depositImpl(int amount) {
       balance += amount;       // WARNING! Cannot write balance without locking mu.
     }
-  
-    void withdrawImpl(int amount) EXCLUSIVE_LOCKS_REQUIRED(mu) {
+
+    void withdrawImpl(int amount) REQUIRES(mu) {
       balance -= amount;       // OK. Caller must have locked mu.
     }
-  
+
   public:
     void withdraw(int amount) {
       mu.Lock();
       withdrawImpl(amount);    // OK.  We've locked mu.
     }                          // WARNING!  Failed to unlock mu.
-  
+
     void transferFrom(BankAccount& b, int amount) {
       mu.Lock();
       b.withdrawImpl(amount);  // WARNING!  Calling withdrawImpl() requires locking b.mu.
@@ -60,23 +60,23 @@
 This example demonstrates the basic concepts behind the analysis.  The
 ``GUARDED_BY`` attribute declares that a thread must lock ``mu`` before it can
 read or write to ``balance``, thus ensuring that the increment and decrement
-operations are atomic.  Similarly, ``EXCLUSIVE_LOCKS_REQUIRED`` declares that
+operations are atomic.  Similarly, ``REQUIRES`` declares that
 the calling thread must lock ``mu`` before calling ``withdrawImpl``.
 Because the caller is assumed to have locked ``mu``, it is safe to modify
 ``balance`` within the body of the method.
 
-The ``depositImpl()`` method does not have ``EXCLUSIVE_LOCKS_REQUIRED``, so the
+The ``depositImpl()`` method does not have ``REQUIRES``, so the
 analysis issues a warning.  Thread safety analysis is not inter-procedural, so
 caller requirements must be explicitly declared.
 There is also a warning in ``transferFrom()``, because although the method
 locks ``this->mu``, it does not lock ``b.mu``.  The analysis understands
-that these are two separate mutexes, in two different objects.  
+that these are two separate mutexes, in two different objects.
 
 Finally, there is a warning in the ``withdraw()`` method, because it fails to
 unlock ``mu``.  Every lock must have a corresponding unlock, and the analysis
 will detect both double locks, and double unlocks.  A function is allowed to
 acquire a lock without releasing it, (or vice versa), but it must be annotated
-as such (using ``LOCK``/``UNLOCK_FUNCTION``).
+as such (using ``ACQUIRE``/``RELEASE``).
 
 
 Running The Analysis
@@ -90,7 +90,7 @@
 
 Note that this example assumes the presence of a suitably annotated
 :ref:`mutexheader` that declares which methods perform locking,
-unlocking, and so on. 
+unlocking, and so on.
 
 
 Basic Concepts: Capabilities
@@ -106,14 +106,14 @@
 methods to acquire and release the capability.  The name of the object serves
 to identify the capability.  The most common example is a mutex.  For example,
 if ``mu`` is a mutex, then calling ``mu.Lock()`` causes the calling thread
-to acquire the capability to access data that is protected by ``mu``. Similarly, 
+to acquire the capability to access data that is protected by ``mu``. Similarly,
 calling ``mu.Unlock()`` releases that capability.
 
 A thread may hold a capability either *exclusively* or *shared*.  An exclusive
 capability can be held by only one thread at a time, while a shared capability
 can be held by many threads at the same time.  This mechanism enforces a
 multiple-reader, single-writer pattern.  Write operations to protected data
-require exclusive access, while read operations require only shared access.  
+require exclusive access, while read operations require only shared access.
 
 At any given moment during program execution, a thread holds a specific set of
 capabilities (e.g. the set of mutexes that it has locked.)  These act like keys
@@ -121,7 +121,7 @@
 security keys, a thread cannot make copy of a capability, nor can it destroy
 one.  A thread can only release a capability to another thread, or acquire one
 from another thread.  The annotations are deliberately agnostic about the
-exact mechanism used to acquire and release capabilities; it assumes that the 
+exact mechanism used to acquire and release capabilities; it assumes that the
 underlying implementation (e.g. the Mutex implementation) does the handoff in
 an appropriate manner.
 
@@ -144,6 +144,11 @@
 attributes; example definitions can be found in :ref:`mutexheader`, below.
 The following documentation assumes the use of macros.
 
+For historical reasons, prior versions of thread safety used macro names that
+were very lock-centric.  These macros have since been renamed to fit a more
+general capability model.  The prior names are still in use, and will be
+mentioned under the tag *previously* where appropriate.
+
 
 GUARDED_BY(c) and PT_GUARDED_BY(c)
 ----------------------------------
@@ -154,47 +159,49 @@
 
 ``PT_GUARDED_BY`` is similar, but is intended for use on pointers and smart
 pointers. There is no constraint on the data member itself, but the *data that
-it points to* is protected by the given capability.  
+it points to* is protected by the given capability.
 
 .. code-block:: c++
 
   Mutex mu;
-  int *p1            GUARDED_BY(mu);
-  int *p2            PT_GUARDED_BY(mu);
-  unique_ptr<int> p3 PT_GUARDED_BY(mu);
-  
+  int *p1             GUARDED_BY(mu);
+  int *p2             PT_GUARDED_BY(mu);
+  unique_ptr<int> p3  PT_GUARDED_BY(mu);
+
   void test() {
     p1 = 0;             // Warning!
-  
-    p2 = new int;       // OK.
+
     *p2 = 42;           // Warning!
-  
-    p3.reset(new int);  // OK.
+    p2 = new int;       // OK.
+
     *p3 = 42;           // Warning!
+    p3.reset(new int);  // OK.
   }
 
 
-EXCLUSIVE_LOCKS_REQUIRED(...), SHARED_LOCKS_REQUIRED(...)
----------------------------------------------------------
+REQUIRES(...), REQUIRES_SHARED(...)
+-----------------------------------
 
-``EXCLUSIVE_LOCKS_REQUIRED`` is an attribute on functions or methods, which
+*Previously*: ``EXCLUSIVE_LOCKS_REQUIRED``, ``SHARED_LOCKS_REQUIRED``
+
+``REQUIRES`` is an attribute on functions or methods, which
 declares that the calling thread must have exclusive access to the given
 capabilities.  More than one capability may be specified.  The capabilities
-must be held on entry to the function, *and must still be held on exit*.  
+must be held on entry to the function, *and must still be held on exit*.
 
-``SHARED_LOCKS_REQUIRED`` is similar, but requires only shared access.
+``REQUIRES_SHARED`` is similar, but requires only shared access.
 
 .. code-block:: c++
 
   Mutex mu1, mu2;
   int a GUARDED_BY(mu1);
   int b GUARDED_BY(mu2);
-  
-  void foo() EXCLUSIVE_LOCKS_REQUIRED(mu1, mu2) {
+
+  void foo() REQUIRES(mu1, mu2) {
     a = 0;
     b = 0;
   }
-  
+
   void test() {
     mu1.Lock();
     foo();         // Warning!  Requires mu2.
@@ -202,32 +209,36 @@
   }
 
 
-EXCLUSIVE_LOCK_FUNCTION(...), SHARED_LOCK_FUNCTION(...), UNLOCK_FUNCTION(...)
------------------------------------------------------------------------------
+ACQUIRE(...), ACQUIRE_SHARED(...), RELEASE(...), RELEASE_SHARED(...)
+--------------------------------------------------------------------
 
-``EXCLUSIVE_LOCK_FUNCTION`` is an attribute on functions or methods, which
+*Previously*: ``EXCLUSIVE_LOCK_FUNCTION``, ``SHARED_LOCK_FUNCTION``,
+``UNLOCK_FUNCTION``
+
+``ACQUIRE`` is an attribute on functions or methods, which
 declares that the function acquires a capability, but does not release it.  The
 caller must not hold the given capability on entry, and it will hold the
-capability on exit.  ``SHARED_LOCK_FUNCTION`` is similar. 
+capability on exit.  ``ACQUIRE_SHARED`` is similar.
 
-``UNLOCK_FUNCTION`` declares that the function releases the given capability.
-The caller must hold the capability on entry, and will no longer hold it on
-exit. It does not matter whether the given capability is shared or exclusive.
+``RELEASE`` and ``RELEASE_SHARED`` declare that the function releases the given
+capability.  The caller must hold the capability on entry, and will no longer
+hold it on exit. It does not matter whether the given capability is shared or
+exclusive.
 
 .. code-block:: c++
 
   Mutex mu;
   MyClass myObject GUARDED_BY(mu);
-  
-  void lockAndInit() EXCLUSIVE_LOCK_FUNCTION(mu) {
+
+  void lockAndInit() ACQUIRE(mu) {
     mu.Lock();
     myObject.init();
   }
-  
-  void cleanupAndUnlock() UNLOCK_FUNCTION(mu) {
+
+  void cleanupAndUnlock() RELEASE(mu) {
     myObject.cleanup();
-  }  // Warning!  Need to unlock mu.
-  
+  }                          // Warning!  Need to unlock mu.
+
   void test() {
     lockAndInit();
     myObject.doSomething();
@@ -235,27 +246,27 @@
     myObject.doSomething();  // Warning, mu is not locked.
   }
 
-If no argument is passed to ``(UN)LOCK_FUNCTION``, then the argument is assumed
-to be ``this``, and the analysis will not check the body of the function.  This
-pattern is intended for use by classes which hide locking details behind an
-abstract interface.  E.g.
+If no argument is passed to ``ACQUIRE`` or ``RELEASE``, then the argument is
+assumed to be ``this``, and the analysis will not check the body of the
+function.  This pattern is intended for use by classes which hide locking
+details behind an abstract interface.  For example:
 
 .. code-block:: c++
 
   template <class T>
-  class LOCKABLE Container {
+  class CAPABILITY("mutex") Container {
   private:
     Mutex mu;
     T* data;
-  
+
   public:
     // Hide mu from public interface.
-    void Lock() EXCLUSIVE_LOCK_FUNCTION() { mu.Lock(); }
-    void Unlock() UNLOCK_FUNCTION() { mu.Unlock(); }
-  
+    void Lock()   ACQUIRE() { mu.Lock(); }
+    void Unlock() RELEASE() { mu.Unlock(); }
+
     T& getElem(int i) { return data[i]; }
   };
-  
+
   void test() {
     Container<int> c;
     c.Lock();
@@ -264,33 +275,36 @@
   }
 
 
-LOCKS_EXCLUDED(...)
--------------------
+EXCLUDES(...)
+-------------
 
-``LOCKS_EXCLUDED`` is an attribute on functions or methods, which declares that
+*Previously*: ``LOCKS_EXCLUDED``
+
+``EXCLUDES`` is an attribute on functions or methods, which declares that
 the caller must *not* hold the given capabilities.  This annotation is
 used to prevent deadlock.  Many mutex implementations are not re-entrant, so
-deadlock can occur if the function in question acquires the mutex a second time.
+deadlock can occur if the function acquires the mutex a second time.
 
 .. code-block:: c++
 
   Mutex mu;
   int a GUARDED_BY(mu);
-  
-  void clear() LOCKS_EXCLUDED(mu) {
+
+  void clear() EXCLUDES(mu) {
     mu.Lock();
     a = 0;
     mu.Unlock();
   }
-  
+
   void reset() {
     mu.Lock();
     clear();     // Warning!  Caller cannot hold 'mu'.
     mu.Unlock();
   }
 
-Unlike ``LOCKS_REQUIRED``, ``LOCKS_EXCLUDED`` is optional.  The analysis will
-not issue a warning if the attribute is missing.  See :ref:`limitations`.
+Unlike ``REQUIRES``, ``EXCLUDES`` is optional.  The analysis will not issue a
+warning if the attribute is missing, which can lead to false negatives in some
+cases.  This issue is discussed further in :ref:`negative`.
 
 
 NO_THREAD_SAFETY_ANALYSIS
@@ -307,16 +321,23 @@
   class Counter {
     Mutex mu;
     int a GUARDED_BY(mu);
-  
+
     void unsafeIncrement() NO_THREAD_SAFETY_ANALYSIS { a++; }
   };
 
+Unlike the other attributes, NO_THREAD_SAFETY_ANALYSIS is not part of the
+interface of a function, and should thus be placed on the function definition
+(in the ``.cc`` or ``.cpp`` file) rather than on the function declaration
+(in the header).
 
-LOCK_RETURNED(c)
-----------------
 
-``LOCK_RETURNED`` is an attribute on functions or methods, which declares that
-the function returns a reference to the given capability.  It is used to
+RETURN_CAPABILITY(c)
+--------------------
+
+*Previously*: ``LOCK_RETURNED``
+
+``RETURN_CAPABILITY`` is an attribute on functions or methods, which declares
+that the function returns a reference to the given capability.  It is used to
 annotate getter methods that return mutexes.
 
 .. code-block:: c++
@@ -325,12 +346,12 @@
   private:
     Mutex mu;
     int a GUARDED_BY(mu);
-  
+
   public:
-    Mutex* getMu() LOCK_RETURNED(mu) { return &mu; }
-  
+    Mutex* getMu() RETURN_CAPABILITY(mu) { return &mu; }
+
     // analysis knows that getMu() == mu
-    void clear() EXCLUSIVE_LOCKS_REQUIRED(getMu()) { a = 0; }
+    void clear() REQUIRES(getMu()) { a = 0; }
   };
 
 
@@ -346,11 +367,11 @@
 
   Mutex m1;
   Mutex m2 ACQUIRED_AFTER(m1);
-  
+
   // Alternative declaration
   // Mutex m2;
   // Mutex m1 ACQUIRED_BEFORE(m2);
-  
+
   void foo() {
     m2.Lock();
     m1.Lock();  // Warning!  m2 must be acquired after m1.
@@ -359,36 +380,45 @@
   }
 
 
-LOCKABLE
---------
+CAPABILITY(<string>)
+--------------------
 
-``LOCKABLE`` is an attribute on classes, which specifies that objects of the
-class can be used as a capability.  See the ``Container`` example given above,
-or the ``Mutex`` class in :ref:`mutexheader`.
+*Previously*: ``LOCKABLE``
+
+``CAPABILITY`` is an attribute on classes, which specifies that objects of the
+class can be used as a capability.  The string argument specifies the kind of
+capability in error messages, e.g. ``"mutex"``.  See the ``Container`` example
+given above, or the ``Mutex`` class in :ref:`mutexheader`.
 
 
-SCOPED_LOCKABLE
----------------
+SCOPED_CAPABILITY
+-----------------
 
-``SCOPED_LOCKABLE`` is an attribute on classes that implement RAII-style
+*Previously*: ``SCOPED_LOCKABLE``
+
+``SCOPED_CAPABILITY`` is an attribute on classes that implement RAII-style
 locking, in which a capability is acquired in the constructor, and released in
 the destructor.  Such classes require special handling because the constructor
 and destructor refer to the capability via different names; see the
 ``MutexLocker`` class in :ref:`mutexheader`, below.
 
 
-EXCLUSIVE_TRYLOCK_FUNCTION(<bool>, ...), SHARED_TRYLOCK_FUNCTION(<bool>, ...)
------------------------------------------------------------------------------
+TRY_ACQUIRE(<bool>, ...), TRY_ACQUIRE_SHARED(<bool>, ...)
+---------------------------------------------------------
+
+*Previously:* ``EXCLUSIVE_TRYLOCK_FUNCTION``, ``SHARED_TRYLOCK_FUNCTION``
 
 These are attributes on a function or method that tries to acquire the given
 capability, and returns a boolean value indicating success or failure.
 The first argument must be ``true`` or ``false``, to specify which return value
 indicates success, and the remaining arguments are interpreted in the same way
-as ``(UN)LOCK_FUNCTION``.  See :ref:`mutexheader`, below, for example uses.
+as ``ACQUIRE``.  See :ref:`mutexheader`, below, for example uses.
 
 
-ASSERT_EXCLUSIVE_LOCK(...) and ASSERT_SHARED_LOCK(...)
-------------------------------------------------------
+ASSERT_CAPABILITY(...) and ASSERT_SHARED_CAPABILITY(...)
+--------------------------------------------------------
+
+*Previously:*  ``ASSERT_EXCLUSIVE_LOCK``, ``ASSERT_SHARED_LOCK``
 
 These are attributes on a function or method that does a run-time test to see
 whether the calling thread holds the given capability.  The function is assumed
@@ -410,13 +440,104 @@
   + ``-Wthread-safety-attributes``: Sanity checks on attribute syntax.
   + ``-Wthread-safety-analysis``: The core analysis.
   + ``-Wthread-safety-precise``: Requires that mutex expressions match precisely.
-    This warning can be disabled for code which has a lot of aliases.
+       This warning can be disabled for code which has a lot of aliases.
+  + ``-Wthread-safety-reference``: Checks when guarded members are passed by reference.
+
+
+:ref:`negative` are an experimental feature, which are enabled with:
+
+* ``-Wthread-safety-negative``:  Negative capabilities.  Off by default.
 
 When new features and checks are added to the analysis, they can often introduce
 additional warnings.  Those warnings are initially released as *beta* warnings
-for a period of time, after which they are migrated to the standard analysis.  
+for a period of time, after which they are migrated into the standard analysis.
 
-* ``-Wthread-safety-beta``:  New features.  Off by default. 
+* ``-Wthread-safety-beta``:  New features.  Off by default.
+
+
+.. _negative:
+
+Negative Capabilities
+=====================
+
+Thread Safety Analysis is designed to prevent both race conditions and
+deadlock.  The GUARDED_BY and REQUIRES attributes prevent race conditions, by
+ensuring that a capability is held before reading or writing to guarded data,
+and the EXCLUDES attribute prevents deadlock, by making sure that a mutex is
+*not* held.
+
+However, EXCLUDES is an optional attribute, and does not provide the same
+safety guarantee as REQUIRES.  In particular:
+
+  * A function which acquires a capability does not have to exclude it.
+  * A function which calls a function that excludes a capability does not
+    have transitively exclude that capability.
+
+As a result, EXCLUDES can easily produce false negatives:
+
+.. code-block:: c++
+
+  class Foo {
+    Mutex mu;
+
+    void foo() {
+      mu.Lock();
+      bar();           // No warning.
+      baz();           // No warning.
+      mu.Unlock();
+    }
+
+    void bar() {       // No warning.  (Should have EXCLUDES(mu)).
+      mu.Lock();
+      // ...
+      mu.Unlock();
+    }
+
+    void baz() {
+      bif();           // No warning.  (Should have EXCLUDES(mu)).
+    }
+
+    void bif() EXCLUDES(mu);
+  };
+
+
+Negative requirements are an alternative EXCLUDES that provide
+a stronger safety guarantee.  A negative requirement uses the  REQUIRES
+attribute, in conjunction with the ``!`` operator, to indicate that a capability
+should *not* be held.
+
+For example, using ``REQUIRES(!mu)`` instead of ``EXCLUDES(mu)`` will produce
+the appropriate warnings:
+
+.. code-block:: c++
+
+  class FooNeg {
+    Mutex mu;
+
+    void foo() REQUIRES(!mu) {   // foo() now requires !mu.
+      mu.Lock();
+      bar();
+      baz();
+      mu.Unlock();
+    }
+
+    void bar() {
+      mu.Lock();       // WARNING!  Missing REQUIRES(!mu).
+      // ...
+      mu.Unlock();
+    }
+
+    void baz() {
+      bif();           // WARNING!  Missing REQUIRES(!mu).
+    }
+
+    void bif() REQUIRES(!mu);
+  };
+
+
+Negative requirements are an experimental feature which is off by default,
+because it will produce many warnings in existing code.  It can be enabled
+by passing ``-Wthread-safety-negative``.
 
 
 .. _faq:
@@ -426,7 +547,10 @@
 
 (Q) Should I put attributes in the header file, or in the .cc/.cpp/.cxx file?
 
-(A) Attributes should always go in the header.
+(A) Attributes are part of the formal interface of a function, and should
+always go in the header, where they are visible to anything that includes
+the header.  Attributes in the .cpp file are not visible outside of the
+immediate translation unit, which leads to false negatives and false positives.
 
 
 (Q) "*Mutex is not locked on every path through here?*"  What does that mean?
@@ -436,7 +560,7 @@
 
 .. _limitations:
 
-Known Limitations 
+Known Limitations
 =================
 
 Lexical scope
@@ -448,14 +572,14 @@
 Use-before-declaration is okay within a single class, because attributes are
 parsed at the same time as method bodies. (C++ delays parsing of method bodies
 until the end of the class.)  However, use-before-declaration is not allowed
-between classes, as illustrated below.  
+between classes, as illustrated below.
 
 .. code-block:: c++
 
   class Foo;
 
   class Bar {
-    void bar(Foo* f) EXCLUSIVE_LOCKS_REQUIRED(f->mu);  // Error: mu undeclared.
+    void bar(Foo* f) REQUIRES(f->mu);  // Error: mu undeclared.
   };
 
   class Foo {
@@ -474,9 +598,9 @@
 is a private member of ``c``, then it is an error to write ``c.mu`` in an
 attribute.
 
-One workround is to (ab)use the ``LOCK_RETURNED`` attribute to provide a public
-*name* for a private mutex, without actually exposing the underlying mutex.
-For example:
+One workaround is to (ab)use the ``RETURN_CAPABILITY`` attribute to provide a
+public *name* for a private mutex, without actually exposing the underlying
+mutex.  For example:
 
 .. code-block:: c++
 
@@ -486,12 +610,12 @@
 
   public:
     // For thread safety analysis only.  Does not actually return mu.
-    Mutex* getMu() LOCK_RETURNED(mu) { return 0; }
+    Mutex* getMu() RETURN_CAPABILITY(mu) { return 0; }
 
-    void doSomething() EXCLUSIVE_LOCKS_REQUIRED(mu); 
+    void doSomething() REQUIRES(mu);
   };
 
-  void doSomethingTwice(MyClass& c) EXCLUSIVE_LOCKS_REQUIRED(c.getMu()) {
+  void doSomethingTwice(MyClass& c) REQUIRES(c.getMu()) {
     // The analysis thinks that c.getMu() == c.mu
     c.doSomething();
     c.doSomething();
@@ -506,43 +630,6 @@
 safety analysis.
 
 
-False negatives on pass by reference.
--------------------------------------
-
-The current version of the analysis only checks operations which refer to
-guarded data members directly by name.  If the data members are accessed
-indirectly, via a pointer or reference, then no warning is generated.  Thus,
-no warnings will be generated for the following code:
-
-.. code-block:: c++
-
-  Mutex mu;
-  int a GUARDED_BY(mu);
-
-  void clear(int& ra) { ra = 0; }
-
-  void test() {
-    int *p = &a;
-    *p = 0;       // No warning.  *p is an alias to a.  
-       
-    clear(a);     // No warning.  'a' is passed by reference.
-  }
-
-This issue is by far the biggest source of false negatives in the current
-version of the analysis.  At a fundamental level, the
-false negatives are caused by the fact that annotations are attached to data
-members, rather than types.  The type of ``&a`` should really be
-``int GUARDED_BY(mu)*``, rather than ``int*``, and the statement ``p = &a``
-should thus generate a type error.  However, attaching attributes to types
-would be an invasive change to the C++ type system, with potential
-ramifications with respect to template instantation, function overloading,
-and so on.  Thus, a complete solution to this issue is simply not feasible.
-
-Future versions of the analysis will include better support for pointer
-alias analysis, along with limited checking of guarded types, in order to
-reduce the number of false negatives.
-
-
 .. _conditional_locks:
 
 No conditionally held locks.
@@ -557,7 +644,7 @@
   void foo() {
     bool b = needsToLock();
     if (b) mu.Lock();
-    ...  // Warning!  Mutex 'mu' is not held on every path through here. 
+    ...  // Warning!  Mutex 'mu' is not held on every path through here.
     if (b) mu.Unlock();
   }
 
@@ -567,7 +654,7 @@
 
 The analysis currently does not do any checking inside constructors or
 destructors.  In other words, every constructor and destructor is treated as
-if it was annotated with ``NO_THREAD_SAFETY_ANALYSIS``.  
+if it was annotated with ``NO_THREAD_SAFETY_ANALYSIS``.
 The reason for this is that during initialization, only one thread typically
 has access to the object which is being initialized, and it is thus safe (and
 common practice) to initialize guarded members without acquiring any locks.
@@ -577,15 +664,15 @@
 object being initialized or destroyed, while still enforcing the usual access
 restrictions on everything else.  However, this is difficult to enforce in
 practice, because in complex pointer-based data structures, it is hard to
-determine what data is "owned by" the enclosing object.
+determine what data is owned by the enclosing object.
 
 No inlining.
 ------------
 
 Thread safety analysis is strictly intra-procedural, just like ordinary type
 checking.  It relies only on the declared attributes of a function, and will
-not attempt to "step inside", or inline any method calls.  As a result, code
-such as the following will not work:
+not attempt to inline any method calls.  As a result, code such as the
+following will not work:
 
 .. code-block:: c++
 
@@ -593,7 +680,7 @@
   class AutoCleanup {
     T* object;
     void (T::*mp)();
-    
+
   public:
     AutoCleanup(T* obj, void (T::*imp)()) : object(obj), mp(imp) { }
     ~AutoCleanup() { (object->*mp)(); }
@@ -602,8 +689,8 @@
   Mutex mu;
   void foo() {
     mu.Lock();
-    AutoCleanup<Mutex>(&mu, &Mutex::Unlock); 
-    ...
+    AutoCleanup<Mutex>(&mu, &Mutex::Unlock);
+    // ...
   }  // Warning, mu is not unlocked.
 
 In this case, the destructor of ``Autocleanup`` calls ``mu.Unlock()``, so
@@ -611,42 +698,14 @@
 thread safety analysis cannot see the unlock, because it does not attempt to
 inline the destructor.  Moreover, there is no way to annotate the destructor,
 because the destructor is calling a function that is not statically known.
-This pattern is simply not supported. 
-
-
-LOCKS_EXCLUDED is not transitive.
----------------------------------
-
-A function which calls a method marked with LOCKS_EXCLUDED is not required to
-put LOCKS_EXCLUDED in its own interface.  LOCKS_EXCLUDED behaves differently
-from LOCKS_REQUIRED in this respect, and it can result in false negatives:
-
-.. code-block:: c++
-
-  class Foo {
-    Mutex mu;
-    
-    void foo() {
-      mu.Lock();
-      bar();                // No warning
-      mu.Unlock();
-    }
-    
-    void bar() { baz(); }   // No warning.  (Should have LOCKS_EXCLUDED(mu).)
-    
-    void baz() LOCKS_EXCLUDED(mu);
-  };
-
-The lack of transitivity is due to the fact that LOCKS_EXCLUDED can easily
-break encapsulation; it would be a bad idea to require functions to list the
-names private locks which happen to be acquired internally.  
+This pattern is simply not supported.
 
 
 No alias analysis.
 ------------------
 
 The analysis currently does not track pointer aliases.  Thus, there can be
-false positives if two pointers both point to the same mutex.  
+false positives if two pointers both point to the same mutex.
 
 
 .. code-block:: c++
@@ -655,13 +714,13 @@
     Mutex* mu;
 
   public:
-    MutexUnlocker(Mutex* m) UNLOCK_FUNCTION(m) : mu(m)  { mu->Unlock(); }
-    ~MutexUnlocker() EXCLUSIVE_LOCK_FUNCTION(mu) { mu->Lock(); }
+    MutexUnlocker(Mutex* m) RELEASE(m) : mu(m)  { mu->Unlock(); }
+    ~MutexUnlocker() ACQUIRE(mu) { mu->Lock(); }
   };
 
   Mutex mutex;
-  void test() EXCLUSIVE_LOCKS_REQUIRED(mutex) {
-    { 
+  void test() REQUIRES(mutex) {
+    {
       MutexUnlocker munl(&mutex);  // unlocks mutex
       doSomeIO();
     }                              // Warning: locks munl.mu
@@ -669,14 +728,14 @@
 
 The MutexUnlocker class is intended to be the dual of the MutexLocker class,
 defined in :ref:`mutexheader`.  However, it doesn't work because the analysis
-doesn't know that munl.mu == mutex.  The SCOPED_LOCKABLE attribute handles
-aliasing 
+doesn't know that munl.mu == mutex.  The SCOPED_CAPABILITY attribute handles
+aliasing for MutexLocker, but does so only for that particular pattern.
 
 
 ACQUIRED_BEFORE(...) and ACQUIRED_AFTER(...) are currently unimplemented.
 -------------------------------------------------------------------------
 
-To be fixed in a future update. 
+To be fixed in a future update.
 
 
 .. _mutexheader:
@@ -688,14 +747,15 @@
 require that the threading API be wrapped in classes and methods which have the
 appropriate annotations.  The following code provides ``mutex.h`` as an example;
 these methods should be filled in to call the appropriate underlying
-implementation. 
+implementation.
 
 
 .. code-block:: c++
 
+
   #ifndef THREAD_SAFETY_ANALYSIS_MUTEX_H
   #define THREAD_SAFETY_ANALYSIS_MUTEX_H
-  
+
   // Enable thread safety attributes only with clang.
   // The attributes can be safely erased when compiling with other compilers.
   #if defined(__clang__) && (!defined(SWIG))
@@ -703,116 +763,185 @@
   #else
   #define THREAD_ANNOTATION_ATTRIBUTE__(x)   // no-op
   #endif
-  
+
   #define THREAD_ANNOTATION_ATTRIBUTE__(x)   __attribute__((x))
-  
+
+  #define CAPABILITY(x) \
+    THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
+
+  #define SCOPED_CAPABILITY \
+    THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
+
   #define GUARDED_BY(x) \
     THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
-  
-  #define GUARDED_VAR \
-    THREAD_ANNOTATION_ATTRIBUTE__(guarded)
-  
+
   #define PT_GUARDED_BY(x) \
     THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
-  
-  #define PT_GUARDED_VAR \
-    THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded)
-  
-  #define ACQUIRED_AFTER(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
-  
+
   #define ACQUIRED_BEFORE(...) \
     THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
-  
-  #define EXCLUSIVE_LOCKS_REQUIRED(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__))
-  
-  #define SHARED_LOCKS_REQUIRED(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__))
-  
-  #define LOCKS_EXCLUDED(...) \
+
+  #define ACQUIRED_AFTER(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
+
+  #define REQUIRES(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
+
+  #define REQUIRES_SHARED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
+
+  #define ACQUIRE(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
+
+  #define ACQUIRE_SHARED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
+
+  #define RELEASE(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
+
+  #define RELEASE_SHARED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
+
+  #define TRY_ACQUIRE(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
+
+  #define TRY_ACQUIRE_SHARED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
+
+  #define EXCLUDES(...) \
     THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
-  
-  #define LOCK_RETURNED(x) \
+
+  #define ASSERT_CAPABILITY(x) \
+    THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
+
+  #define ASSERT_SHARED_CAPABILITY(x) \
+    THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
+
+  #define RETURN_CAPABILITY(x) \
     THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
-  
-  #define LOCKABLE \
-    THREAD_ANNOTATION_ATTRIBUTE__(lockable)
-  
-  #define SCOPED_LOCKABLE \
-    THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
-  
-  #define EXCLUSIVE_LOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__))
-  
-  #define SHARED_LOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__))
-  
-  #define ASSERT_EXCLUSIVE_LOCK(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__))
-  
-  #define ASSERT_SHARED_LOCK(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__))
-  
-  #define EXCLUSIVE_TRYLOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__))
-  
-  #define SHARED_TRYLOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__))
-  
-  #define UNLOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__))
-  
+
   #define NO_THREAD_SAFETY_ANALYSIS \
     THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
-  
-  
+
+
   // Defines an annotated interface for mutexes.
   // These methods can be implemented to use any internal mutex implementation.
-  class LOCKABLE Mutex {
+  class CAPABILITY("mutex") Mutex {
   public:
     // Acquire/lock this mutex exclusively.  Only one thread can have exclusive
     // access at any one time.  Write operations to guarded data require an
     // exclusive lock.
-    void Lock() EXCLUSIVE_LOCK_FUNCTION();
-  
+    void Lock() ACQUIRE();
+
     // Acquire/lock this mutex for read operations, which require only a shared
     // lock.  This assumes a multiple-reader, single writer semantics.  Multiple
-    // threads may acquire the mutex simultaneously as readers, but a writer must
-    // wait for all of them to release the mutex before it can acquire it
-    // exclusively.  
-    void ReaderLock() SHARED_LOCK_FUNCTION();
-  
-    // Release/unlock the mutex, regardless of whether it is exclusive or shared.
-    void Unlock() UNLOCK_FUNCTION();
-  
+    // threads may acquire the mutex simultaneously as readers, but a writer
+    // must wait for all of them to release the mutex before it can acquire it
+    // exclusively.
+    void ReaderLock() ACQUIRE_SHARED();
+
+    // Release/unlock an exclusive mutex.
+    void Unlock() RELEASE();
+
+    // Release/unlock a shared mutex.
+    void ReaderUnlock() RELEASE_SHARED();
+
     // Try to acquire the mutex.  Returns true on success, and false on failure.
-    bool TryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true);
-  
+    bool TryLock() TRY_ACQUIRE(true);
+
     // Try to acquire the mutex for read operations.
-    bool ReaderTryLock() SHARED_TRYLOCK_FUNCTION(true);
-  
+    bool ReaderTryLock() TRY_ACQUIRE_SHARED(true);
+
     // Assert that this mutex is currently held by the calling thread.
-    void AssertHeld() ASSERT_EXCLUSIVE_LOCK();
-  
-    // Assert that is mutex is currently held for read operations. 
-    void AssertReaderHeld() ASSERT_SHARED_LOCK();
+    void AssertHeld() ASSERT_CAPABILITY(this);
+
+    // Assert that is mutex is currently held for read operations.
+    void AssertReaderHeld() ASSERT_SHARED_CAPABILITY(this);
   };
-  
-  
+
+
   // MutexLocker is an RAII class that acquires a mutex in its constructor, and
-  // releases it in its destructor.  
-  class SCOPED_LOCKABLE MutexLocker {
+  // releases it in its destructor.
+  class SCOPED_CAPABILITY MutexLocker {
   private:
     Mutex* mut;
-  
+
   public:
-    MutexLocker(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mut(mu) {
+    MutexLocker(Mutex *mu) ACQUIRE(mu) : mut(mu) {
       mu->Lock();
-    }  
-    ~MutexLocker() UNLOCK_FUNCTION() {
+    }
+    ~MutexLocker() RELEASE() {
       mut->Unlock();
     }
   };
-  
+
+
+  #ifdef USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES
+  // The original version of thread safety analysis the following attribute
+  // definitions.  These use a lock-based terminology.  They are still in use
+  // by existing thread safety code, and will continue to be supported.
+
+  // Deprecated.
+  #define PT_GUARDED_VAR \
+    THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded)
+
+  // Deprecated.
+  #define GUARDED_VAR \
+    THREAD_ANNOTATION_ATTRIBUTE__(guarded)
+
+  // Replaced by REQUIRES
+  #define EXCLUSIVE_LOCKS_REQUIRED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__))
+
+  // Replaced by REQUIRES_SHARED
+  #define SHARED_LOCKS_REQUIRED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__))
+
+  // Replaced by CAPABILITY
+  #define LOCKABLE \
+    THREAD_ANNOTATION_ATTRIBUTE__(lockable)
+
+  // Replaced by SCOPED_CAPABILITY
+  #define SCOPED_LOCKABLE \
+    THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
+
+  // Replaced by ACQUIRE
+  #define EXCLUSIVE_LOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__))
+
+  // Replaced by ACQUIRE_SHARED
+  #define SHARED_LOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__))
+
+  // Replaced by RELEASE and RELEASE_SHARED
+  #define UNLOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__))
+
+  // Replaced by TRY_ACQUIRE
+  #define EXCLUSIVE_TRYLOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__))
+
+  // Replaced by TRY_ACQUIRE_SHARED
+  #define SHARED_TRYLOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__))
+
+  // Replaced by ASSERT_CAPABILITY
+  #define ASSERT_EXCLUSIVE_LOCK(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__))
+
+  // Replaced by ASSERT_SHARED_CAPABILITY
+  #define ASSERT_SHARED_LOCK(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__))
+
+  // Replaced by EXCLUDE_CAPABILITY.
+  #define LOCKS_EXCLUDED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
+
+  // Replaced by RETURN_CAPABILITY
+  #define LOCK_RETURNED(x) \
+    THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
+
+  #endif  // USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES
+
   #endif  // THREAD_SAFETY_ANALYSIS_MUTEX_H
+
diff --git a/docs/UsersManual.rst b/docs/UsersManual.rst
index 90f16ee..9d8e978 100644
--- a/docs/UsersManual.rst
+++ b/docs/UsersManual.rst
@@ -73,7 +73,7 @@
 Intro to how to use a C compiler for newbies.
 
 compile + link compile then link debug info enabling optimizations
-picking a language to use, defaults to C99 by default. Autosenses based
+picking a language to use, defaults to C11 by default. Autosenses based
 on extension. using a makefile
 
 Command Line Options
@@ -481,7 +481,7 @@
    Warn about an unusable copy constructor when binding a reference to a
    temporary.
 
-   This option, which defaults to on, enables warnings about binding a
+   This option enables warnings about binding a
    reference to a temporary when the temporary doesn't have a usable
    copy constructor. For example:
 
@@ -531,8 +531,6 @@
 The -fno-crash-diagnostics flag can be helpful for speeding the process
 of generating a delta reduced test case.
 
-.. _opt_rpass:
-
 Options to Emit Optimization Reports
 ------------------------------------
 
@@ -979,6 +977,8 @@
    -  ``-fsanitize=function``: Indirect call of a function through a
       function pointer of the wrong type (Linux, C++ and x86/x86_64 only).
    -  ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
+   -  ``-fsanitize=nonnull-attribute``: Passing null pointer as a function
+      parameter which is declared to never be null.
    -  ``-fsanitize=null``: Use of a null pointer or creation of a null
       reference.
    -  ``-fsanitize=object-size``: An attempt to use bytes which the
@@ -988,6 +988,8 @@
       more problems at higher optimization levels.
    -  ``-fsanitize=return``: In C++, reaching the end of a
       value-returning function without returning a value.
+   -  ``-fsanitize=returns-nonnull-attribute``: Returning null pointer
+      from a function which is declared to never return null.
    -  ``-fsanitize=shift``: Shift operators where the amount shifted is
       greater or equal to the promoted bit-width of the left hand side
       or less than zero, or where the left hand side is negative. For a
@@ -1113,6 +1115,37 @@
    This option restricts the generated code to use general registers
    only. This only applies to the AArch64 architecture.
 
+**-f[no-]max-unknown-pointer-align=[number]**
+   Instruct the code generator to not enforce a higher alignment than the given
+   number (of bytes) when accessing memory via an opaque pointer or reference.
+   This cap is ignored when directly accessing a variable or when the pointee
+   type has an explicit “aligned” attribute.
+
+   The value should usually be determined by the properties of the system allocator.
+   Some builtin types, especially vector types, have very high natural alignments;
+   when working with values of those types, Clang usually wants to use instructions
+   that take advantage of that alignment.  However, many system allocators do
+   not promise to return memory that is more than 8-byte or 16-byte-aligned.  Use
+   this option to limit the alignment that the compiler can assume for an arbitrary
+   pointer, which may point onto the heap.
+
+   This option does not affect the ABI alignment of types; the layout of structs and
+   unions and the value returned by the alignof operator remain the same.
+
+   This option can be overridden on a case-by-case basis by putting an explicit
+   “aligned” alignment on a struct, union, or typedef.  For example:
+
+   .. code-block:: console
+
+      #include <immintrin.h>
+      // Make an aligned typedef of the AVX-512 16-int vector type.
+      typedef __v16si __aligned_v16si __attribute__((aligned(64)));
+
+      void initialize_vector(__aligned_v16si *v) {
+        // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
+        // value of -fmax-unknown-pointer-align.
+      }
+
 
 Profile Guided Optimization
 ---------------------------
@@ -1441,9 +1474,12 @@
 ------------------------------------------
 
 clang supports the -std option, which changes what language mode clang
-uses. The supported modes for C are c89, gnu89, c94, c99, gnu99 and
-various aliases for those modes. If no -std option is specified, clang
-defaults to gnu99 mode.
+uses. The supported modes for C are c89, gnu89, c94, c99, gnu99, c11,
+gnu11, and various aliases for those modes. If no -std option is
+specified, clang defaults to gnu11 mode. Many C99 and C11 features are
+supported in earlier modes as a conforming extension, with a warning. Use
+``-pedantic-errors`` to request an error if a feature from a later standard
+revision is used in an earlier mode.
 
 Differences between all ``c*`` and ``gnu*`` modes:
 
@@ -1481,6 +1517,11 @@
    in ``*89`` modes.
 -  Some warnings are different.
 
+Differences between ``*99`` and ``*11`` modes:
+
+-  Warnings for use of C11 features are disabled.
+-  ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
+
 c94 mode is identical to c89 mode except that digraphs are enabled in
 c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
 
@@ -1874,6 +1915,8 @@
       /WX                    Treat warnings as errors
       /w                     Disable all warnings
       /Zi                    Enable debug information
+      /Zp                    Set the default maximum struct packing alignment to 1
+      /Zp<value>             Specify the default maximum struct packing alignment
       /Zs                    Syntax-check only
 
     OPTIONS:
diff --git a/docs/conf.py b/docs/conf.py
index 1963a05..7c2ef2a 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -48,9 +48,9 @@
 # built documents.
 #
 # The short X.Y version.
-version = '3.5'
+version = '3.6'
 # The full version, including alpha/beta/rc tags.
-release = '3.5'
+release = '3.6'
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
diff --git a/examples/PrintFunctionNames/PrintFunctionNames.cpp b/examples/PrintFunctionNames/PrintFunctionNames.cpp
index 3f18cd4..e8a361d 100644
--- a/examples/PrintFunctionNames/PrintFunctionNames.cpp
+++ b/examples/PrintFunctionNames/PrintFunctionNames.cpp
@@ -36,8 +36,9 @@
 
 class PrintFunctionNamesAction : public PluginASTAction {
 protected:
-  ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
-    return new PrintFunctionsConsumer();
+  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
+                                                 llvm::StringRef) {
+    return llvm::make_unique<PrintFunctionsConsumer>();
   }
 
   bool ParseArgs(const CompilerInstance &CI,
diff --git a/examples/clang-interpreter/CMakeLists.txt b/examples/clang-interpreter/CMakeLists.txt
index 3c66881..4c6db12 100644
--- a/examples/clang-interpreter/CMakeLists.txt
+++ b/examples/clang-interpreter/CMakeLists.txt
@@ -1,7 +1,8 @@
 set(LLVM_LINK_COMPONENTS
   Core
   ExecutionEngine
-  JIT
+  MC
+  MCJIT
   Support
   native
   )
diff --git a/examples/clang-interpreter/Makefile b/examples/clang-interpreter/Makefile
index d571337..2eff90b 100644
--- a/examples/clang-interpreter/Makefile
+++ b/examples/clang-interpreter/Makefile
@@ -15,12 +15,14 @@
 # No plugins, optimize startup time.
 TOOL_NO_EXPORTS = 1
 
-LINK_COMPONENTS := jit interpreter nativecodegen bitreader bitwriter irreader \
+LINK_COMPONENTS := mcjit interpreter nativecodegen bitreader bitwriter irreader \
 	ipo linker selectiondag asmparser instrumentation objcarcopts option
 USEDLIBS = clangFrontend.a clangSerialization.a clangDriver.a clangCodeGen.a \
            clangParse.a clangSema.a clangStaticAnalyzerFrontend.a \
            clangStaticAnalyzerCheckers.a clangStaticAnalyzerCore.a \
            clangAnalysis.a clangRewrite.a clangRewriteFrontend.a \
-           clangEdit.a clangAST.a clangLex.a clangBasic.a
+           clangEdit.a clangAST.a clangLex.a clangBasic.a LLVMCore.a \
+           LLVMExecutionEngine.a LLVMMC.a LLVMMCJIT.a LLVMRuntimeDyld.a \
+           LLVMObject.a LLVMSupport.a LLVMProfileData.a
 
 include $(CLANG_LEVEL)/Makefile
diff --git a/examples/clang-interpreter/main.cpp b/examples/clang-interpreter/main.cpp
index 8b8ccfd..9b4a257 100644
--- a/examples/clang-interpreter/main.cpp
+++ b/examples/clang-interpreter/main.cpp
@@ -18,7 +18,7 @@
 #include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ExecutionEngine/ExecutionEngine.h"
-#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/ExecutionEngine/MCJIT.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -42,18 +42,28 @@
   return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
 }
 
-static int Execute(llvm::Module *Mod, char * const *envp) {
-  llvm::InitializeNativeTarget();
+static llvm::ExecutionEngine *
+createExecutionEngine(std::unique_ptr<llvm::Module> M, std::string *ErrorStr) {
+  return llvm::EngineBuilder(std::move(M))
+      .setEngineKind(llvm::EngineKind::Either)
+      .setErrorStr(ErrorStr)
+      .create();
+}
 
+static int Execute(std::unique_ptr<llvm::Module> Mod, char *const *envp) {
+  llvm::InitializeNativeTarget();
+  llvm::InitializeNativeTargetAsmPrinter();
+
+  llvm::Module &M = *Mod;
   std::string Error;
   std::unique_ptr<llvm::ExecutionEngine> EE(
-      llvm::ExecutionEngine::create(Mod, /*ForceInterpreter*/ false, &Error));
+      createExecutionEngine(std::move(Mod), &Error));
   if (!EE) {
     llvm::errs() << "unable to make execution engine: " << Error << "\n";
     return 255;
   }
 
-  llvm::Function *EntryFn = Mod->getFunction("main");
+  llvm::Function *EntryFn = M.getFunction("main");
   if (!EntryFn) {
     llvm::errs() << "'main' function not found in module.\n";
     return 255;
@@ -61,8 +71,9 @@
 
   // FIXME: Support passing arguments.
   std::vector<std::string> Args;
-  Args.push_back(Mod->getModuleIdentifier());
+  Args.push_back(M.getModuleIdentifier());
 
+  EE->finalizeObject();
   return EE->runFunctionAsMain(EntryFn, Args, envp);
 }
 
@@ -75,7 +86,14 @@
 
   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
-  Driver TheDriver(Path, llvm::sys::getProcessTriple(), Diags);
+
+  // Use ELF on windows for now.
+  std::string TripleStr = llvm::sys::getProcessTriple();
+  llvm::Triple T(TripleStr);
+  if (T.isOSBinFormatCOFF())
+    T.setObjectFormat(llvm::Triple::ELF);
+
+  Driver TheDriver(Path, T.str(), Diags);
   TheDriver.setTitle("clang interpreter");
   TheDriver.setCheckInputsExist(false);
 
@@ -101,14 +119,14 @@
     return 1;
   }
 
-  const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
-  if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
+  const driver::Command &Cmd = cast<driver::Command>(*Jobs.begin());
+  if (llvm::StringRef(Cmd.getCreator().getName()) != "clang") {
     Diags.Report(diag::err_fe_expected_clang_command);
     return 1;
   }
 
   // Initialize a compiler invocation object from the clang (-cc1) arguments.
-  const driver::ArgStringList &CCArgs = Cmd->getArguments();
+  const driver::ArgStringList &CCArgs = Cmd.getArguments();
   std::unique_ptr<CompilerInvocation> CI(new CompilerInvocation);
   CompilerInvocation::CreateFromArgs(*CI,
                                      const_cast<const char **>(CCArgs.data()),
@@ -146,8 +164,8 @@
     return 1;
 
   int Res = 255;
-  if (llvm::Module *Module = Act->takeModule())
-    Res = Execute(Module, envp);
+  if (std::unique_ptr<llvm::Module> Module = Act->takeModule())
+    Res = Execute(std::move(Module), envp);
 
   // Shutdown.
 
diff --git a/include/clang-c/BuildSystem.h b/include/clang-c/BuildSystem.h
index ed3e8d9..7aa0191 100644
--- a/include/clang-c/BuildSystem.h
+++ b/include/clang-c/BuildSystem.h
@@ -11,8 +11,8 @@
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 
-#ifndef CLANG_C_BUILD_SYSTEM_H
-#define CLANG_C_BUILD_SYSTEM_H
+#ifndef LLVM_CLANG_C_BUILDSYSTEM_H
+#define LLVM_CLANG_C_BUILDSYSTEM_H
 
 #include "clang-c/Platform.h"
 #include "clang-c/CXErrorCode.h"
diff --git a/include/clang-c/CXCompilationDatabase.h b/include/clang-c/CXCompilationDatabase.h
index fd65418..068a677 100644
--- a/include/clang-c/CXCompilationDatabase.h
+++ b/include/clang-c/CXCompilationDatabase.h
@@ -12,8 +12,8 @@
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 
-#ifndef CLANG_CXCOMPILATIONDATABASE_H
-#define CLANG_CXCOMPILATIONDATABASE_H
+#ifndef LLVM_CLANG_C_CXCOMPILATIONDATABASE_H
+#define LLVM_CLANG_C_CXCOMPILATIONDATABASE_H
 
 #include "clang-c/Platform.h"
 #include "clang-c/CXString.h"
diff --git a/include/clang-c/CXErrorCode.h b/include/clang-c/CXErrorCode.h
index a026c95..aff73b7 100644
--- a/include/clang-c/CXErrorCode.h
+++ b/include/clang-c/CXErrorCode.h
@@ -11,8 +11,8 @@
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 
-#ifndef CLANG_C_CXERRORCODE_H
-#define CLANG_C_CXERRORCODE_H
+#ifndef LLVM_CLANG_C_CXERRORCODE_H
+#define LLVM_CLANG_C_CXERRORCODE_H
 
 #include "clang-c/Platform.h"
 
diff --git a/include/clang-c/CXString.h b/include/clang-c/CXString.h
index cf198cb..a649cdf 100644
--- a/include/clang-c/CXString.h
+++ b/include/clang-c/CXString.h
@@ -11,8 +11,8 @@
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 
-#ifndef CLANG_CXSTRING_H
-#define CLANG_CXSTRING_H
+#ifndef LLVM_CLANG_C_CXSTRING_H
+#define LLVM_CLANG_C_CXSTRING_H
 
 #include "clang-c/Platform.h"
 
diff --git a/include/clang-c/Documentation.h b/include/clang-c/Documentation.h
index ad2da07..89373b1 100644
--- a/include/clang-c/Documentation.h
+++ b/include/clang-c/Documentation.h
@@ -12,8 +12,8 @@
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 
-#ifndef CLANG_C_DOCUMENTATION_H
-#define CLANG_C_DOCUMENTATION_H
+#ifndef LLVM_CLANG_C_DOCUMENTATION_H
+#define LLVM_CLANG_C_DOCUMENTATION_H
 
 #include "clang-c/Index.h"
 
diff --git a/include/clang-c/Index.h b/include/clang-c/Index.h
index f69f567..6e3bd07 100644
--- a/include/clang-c/Index.h
+++ b/include/clang-c/Index.h
@@ -13,8 +13,8 @@
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 
-#ifndef CLANG_C_INDEX_H
-#define CLANG_C_INDEX_H
+#ifndef LLVM_CLANG_C_INDEX_H
+#define LLVM_CLANG_C_INDEX_H
 
 #include <time.h>
 
@@ -32,7 +32,7 @@
  * compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
  */
 #define CINDEX_VERSION_MAJOR 0
-#define CINDEX_VERSION_MINOR 27
+#define CINDEX_VERSION_MINOR 29
 
 #define CINDEX_VERSION_ENCODE(major, minor) ( \
       ((major) * 10000)                       \
@@ -336,6 +336,12 @@
                                     const char *file_name);
 
 /**
+ * \brief Returns non-zero if the \c file1 and \c file2 point to the same file,
+ * or they are both NULL.
+ */
+CINDEX_LINKAGE int clang_File_isEqual(CXFile file1, CXFile file2);
+
+/**
  * @}
  */
 
@@ -2195,7 +2201,31 @@
    */
   CXCursor_SEHLeaveStmt                  = 247,
 
-  CXCursor_LastStmt                      = CXCursor_SEHLeaveStmt,
+  /** \brief OpenMP ordered directive.
+   */
+  CXCursor_OMPOrderedDirective           = 248,
+
+  /** \brief OpenMP atomic directive.
+   */
+  CXCursor_OMPAtomicDirective            = 249,
+
+  /** \brief OpenMP for simd directive.
+   */
+  CXCursor_OMPForSimdDirective           = 250,
+
+  /** \brief OpenMP parallel for simd directive.
+   */
+  CXCursor_OMPParallelForSimdDirective   = 251,
+
+  /** \brief OpenMP target directive.
+   */
+  CXCursor_OMPTargetDirective            = 252,
+
+  /** \brief OpenMP teams directive.
+   */
+  CXCursor_OMPTeamsDirective             = 253,
+
+  CXCursor_LastStmt                      = CXCursor_OMPTeamsDirective,
 
   /**
    * \brief Cursor that represents the translation unit itself.
@@ -2228,7 +2258,8 @@
   CXCursor_CUDADeviceAttr                = 413,
   CXCursor_CUDAGlobalAttr                = 414,
   CXCursor_CUDAHostAttr                  = 415,
-  CXCursor_LastAttr                      = CXCursor_CUDAHostAttr,
+  CXCursor_CUDASharedAttr                = 416,
+  CXCursor_LastAttr                      = CXCursor_CUDASharedAttr,
 
   /* Preprocessing */
   CXCursor_PreprocessingDirective        = 500,
@@ -2822,6 +2853,7 @@
   CXCallingConv_IntelOclBicc = 9,
   CXCallingConv_X86_64Win64 = 10,
   CXCallingConv_X86_64SysV = 11,
+  CXCallingConv_X86VectorCall = 12,
 
   CXCallingConv_Invalid = 100,
   CXCallingConv_Unexposed = 200
@@ -2912,6 +2944,124 @@
 CINDEX_LINKAGE CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i);
 
 /**
+ * \brief Describes the kind of a template argument.
+ *
+ * See the definition of llvm::clang::TemplateArgument::ArgKind for full
+ * element descriptions.
+ */
+enum CXTemplateArgumentKind {
+  CXTemplateArgumentKind_Null,
+  CXTemplateArgumentKind_Type,
+  CXTemplateArgumentKind_Declaration,
+  CXTemplateArgumentKind_NullPtr,
+  CXTemplateArgumentKind_Integral,
+  CXTemplateArgumentKind_Template,
+  CXTemplateArgumentKind_TemplateExpansion,
+  CXTemplateArgumentKind_Expression,
+  CXTemplateArgumentKind_Pack,
+  /* Indicates an error case, preventing the kind from being deduced. */
+  CXTemplateArgumentKind_Invalid
+};
+
+/**
+ *\brief Returns the number of template args of a function decl representing a
+ * template specialization.
+ *
+ * If the argument cursor cannot be converted into a template function
+ * declaration, -1 is returned.
+ *
+ * For example, for the following declaration and specialization:
+ *   template <typename T, int kInt, bool kBool>
+ *   void foo() { ... }
+ *
+ *   template <>
+ *   void foo<float, -7, true>();
+ *
+ * The value 3 would be returned from this call.
+ */
+CINDEX_LINKAGE int clang_Cursor_getNumTemplateArguments(CXCursor C);
+
+/**
+ * \brief Retrieve the kind of the I'th template argument of the CXCursor C.
+ *
+ * If the argument CXCursor does not represent a FunctionDecl, an invalid
+ * template argument kind is returned.
+ *
+ * For example, for the following declaration and specialization:
+ *   template <typename T, int kInt, bool kBool>
+ *   void foo() { ... }
+ *
+ *   template <>
+ *   void foo<float, -7, true>();
+ *
+ * For I = 0, 1, and 2, Type, Integral, and Integral will be returned,
+ * respectively.
+ */
+CINDEX_LINKAGE enum CXTemplateArgumentKind clang_Cursor_getTemplateArgumentKind(
+    CXCursor C, unsigned I);
+
+/**
+ * \brief Retrieve a CXType representing the type of a TemplateArgument of a
+ *  function decl representing a template specialization.
+ *
+ * If the argument CXCursor does not represent a FunctionDecl whose I'th
+ * template argument has a kind of CXTemplateArgKind_Integral, an invalid type
+ * is returned.
+ *
+ * For example, for the following declaration and specialization:
+ *   template <typename T, int kInt, bool kBool>
+ *   void foo() { ... }
+ *
+ *   template <>
+ *   void foo<float, -7, true>();
+ *
+ * If called with I = 0, "float", will be returned.
+ * Invalid types will be returned for I == 1 or 2.
+ */
+CINDEX_LINKAGE CXType clang_Cursor_getTemplateArgumentType(CXCursor C,
+                                                           unsigned I);
+
+/**
+ * \brief Retrieve the value of an Integral TemplateArgument (of a function
+ *  decl representing a template specialization) as a signed long long.
+ *
+ * It is undefined to call this function on a CXCursor that does not represent a
+ * FunctionDecl or whose I'th template argument is not an integral value.
+ *
+ * For example, for the following declaration and specialization:
+ *   template <typename T, int kInt, bool kBool>
+ *   void foo() { ... }
+ *
+ *   template <>
+ *   void foo<float, -7, true>();
+ *
+ * If called with I = 1 or 2, -7 or true will be returned, respectively.
+ * For I == 0, this function's behavior is undefined.
+ */
+CINDEX_LINKAGE long long clang_Cursor_getTemplateArgumentValue(CXCursor C,
+                                                               unsigned I);
+
+/**
+ * \brief Retrieve the value of an Integral TemplateArgument (of a function
+ *  decl representing a template specialization) as an unsigned long long.
+ *
+ * It is undefined to call this function on a CXCursor that does not represent a
+ * FunctionDecl or whose I'th template argument is not an integral value.
+ *
+ * For example, for the following declaration and specialization:
+ *   template <typename T, int kInt, bool kBool>
+ *   void foo() { ... }
+ *
+ *   template <>
+ *   void foo<float, 2147483649, true>();
+ *
+ * If called with I = 1 or 2, 2147483649 or true will be returned, respectively.
+ * For I == 0, this function's behavior is undefined.
+ */
+CINDEX_LINKAGE unsigned long long clang_Cursor_getTemplateArgumentUnsignedValue(
+    CXCursor C, unsigned I);
+
+/**
  * \brief Determine whether two CXTypes represent the same type.
  *
  * \returns non-zero if the CXTypes represent the same type and
@@ -3194,6 +3344,29 @@
 CINDEX_LINKAGE enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor);
 
 /**
+ * \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.
+ */
+enum CX_StorageClass {
+  CX_SC_Invalid,
+  CX_SC_None,
+  CX_SC_Extern,
+  CX_SC_Static,
+  CX_SC_PrivateExtern,
+  CX_SC_OpenCLWorkGroupLocal,
+  CX_SC_Auto,
+  CX_SC_Register
+};
+
+/**
+ * \brief Returns the storage class for a function or variable declaration.
+ *
+ * If the passed in Cursor is not a function or variable declaration,
+ * CX_SC_Invalid is returned else the storage class.
+ */
+CINDEX_LINKAGE enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor);
+
+/**
  * \brief Determine the number of overloaded declarations referenced by a 
  * \c CXCursor_OverloadedDeclRef cursor.
  *
@@ -3631,6 +3804,20 @@
  * @}
  */
 
+/** \defgroup CINDEX_MANGLE Name Mangling API Functions
+ *
+ * @{
+ */
+
+/**
+ * \brief Retrieve the CXString representing the mangled name of the cursor.
+ */
+CINDEX_LINKAGE CXString clang_Cursor_getMangling(CXCursor);
+
+/**
+ * @}
+ */
+
 /**
  * \defgroup CINDEX_MODULE Module introspection
  *
diff --git a/include/clang-c/Platform.h b/include/clang-c/Platform.h
index 0f866c6..e2a4dcc 100644
--- a/include/clang-c/Platform.h
+++ b/include/clang-c/Platform.h
@@ -11,8 +11,8 @@
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 
-#ifndef CLANG_C_PLATFORM_H
-#define CLANG_C_PLATFORM_H
+#ifndef LLVM_CLANG_C_PLATFORM_H
+#define LLVM_CLANG_C_PLATFORM_H
 
 #ifdef __cplusplus
 extern "C" {
diff --git a/include/clang/ARCMigrate/ARCMTActions.h b/include/clang/ARCMigrate/ARCMTActions.h
index b3e74b9..c830aa3 100644
--- a/include/clang/ARCMigrate/ARCMTActions.h
+++ b/include/clang/ARCMigrate/ARCMTActions.h
@@ -7,8 +7,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_ARCMIGRATE_ARCMT_ACTION_H
-#define LLVM_CLANG_ARCMIGRATE_ARCMT_ACTION_H
+#ifndef LLVM_CLANG_ARCMIGRATE_ARCMTACTIONS_H
+#define LLVM_CLANG_ARCMIGRATE_ARCMTACTIONS_H
 
 #include "clang/ARCMigrate/FileRemapper.h"
 #include "clang/Frontend/FrontendAction.h"
@@ -37,8 +37,8 @@
   FileRemapper Remapper;
 protected:
   bool BeginInvocation(CompilerInstance &CI) override;
-  ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
-                                 StringRef InFile) override;
+  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
+                                                 StringRef InFile) override;
 };
 
 class MigrateAction : public WrapperFrontendAction {
@@ -65,8 +65,8 @@
                     unsigned migrateAction);
 
 protected:
-  ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
-                                 StringRef InFile) override;
+  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
+                                                 StringRef InFile) override;
   bool BeginInvocation(CompilerInstance &CI) override;
 };
 
diff --git a/include/clang/ARCMigrate/FileRemapper.h b/include/clang/ARCMigrate/FileRemapper.h
index e094301..53b88e9 100644
--- a/include/clang/ARCMigrate/FileRemapper.h
+++ b/include/clang/ARCMigrate/FileRemapper.h
@@ -52,14 +52,14 @@
   bool overwriteOriginal(DiagnosticsEngine &Diag,
                          StringRef outputDir = StringRef());
 
-  void remap(StringRef filePath, llvm::MemoryBuffer *memBuf);
+  void remap(StringRef filePath, std::unique_ptr<llvm::MemoryBuffer> memBuf);
 
   void applyMappings(PreprocessorOptions &PPOpts) const;
 
   void clear(StringRef outputDir = StringRef());
 
 private:
-  void remap(const FileEntry *file, llvm::MemoryBuffer *memBuf);
+  void remap(const FileEntry *file, std::unique_ptr<llvm::MemoryBuffer> memBuf);
   void remap(const FileEntry *file, const FileEntry *newfile);
 
   const FileEntry *getOriginalFile(StringRef filePath);
diff --git a/include/clang/AST/ASTContext.h b/include/clang/AST/ASTContext.h
index 8134f6b..ef87fa6 100644
--- a/include/clang/AST/ASTContext.h
+++ b/include/clang/AST/ASTContext.h
@@ -30,6 +30,7 @@
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/PartialDiagnostic.h"
+#include "clang/Basic/SanitizerBlacklist.h"
 #include "clang/Basic/VersionTuple.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/FoldingSet.h"
@@ -74,6 +75,15 @@
     class FullComment;
   }
 
+  struct TypeInfo {
+    uint64_t Width;
+    unsigned Align;
+    bool AlignIsRequired : 1;
+    TypeInfo() : Width(0), Align(0), AlignIsRequired(false) {}
+    TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
+        : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
+  };
+
 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
 /// referred to throughout the semantic analysis of a file.
 class ASTContext : public RefCountedBase<ASTContext> {
@@ -144,8 +154,7 @@
     ObjCLayouts;
 
   /// \brief A cache from types to size and alignment information.
-  typedef llvm::DenseMap<const Type*,
-                         std::pair<uint64_t, unsigned> > TypeInfoMap;
+  typedef llvm::DenseMap<const Type *, struct TypeInfo> TypeInfoMap;
   mutable TypeInfoMap MemoizedTypeInfo;
 
   /// \brief A cache mapping from CXXRecordDecls to key functions.
@@ -384,6 +393,10 @@
   ///  this ASTContext object.
   LangOptions &LangOpts;
 
+  /// \brief Blacklist object that is used by sanitizers to decide which
+  /// entities should not be instrumented.
+  std::unique_ptr<SanitizerBlacklist> SanitizerBL;
+
   /// \brief The allocator used to create AST objects.
   ///
   /// AST objects are never destructed; rather, all memory associated with the
@@ -453,11 +466,12 @@
   /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
   /// NestedNameSpecifier or NestedNameSpecifierLoc.
   template <typename NodeT>
-  ParentVector getParents(const NodeT &Node) {
+  ArrayRef<ast_type_traits::DynTypedNode> getParents(const NodeT &Node) {
     return getParents(ast_type_traits::DynTypedNode::create(Node));
   }
 
-  ParentVector getParents(const ast_type_traits::DynTypedNode &Node);
+  ArrayRef<ast_type_traits::DynTypedNode>
+  getParents(const ast_type_traits::DynTypedNode &Node);
 
   const clang::PrintingPolicy &getPrintingPolicy() const {
     return PrintingPolicy;
@@ -508,6 +522,10 @@
   
   const LangOptions& getLangOpts() const { return LangOpts; }
 
+  const SanitizerBlacklist &getSanitizerBlacklist() const {
+    return *SanitizerBL;
+  }
+
   DiagnosticsEngine &getDiagnostics() const;
 
   FullSourceLoc getFullLoc(SourceLocation Loc) const {
@@ -912,6 +930,12 @@
   /// \brief Change the result type of a function type once it is deduced.
   void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
 
+  /// \brief Change the exception specification on a function once it is
+  /// delay-parsed, instantiated, or computed.
+  void adjustExceptionSpec(FunctionDecl *FD,
+                           const FunctionProtoType::ExceptionSpecInfo &ESI,
+                           bool AsWritten = false);
+
   /// \brief Return the uniqued reference to the type for a complex
   /// number with the specified element type.
   QualType getComplexType(QualType T) const;
@@ -1371,7 +1395,8 @@
   ///
   /// If \p Field is specified then record field names are also encoded.
   void getObjCEncodingForType(QualType T, std::string &S,
-                              const FieldDecl *Field=nullptr) const;
+                              const FieldDecl *Field=nullptr,
+                              QualType *NotEncodedT=nullptr) const;
 
   /// \brief Emit the Objective-C property type encoding for the given
   /// type \p T into \p S.
@@ -1581,7 +1606,7 @@
 
 private:
   CanQualType getFromTargetType(unsigned Type) const;
-  std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
+  TypeInfo getTypeInfoImpl(const Type *T) const;
 
   //===--------------------------------------------------------------------===//
   //                         Type Predicates.
@@ -1614,18 +1639,12 @@
   const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
 
   /// \brief Get the size and alignment of the specified complete type in bits.
-  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
-  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
-    return getTypeInfo(T.getTypePtr());
-  }
+  TypeInfo getTypeInfo(const Type *T) const;
+  TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
 
   /// \brief Return the size of the specified (complete) type \p T, in bits.
-  uint64_t getTypeSize(QualType T) const {
-    return getTypeInfo(T).first;
-  }
-  uint64_t getTypeSize(const Type *T) const {
-    return getTypeInfo(T).first;
-  }
+  uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
+  uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
 
   /// \brief Return the size of the character type, in bits.
   uint64_t getCharWidth() const {
@@ -1645,12 +1664,8 @@
 
   /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
   /// bits.
-  unsigned getTypeAlign(QualType T) const {
-    return getTypeInfo(T).second;
-  }
-  unsigned getTypeAlign(const Type *T) const {
-    return getTypeInfo(T).second;
-  }
+  unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
+  unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
 
   /// \brief Return the ABI-specified alignment of a (complete) type \p T, in 
   /// characters.
@@ -1664,6 +1679,11 @@
   std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
   std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
 
+  /// \brief Determine if the alignment the type has was required using an
+  /// alignment attribute.
+  bool isAlignmentRequired(const Type *T) const;
+  bool isAlignmentRequired(QualType T) const;
+
   /// \brief Return the "preferred" alignment of the specified type \p T for
   /// the current target, in bits.
   ///
@@ -2272,12 +2292,14 @@
                                   bool StructField = false,
                                   bool EncodeBlockParameters = false,
                                   bool EncodeClassNames = false,
-                                  bool EncodePointerToObjCTypedef = false) const;
+                                  bool EncodePointerToObjCTypedef = false,
+                                  QualType *NotEncodedT=nullptr) const;
 
   // Adds the encoding of the structure's members.
   void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
                                        const FieldDecl *Field,
-                                       bool includeVBases = true) const;
+                                       bool includeVBases = true,
+                                       QualType *NotEncodedT=nullptr) const;
 public:
   // Adds the encoding of a method parameter or return type.
   void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
@@ -2312,6 +2334,31 @@
   std::unique_ptr<ParentMap> AllParents;
 
   std::unique_ptr<VTableContextBase> VTContext;
+
+public:
+  enum PragmaSectionFlag : unsigned {
+    PSF_None = 0,
+    PSF_Read = 0x1,
+    PSF_Write = 0x2,
+    PSF_Execute = 0x4,
+    PSF_Implicit = 0x8,
+    PSF_Invalid = 0x80000000U,
+  };
+
+  struct SectionInfo {
+    DeclaratorDecl *Decl;
+    SourceLocation PragmaSectionLocation;
+    int SectionFlags;
+    SectionInfo() {}
+    SectionInfo(DeclaratorDecl *Decl,
+                SourceLocation PragmaSectionLocation,
+                int SectionFlags)
+      : Decl(Decl),
+        PragmaSectionLocation(PragmaSectionLocation),
+        SectionFlags(SectionFlags) {}
+  };
+
+  llvm::StringMap<SectionInfo> SectionInfos;
 };
 
 /// \brief Utility function for constructing a nullary selector.
@@ -2349,9 +2396,9 @@
 /// // Specific alignment
 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
 /// @endcode
-/// Please note that you cannot use delete on the pointer; it must be
-/// deallocated using an explicit destructor call followed by
-/// @c Context.Deallocate(Ptr).
+/// Memory allocated through this placement new operator does not need to be
+/// explicitly freed, as ASTContext will free all of this memory when it gets
+/// destroyed. Please note that you cannot use delete on the pointer.
 ///
 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
 /// @param C The ASTContext that provides the allocator.
@@ -2386,9 +2433,9 @@
 /// // Specific alignment
 /// char *data = new (Context, 4) char[10];
 /// @endcode
-/// Please note that you cannot use delete on the pointer; it must be
-/// deallocated using an explicit destructor call followed by
-/// @c Context.Deallocate(Ptr).
+/// Memory allocated through this placement new[] operator does not need to be
+/// explicitly freed, as ASTContext will free all of this memory when it gets
+/// destroyed. Please note that you cannot use delete on the pointer.
 ///
 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
 /// @param C The ASTContext that provides the allocator.
diff --git a/include/clang/AST/ASTDiagnostic.h b/include/clang/AST/ASTDiagnostic.h
index 484ca4c..27c85e6 100644
--- a/include/clang/AST/ASTDiagnostic.h
+++ b/include/clang/AST/ASTDiagnostic.h
@@ -7,8 +7,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_DIAGNOSTICAST_H
-#define LLVM_CLANG_DIAGNOSTICAST_H
+#ifndef LLVM_CLANG_AST_ASTDIAGNOSTIC_H
+#define LLVM_CLANG_AST_ASTDIAGNOSTIC_H
 
 #include "clang/Basic/Diagnostic.h"
 
diff --git a/include/clang/AST/ASTFwd.h b/include/clang/AST/ASTFwd.h
index 4f32798..003d489 100644
--- a/include/clang/AST/ASTFwd.h
+++ b/include/clang/AST/ASTFwd.h
@@ -12,6 +12,9 @@
 ///
 //===-------------------------------------------------------------===//
 
+#ifndef LLVM_CLANG_AST_ASTFWD_H
+#define LLVM_CLANG_AST_ASTFWD_H
+
 namespace clang {
 
 class Decl;
@@ -26,3 +29,5 @@
 class CXXCtorInitializer;
 
 } // end namespace clang
+
+#endif
diff --git a/include/clang/AST/ASTLambda.h b/include/clang/AST/ASTLambda.h
index 9af016b..69df2d8 100644
--- a/include/clang/AST/ASTLambda.h
+++ b/include/clang/AST/ASTLambda.h
@@ -13,8 +13,8 @@
 ///
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_LAMBDA_H
-#define LLVM_CLANG_AST_LAMBDA_H
+#ifndef LLVM_CLANG_AST_ASTLAMBDA_H
+#define LLVM_CLANG_AST_ASTLAMBDA_H
 
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
@@ -77,4 +77,4 @@
 
 } // clang
 
-#endif // LLVM_CLANG_AST_LAMBDA_H
+#endif
diff --git a/include/clang/AST/ASTMutationListener.h b/include/clang/AST/ASTMutationListener.h
index a89bfed..48eb629 100644
--- a/include/clang/AST/ASTMutationListener.h
+++ b/include/clang/AST/ASTMutationListener.h
@@ -102,6 +102,12 @@
   /// \param D the declaration marked used
   virtual void DeclarationMarkedUsed(const Decl *D) {}
 
+  /// \brief A declaration is marked as OpenMP threadprivate which was not
+  /// previously marked as threadprivate.
+  ///
+  /// \param D the declaration marked OpenMP threadprivate.
+  virtual void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {}
+
   // NOTE: If new methods are added they should also be added to
   // MultiplexASTMutationListener.
 };
diff --git a/include/clang/AST/ASTTypeTraits.h b/include/clang/AST/ASTTypeTraits.h
index 0e06e26..4fe9a3f 100644
--- a/include/clang/AST/ASTTypeTraits.h
+++ b/include/clang/AST/ASTTypeTraits.h
@@ -13,8 +13,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_AST_TYPE_TRAITS_H
-#define LLVM_CLANG_AST_AST_TYPE_TRAITS_H
+#ifndef LLVM_CLANG_AST_ASTTYPETRAITS_H
+#define LLVM_CLANG_AST_ASTTYPETRAITS_H
 
 #include "clang/AST/ASTFwd.h"
 #include "clang/AST/Decl.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 {
@@ -53,9 +54,19 @@
     return ASTNodeKind(KindToKindId<T>::Id);
   }
 
+  /// \{
+  /// \brief Construct an identifier for the dynamic type of the node
+  static ASTNodeKind getFromNode(const Decl &D);
+  static ASTNodeKind getFromNode(const Stmt &S);
+  static ASTNodeKind getFromNode(const Type &T);
+  /// \}
+
   /// \brief Returns \c true if \c this and \c Other represent the same kind.
   bool isSame(ASTNodeKind Other) const;
 
+  /// \brief Returns \c true only for the default \c ASTNodeKind()
+  bool isNone() const { return KindId == NKI_None; }
+
   /// \brief Returns \c true if \c this is a base kind of (or same as) \c Other.
   /// \param Distance If non-null, used to return the distance between \c this
   /// and \c Other in the class hierarchy.
@@ -69,6 +80,32 @@
     return KindId < Other.KindId;
   }
 
+  /// \brief Return the most derived type between \p Kind1 and \p Kind2.
+  ///
+  /// Return ASTNodeKind() if they are not related.
+  static ASTNodeKind getMostDerivedType(ASTNodeKind Kind1, ASTNodeKind Kind2);
+
+  /// \brief Return the most derived common ancestor between Kind1 and Kind2.
+  ///
+  /// Return ASTNodeKind() if they are not related.
+  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.
   ///
@@ -184,12 +221,14 @@
     return BaseConverter<T>::get(NodeKind, Storage.buffer);
   }
 
+  ASTNodeKind getNodeKind() const { return NodeKind; }
+
   /// \brief Returns a pointer that identifies the stored AST node.
   ///
   /// Note that this is not supported by all AST nodes. For AST nodes
   /// that don't have a pointer-defined identity inside the AST, this
   /// method returns NULL.
-  const void *getMemoizationData() const;
+  const void *getMemoizationData() const { return MemoizationData; }
 
   /// \brief Prints the node to the given output stream.
   void print(llvm::raw_ostream &OS, const PrintingPolicy &PP) const;
@@ -241,7 +280,8 @@
     }
     static DynTypedNode create(const BaseT &Node) {
       DynTypedNode Result;
-      Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
+      Result.NodeKind = ASTNodeKind::getFromNode(Node);
+      Result.MemoizationData = &Node;
       new (Result.Storage.buffer) const BaseT * (&Node);
       return Result;
     }
@@ -257,6 +297,7 @@
     static DynTypedNode create(const T &Node) {
       DynTypedNode Result;
       Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
+      Result.MemoizationData = &Node;
       new (Result.Storage.buffer) const T * (&Node);
       return Result;
     }
@@ -272,12 +313,14 @@
     static DynTypedNode create(const T &Node) {
       DynTypedNode Result;
       Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
+      Result.MemoizationData = nullptr;
       new (Result.Storage.buffer) T(Node);
       return Result;
     }
   };
 
   ASTNodeKind NodeKind;
+  const void *MemoizationData;
 
   /// \brief Stores the data of the node.
   ///
@@ -345,20 +388,15 @@
   }
 };
 
-inline const void *DynTypedNode::getMemoizationData() const {
-  if (ASTNodeKind::getFromNodeKind<Decl>().isBaseOf(NodeKind)) {
-    return BaseConverter<Decl>::get(NodeKind, Storage.buffer);
-  } else if (ASTNodeKind::getFromNodeKind<Stmt>().isBaseOf(NodeKind)) {
-    return BaseConverter<Stmt>::get(NodeKind, Storage.buffer);
-  } else if (ASTNodeKind::getFromNodeKind<Type>().isBaseOf(NodeKind)) {
-    return BaseConverter<Type>::get(NodeKind, Storage.buffer);
-  } else if (ASTNodeKind::getFromNodeKind<NestedNameSpecifier>().isBaseOf(NodeKind)) {
-    return BaseConverter<NestedNameSpecifier>::get(NodeKind, Storage.buffer);
-  }
-  return nullptr;
-}
-
 } // end namespace ast_type_traits
 } // end namespace clang
 
-#endif // LLVM_CLANG_AST_AST_TYPE_TRAITS_H
+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/ASTVector.h b/include/clang/AST/ASTVector.h
index d92167e..6ec0545 100644
--- a/include/clang/AST/ASTVector.h
+++ b/include/clang/AST/ASTVector.h
@@ -15,8 +15,8 @@
 // FIXME: Most of this is copy-and-paste from BumpVector.h and SmallVector.h.
 // We can refactor this core logic into something common.
 
-#ifndef LLVM_CLANG_AST_VECTOR
-#define LLVM_CLANG_AST_VECTOR
+#ifndef LLVM_CLANG_AST_ASTVECTOR_H
+#define LLVM_CLANG_AST_ASTVECTOR_H
 
 #include "clang/AST/AttrIterator.h"
 #include "llvm/ADT/PointerIntPair.h"
@@ -236,14 +236,14 @@
 
   iterator insert(const ASTContext &C, iterator I, size_type NumToInsert,
                   const T &Elt) {
-    if (I == this->end()) {  // Important special case for empty vector.
-      append(C, NumToInsert, Elt);
-      return this->end()-1;
-    }
-
     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
     size_t InsertElt = I - this->begin();
 
+    if (I == this->end()) { // Important special case for empty vector.
+      append(C, NumToInsert, Elt);
+      return this->begin() + InsertElt;
+    }
+
     // Ensure there is enough space.
     reserve(C, static_cast<unsigned>(this->size() + NumToInsert));
 
@@ -284,14 +284,15 @@
 
   template<typename ItTy>
   iterator insert(const ASTContext &C, iterator I, ItTy From, ItTy To) {
-    if (I == this->end()) {  // Important special case for empty vector.
+    // Convert iterator to elt# to avoid invalidating iterator when we reserve()
+    size_t InsertElt = I - this->begin();
+
+    if (I == this->end()) { // Important special case for empty vector.
       append(C, From, To);
-      return this->end()-1;
+      return this->begin() + InsertElt;
     }
 
     size_t NumToInsert = std::distance(From, To);
-    // Convert iterator to elt# to avoid invalidating iterator when we reserve()
-    size_t InsertElt = I - this->begin();
 
     // Ensure there is enough space.
     reserve(C, static_cast<unsigned>(this->size() + NumToInsert));
diff --git a/include/clang/AST/Attr.h b/include/clang/AST/Attr.h
index fc48816..787843e 100644
--- a/include/clang/AST/Attr.h
+++ b/include/clang/AST/Attr.h
@@ -16,6 +16,7 @@
 
 #include "clang/AST/AttrIterator.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/AttrKinds.h"
 #include "clang/Basic/LLVM.h"
diff --git a/include/clang/AST/CanonicalType.h b/include/clang/AST/CanonicalType.h
index 7cccef6..aa3c846 100644
--- a/include/clang/AST/CanonicalType.h
+++ b/include/clang/AST/CanonicalType.h
@@ -12,8 +12,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_CANONICAL_TYPE_H
-#define LLVM_CLANG_AST_CANONICAL_TYPE_H
+#ifndef LLVM_CLANG_AST_CANONICALTYPE_H
+#define LLVM_CLANG_AST_CANONICALTYPE_H
 
 #include "clang/AST/Type.h"
 #include "llvm/Support/Casting.h"
@@ -736,4 +736,4 @@
 }
 
 
-#endif // LLVM_CLANG_AST_CANONICAL_TYPE_H
+#endif
diff --git a/include/clang/AST/Comment.h b/include/clang/AST/Comment.h
index e18fe9a..94470cb 100644
--- a/include/clang/AST/Comment.h
+++ b/include/clang/AST/Comment.h
@@ -96,9 +96,10 @@
     unsigned : NumInlineContentCommentBits;
 
     unsigned RenderKind : 2;
-    unsigned CommandID : 8;
+    unsigned CommandID : CommandInfo::NumCommandIDBits;
   };
-  enum { NumInlineCommandCommentBits = NumInlineContentCommentBits + 10 };
+  enum { NumInlineCommandCommentBits = NumInlineContentCommentBits + 2 + 
+                                       CommandInfo::NumCommandIDBits };
 
   class HTMLTagCommentBitfields {
     friend class HTMLTagComment;
@@ -139,13 +140,14 @@
 
     unsigned : NumCommentBits;
 
-    unsigned CommandID : 8;
+    unsigned CommandID : CommandInfo::NumCommandIDBits;
 
     /// Describes the syntax that was used in a documentation command.
     /// Contains values from CommandMarkerKind enum.
     unsigned CommandMarker : 1;
   };
-  enum { NumBlockCommandCommentBits = NumCommentBits + 9 };
+  enum { NumBlockCommandCommentBits = NumCommentBits + 
+                                      CommandInfo::NumCommandIDBits + 1 };
 
   class ParamCommandCommentBitfields {
     friend class ParamCommandComment;
diff --git a/include/clang/AST/CommentBriefParser.h b/include/clang/AST/CommentBriefParser.h
index 5d50886..be5b8ee 100644
--- a/include/clang/AST/CommentBriefParser.h
+++ b/include/clang/AST/CommentBriefParser.h
@@ -12,8 +12,8 @@
 //===----------------------------------------------------------------------===//
 
 
-#ifndef LLVM_CLANG_AST_BRIEF_COMMENT_PARSER_H
-#define LLVM_CLANG_AST_BRIEF_COMMENT_PARSER_H
+#ifndef LLVM_CLANG_AST_COMMENTBRIEFPARSER_H
+#define LLVM_CLANG_AST_COMMENTBRIEFPARSER_H
 
 #include "clang/AST/CommentLexer.h"
 
diff --git a/include/clang/AST/CommentCommandTraits.h b/include/clang/AST/CommentCommandTraits.h
index dde7a14..ec6d83c 100644
--- a/include/clang/AST/CommentCommandTraits.h
+++ b/include/clang/AST/CommentCommandTraits.h
@@ -13,8 +13,8 @@
 //===----------------------------------------------------------------------===//
 
 
-#ifndef LLVM_CLANG_AST_COMMENT_COMMAND_TRAITS_H
-#define LLVM_CLANG_AST_COMMENT_COMMAND_TRAITS_H
+#ifndef LLVM_CLANG_AST_COMMENTCOMMANDTRAITS_H
+#define LLVM_CLANG_AST_COMMENTCOMMANDTRAITS_H
 
 #include "clang/Basic/CommentOptions.h"
 #include "clang/Basic/LLVM.h"
@@ -40,7 +40,11 @@
   /// Name of the command that ends the verbatim block.
   const char *EndCommandName;
 
-  unsigned ID : 8;
+  /// DRY definition of the number of bits used for a command ID.
+  enum { NumCommandIDBits = 20 };
+
+  /// The ID of the command.
+  unsigned ID : NumCommandIDBits;
 
   /// Number of word-like arguments for a given block command, except for
   /// \\param and \\tparam commands -- these have special argument parsers.
diff --git a/include/clang/AST/CommentDiagnostic.h b/include/clang/AST/CommentDiagnostic.h
index 312da06..f3a209b 100644
--- a/include/clang/AST/CommentDiagnostic.h
+++ b/include/clang/AST/CommentDiagnostic.h
@@ -7,8 +7,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_COMMENTDIAGNOSTIC_H
-#define LLVM_CLANG_COMMENTDIAGNOSTIC_H
+#ifndef LLVM_CLANG_AST_COMMENTDIAGNOSTIC_H
+#define LLVM_CLANG_AST_COMMENTDIAGNOSTIC_H
 
 #include "clang/Basic/Diagnostic.h"
 
diff --git a/include/clang/AST/CommentLexer.h b/include/clang/AST/CommentLexer.h
index a6e3ed8..d995df9 100644
--- a/include/clang/AST/CommentLexer.h
+++ b/include/clang/AST/CommentLexer.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_COMMENT_LEXER_H
-#define LLVM_CLANG_AST_COMMENT_LEXER_H
+#ifndef LLVM_CLANG_AST_COMMENTLEXER_H
+#define LLVM_CLANG_AST_COMMENTLEXER_H
 
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/SourceManager.h"
diff --git a/include/clang/AST/CommentParser.h b/include/clang/AST/CommentParser.h
index 7e00813..2c444f0 100644
--- a/include/clang/AST/CommentParser.h
+++ b/include/clang/AST/CommentParser.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_COMMENT_PARSER_H
-#define LLVM_CLANG_AST_COMMENT_PARSER_H
+#ifndef LLVM_CLANG_AST_COMMENTPARSER_H
+#define LLVM_CLANG_AST_COMMENTPARSER_H
 
 #include "clang/AST/Comment.h"
 #include "clang/AST/CommentLexer.h"
diff --git a/include/clang/AST/CommentSema.h b/include/clang/AST/CommentSema.h
index 027c3b9..4ae6fe0 100644
--- a/include/clang/AST/CommentSema.h
+++ b/include/clang/AST/CommentSema.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_COMMENT_SEMA_H
-#define LLVM_CLANG_AST_COMMENT_SEMA_H
+#ifndef LLVM_CLANG_AST_COMMENTSEMA_H
+#define LLVM_CLANG_AST_COMMENTSEMA_H
 
 #include "clang/AST/Comment.h"
 #include "clang/Basic/Diagnostic.h"
@@ -85,7 +85,7 @@
       std::uninitialized_copy(Source.begin(), Source.end(), Mem);
       return llvm::makeArrayRef(Mem, Size);
     }
-    return ArrayRef<T>();
+    return None;
   }
 
   ParagraphComment *actOnParagraphComment(
diff --git a/include/clang/AST/DataRecursiveASTVisitor.h b/include/clang/AST/DataRecursiveASTVisitor.h
index 9ef0087..c0526e1 100644
--- a/include/clang/AST/DataRecursiveASTVisitor.h
+++ b/include/clang/AST/DataRecursiveASTVisitor.h
@@ -424,6 +424,7 @@
   bool TraverseFunctionHelper(FunctionDecl *D);
   bool TraverseVarHelper(VarDecl *D);
   bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
+  bool TraverseOMPLoopDirective(OMPLoopDirective *S);
   bool TraverseOMPClause(OMPClause *C);
 #define OPENMP_CLAUSE(Name, Class) bool Visit##Class(Class *C);
 #include "clang/Basic/OpenMPKinds.def"
@@ -623,6 +624,7 @@
   case NestedNameSpecifier::Namespace:
   case NestedNameSpecifier::NamespaceAlias:
   case NestedNameSpecifier::Global:
+  case NestedNameSpecifier::Super:
     return true;
 
   case NestedNameSpecifier::TypeSpec:
@@ -647,6 +649,7 @@
   case NestedNameSpecifier::Namespace:
   case NestedNameSpecifier::NamespaceAlias:
   case NestedNameSpecifier::Global:
+  case NestedNameSpecifier::Super:
     return true;
 
   case NestedNameSpecifier::TypeSpec:
@@ -875,6 +878,9 @@
   for (const auto &E : T->exceptions()) {
     TRY_TO(TraverseType(E));
   }
+
+  if (Expr *NE = T->getNoexceptExpr())
+    TRY_TO(TraverseStmt(NE));
 })
 
 DEF_TRAVERSE_TYPE(UnresolvedUsingType, {})
@@ -1083,6 +1089,9 @@
   for (const auto &E : T->exceptions()) {
     TRY_TO(TraverseType(E));
   }
+
+  if (Expr *NE = T->getNoexceptExpr())
+    TRY_TO(TraverseStmt(NE));
 })
 
 DEF_TRAVERSE_TYPELOC(UnresolvedUsingType, {})
@@ -2122,21 +2131,29 @@
     TRY_TO(TraverseLambdaCapture(S, C));
   }
 
-  if (S->hasExplicitParameters() || S->hasExplicitResultType()) {
-    TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
-    if (S->hasExplicitParameters() && S->hasExplicitResultType()) {
-      // Visit the whole type.
-      TRY_TO(TraverseTypeLoc(TL));
-    } else if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
-      if (S->hasExplicitParameters()) {
-        // Visit parameters.
-        for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) {
-          TRY_TO(TraverseDecl(Proto.getParam(I)));
-        }
-      } else {
-        TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
+  TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
+  FunctionProtoTypeLoc Proto = TL.castAs<FunctionProtoTypeLoc>();
+
+  if (S->hasExplicitParameters() && S->hasExplicitResultType()) {
+    // Visit the whole type.
+    TRY_TO(TraverseTypeLoc(TL));
+  } else {
+    if (S->hasExplicitParameters()) {
+      // Visit parameters.
+      for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) {
+        TRY_TO(TraverseDecl(Proto.getParam(I)));
       }
+    } else if (S->hasExplicitResultType()) {
+      TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
     }
+
+    auto *T = Proto.getTypePtr();
+    for (const auto &E : T->exceptions()) {
+      TRY_TO(TraverseType(E));
+    }
+
+    if (Expr *NE = T->getNoexceptExpr())
+      TRY_TO(TraverseStmt(NE));
   }
 
   TRY_TO(TraverseLambdaBody(S));
@@ -2237,6 +2254,7 @@
 
 DEF_TRAVERSE_STMT(CXXOperatorCallExpr, {})
 DEF_TRAVERSE_STMT(OpaqueValueExpr, {})
+DEF_TRAVERSE_STMT(TypoExpr, {})
 DEF_TRAVERSE_STMT(CUDAKernelCallExpr, {})
 
 // These operators (all of them) do not need any action except
@@ -2253,6 +2271,7 @@
 DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmExpr, {})
 DEF_TRAVERSE_STMT(FunctionParmPackExpr, {})
 DEF_TRAVERSE_STMT(MaterializeTemporaryExpr, {})
+DEF_TRAVERSE_STMT(CXXFoldExpr, {})
 DEF_TRAVERSE_STMT(AtomicExpr, {})
 
 // These literals (all of them) do not need any action.
@@ -2279,6 +2298,12 @@
   return true;
 }
 
+template <typename Derived>
+bool
+RecursiveASTVisitor<Derived>::TraverseOMPLoopDirective(OMPLoopDirective *S) {
+  return TraverseOMPExecutableDirective(S);
+}
+
 DEF_TRAVERSE_STMT(OMPParallelDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
@@ -2288,6 +2313,9 @@
 DEF_TRAVERSE_STMT(OMPForDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
+DEF_TRAVERSE_STMT(OMPForSimdDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
 DEF_TRAVERSE_STMT(OMPSectionsDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
@@ -2308,6 +2336,9 @@
 DEF_TRAVERSE_STMT(OMPParallelForDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
+DEF_TRAVERSE_STMT(OMPParallelForSimdDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
 DEF_TRAVERSE_STMT(OMPParallelSectionsDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
@@ -2326,6 +2357,18 @@
 DEF_TRAVERSE_STMT(OMPFlushDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
+DEF_TRAVERSE_STMT(OMPOrderedDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
+DEF_TRAVERSE_STMT(OMPAtomicDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
+DEF_TRAVERSE_STMT(OMPTargetDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
+DEF_TRAVERSE_STMT(OMPTeamsDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
 // OpenMP clauses.
 template <typename Derived>
 bool RecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
@@ -2415,6 +2458,31 @@
 }
 
 template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPReadClause(OMPReadClause *) {
+  return true;
+}
+
+template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPWriteClause(OMPWriteClause *) {
+  return true;
+}
+
+template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPUpdateClause(OMPUpdateClause *) {
+  return true;
+}
+
+template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPCaptureClause(OMPCaptureClause *) {
+  return true;
+}
+
+template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPSeqCstClause(OMPSeqCstClause *) {
+  return true;
+}
+
+template <typename Derived>
 template <typename T>
 bool RecursiveASTVisitor<Derived>::VisitOMPClauseList(T *Node) {
   for (auto *E : Node->varlists()) {
@@ -2426,6 +2494,9 @@
 template <typename Derived>
 bool RecursiveASTVisitor<Derived>::VisitOMPPrivateClause(OMPPrivateClause *C) {
   TRY_TO(VisitOMPClauseList(C));
+  for (auto *E : C->private_copies()) {
+    TRY_TO(TraverseStmt(E));
+  }
   return true;
 }
 
@@ -2433,6 +2504,12 @@
 bool RecursiveASTVisitor<Derived>::VisitOMPFirstprivateClause(
     OMPFirstprivateClause *C) {
   TRY_TO(VisitOMPClauseList(C));
+  for (auto *E : C->private_copies()) {
+    TRY_TO(TraverseStmt(E));
+  }
+  for (auto *E : C->inits()) {
+    TRY_TO(TraverseStmt(E));
+  }
   return true;
 }
 
diff --git a/include/clang/AST/Decl.h b/include/clang/AST/Decl.h
index ce8b8b7..b946636 100644
--- a/include/clang/AST/Decl.h
+++ b/include/clang/AST/Decl.h
@@ -43,6 +43,7 @@
 class StringLiteral;
 class TemplateArgumentList;
 class TemplateParameterList;
+class TypeAliasTemplateDecl;
 class TypeLoc;
 class UnresolvedSetImpl;
 class VarTemplateDecl;
@@ -67,6 +68,9 @@
 
   /// \brief Return the TypeLoc wrapper for the type source info.
   TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
+  
+  /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
+  void overrideType(QualType T) { Ty = T; }
 };
 
 /// TranslationUnitDecl - The top declaration context.
@@ -288,6 +292,8 @@
     return const_cast<NamedDecl*>(this)->getMostRecentDecl();
   }
 
+  ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
+
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
 };
@@ -305,6 +311,8 @@
 class LabelDecl : public NamedDecl {
   void anchor() override;
   LabelStmt *TheStmt;
+  StringRef MSAsmName;
+  bool MSAsmNameResolved;
   /// LocStart - For normal labels, this is the same as the main declaration
   /// label, i.e., the location of the identifier; for GNU local labels,
   /// this is the location of the __label__ keyword.
@@ -312,7 +320,10 @@
 
   LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
             LabelStmt *S, SourceLocation StartL)
-    : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
+    : NamedDecl(Label, DC, IdentL, II),
+      TheStmt(S),
+      MSAsmNameResolved(false),
+      LocStart(StartL) {}
 
 public:
   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
@@ -332,6 +343,12 @@
     return SourceRange(LocStart, getLocation());
   }
 
+  bool isMSAsmLabel() const { return MSAsmName.size() != 0; }
+  bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
+  void setMSAsmLabel(StringRef Name);
+  StringRef getMSAsmLabel() const { return MSAsmName; }
+  void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == Label; }
@@ -648,8 +665,6 @@
 /// declaration or definition.
 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
 public:
-  typedef clang::StorageClass StorageClass;
-
   /// getStorageClassSpecifierString - Return the string used to
   /// specify the storage class \p SC.
   ///
@@ -1423,8 +1438,6 @@
 class FunctionDecl : public DeclaratorDecl, public DeclContext,
                      public Redeclarable<FunctionDecl> {
 public:
-  typedef clang::StorageClass StorageClass;
-
   /// \brief The kind of templated function a FunctionDecl can be.
   enum TemplatedKind {
     TK_NonTemplate,
@@ -1650,7 +1663,7 @@
   /// unnecessary AST de-serialization of the body.
   Stmt *getBody(const FunctionDecl *&Definition) const;
 
-   Stmt *getBody() const override {
+  Stmt *getBody() const override {
     const FunctionDecl* Definition;
     return getBody(Definition);
   }
@@ -1880,7 +1893,7 @@
     return llvm::makeArrayRef(ParamInfo, getNumParams());
   }
 
-  const ArrayRef<NamedDecl *> &getDeclsInPrototypeScope() const {
+  ArrayRef<NamedDecl *> getDeclsInPrototypeScope() const {
     return DeclsInPrototypeScope;
   }
   void setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls);
@@ -2154,17 +2167,41 @@
   bool Mutable : 1;
   mutable unsigned CachedFieldIndex : 31;
 
-  /// \brief An InClassInitStyle value, and either a bit width expression (if
-  /// the InClassInitStyle value is ICIS_NoInit), or a pointer to the in-class
-  /// initializer for this field (otherwise).
+  /// The kinds of value we can store in InitializerOrBitWidth.
   ///
-  /// We can safely combine these two because in-class initializers are not
-  /// permitted for bit-fields.
+  /// Note that this is compatible with InClassInitStyle except for
+  /// ISK_CapturedVLAType.
+  enum InitStorageKind {
+    /// If the pointer is null, there's nothing special.  Otherwise,
+    /// this is a bitfield and the pointer is the Expr* storing the
+    /// bit-width.
+    ISK_BitWidthOrNothing = (unsigned) ICIS_NoInit,
+
+    /// The pointer is an (optional due to delayed parsing) Expr*
+    /// holding the copy-initializer.
+    ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
+
+    /// The pointer is an (optional due to delayed parsing) Expr*
+    /// holding the list-initializer.
+    ISK_InClassListInit = (unsigned) ICIS_ListInit,
+
+    /// The pointer is a VariableArrayType* that's been captured;
+    /// the enclosing context is a lambda or captured statement.
+    ISK_CapturedVLAType,
+  };
+
+  /// \brief Storage for either the bit-width, the in-class
+  /// initializer, or the captured variable length array bound.
   ///
-  /// If the InClassInitStyle is not ICIS_NoInit and the initializer is null,
-  /// then this field has an in-class initializer which has not yet been parsed
+  /// We can safely combine these because in-class initializers are
+  /// not permitted for bit-fields, and both are exclusive with VLA
+  /// captures.
+  ///
+  /// If the storage kind is ISK_InClassCopyInit or
+  /// ISK_InClassListInit, but the initializer is null, then this
+  /// field has an in-class initializer which has not yet been parsed
   /// and attached.
-  llvm::PointerIntPair<Expr *, 2, unsigned> InitializerOrBitWidth;
+  llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
 protected:
   FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
             SourceLocation IdLoc, IdentifierInfo *Id,
@@ -2172,7 +2209,7 @@
             InClassInitStyle InitStyle)
     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
       Mutable(Mutable), CachedFieldIndex(0),
-      InitializerOrBitWidth(BW, InitStyle) {
+      InitStorage(BW, (InitStorageKind) InitStyle) {
     assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
   }
 
@@ -2192,10 +2229,10 @@
   /// isMutable - Determines whether this field is mutable (C++ only).
   bool isMutable() const { return Mutable; }
 
-  /// isBitfield - Determines whether this field is a bitfield.
+  /// \brief Determines whether this field is a bitfield.
   bool isBitField() const {
-    return getInClassInitStyle() == ICIS_NoInit &&
-           InitializerOrBitWidth.getPointer();
+    return InitStorage.getInt() == ISK_BitWidthOrNothing &&
+           InitStorage.getPointer() != nullptr;
   }
 
   /// @brief Determines whether this is an unnamed bitfield.
@@ -2208,24 +2245,34 @@
   bool isAnonymousStructOrUnion() const;
 
   Expr *getBitWidth() const {
-    return isBitField() ? InitializerOrBitWidth.getPointer() : nullptr;
+    return isBitField()
+               ? static_cast<Expr *>(InitStorage.getPointer())
+               : nullptr;
   }
   unsigned getBitWidthValue(const ASTContext &Ctx) const;
 
   /// setBitWidth - Set the bit-field width for this member.
   // Note: used by some clients (i.e., do not remove it).
-  void setBitWidth(Expr *Width);
+  void setBitWidth(Expr *Width) {
+    assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
+           InitStorage.getPointer() == nullptr &&
+           "bit width, initializer or captured type already set");
+    InitStorage.setPointerAndInt(Width, ISK_BitWidthOrNothing);
+  }
+
   /// removeBitWidth - Remove the bit-field width from this member.
   // Note: used by some clients (i.e., do not remove it).
   void removeBitWidth() {
     assert(isBitField() && "no bitfield width to remove");
-    InitializerOrBitWidth.setPointer(nullptr);
+    InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
   }
 
   /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
   /// this field has.
   InClassInitStyle getInClassInitStyle() const {
-    return static_cast<InClassInitStyle>(InitializerOrBitWidth.getInt());
+    InitStorageKind storageKind = InitStorage.getInt();
+    return (storageKind == ISK_CapturedVLAType
+              ? ICIS_NoInit : (InClassInitStyle) storageKind);
   }
 
   /// hasInClassInitializer - Determine whether this member has a C++11 in-class
@@ -2233,25 +2280,48 @@
   bool hasInClassInitializer() const {
     return getInClassInitStyle() != ICIS_NoInit;
   }
+
   /// getInClassInitializer - Get the C++11 in-class initializer for this
   /// member, or null if one has not been set. If a valid declaration has an
   /// in-class initializer, but this returns null, then we have not parsed and
   /// attached it yet.
   Expr *getInClassInitializer() const {
-    return hasInClassInitializer() ? InitializerOrBitWidth.getPointer()
-                                   : nullptr;
+    return hasInClassInitializer()
+               ? static_cast<Expr *>(InitStorage.getPointer())
+               : nullptr;
   }
+
   /// setInClassInitializer - Set the C++11 in-class initializer for this
   /// member.
-  void setInClassInitializer(Expr *Init);
+  void setInClassInitializer(Expr *Init) {
+    assert(hasInClassInitializer() &&
+           InitStorage.getPointer() == nullptr &&
+           "bit width, initializer or captured type already set");
+    InitStorage.setPointer(Init);
+  }
+
   /// removeInClassInitializer - Remove the C++11 in-class initializer from this
   /// member.
   void removeInClassInitializer() {
     assert(hasInClassInitializer() && "no initializer to remove");
-    InitializerOrBitWidth.setPointer(nullptr);
-    InitializerOrBitWidth.setInt(ICIS_NoInit);
+    InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
   }
 
+  /// \brief Determine whether this member captures the variable length array
+  /// type.
+  bool hasCapturedVLAType() const {
+    return InitStorage.getInt() == ISK_CapturedVLAType;
+  }
+
+  /// \brief Get the captured variable length array type.
+  const VariableArrayType *getCapturedVLAType() const {
+    return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
+                                      InitStorage.getPointer())
+                                : nullptr;
+  }
+  /// \brief Set the captured variable length array type for this field.
+  void setCapturedVLAType(const VariableArrayType *VLAType);
+
   /// getParent - Returns the parent of this field declaration, which
   /// is the struct in which this method is defined.
   const RecordDecl *getParent() const {
@@ -2492,9 +2562,13 @@
 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
 /// alias-declaration.
 class TypeAliasDecl : public TypedefNameDecl {
+  /// The template for which this is the pattern, if any.
+  TypeAliasTemplateDecl *Template;
+
   TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
                 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
-      : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo) {}
+      : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
+        Template(nullptr) {}
 
 public:
   static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
@@ -2504,6 +2578,9 @@
 
   SourceRange getSourceRange() const override LLVM_READONLY;
 
+  TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
+  void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == TypeAlias; }
@@ -2647,7 +2724,7 @@
   }
 
   /// isThisDeclarationADefinition() - Return true if this declaration
-  /// is a completion definintion of the type.  Provided for consistency.
+  /// is a completion definition of the type.  Provided for consistency.
   bool isThisDeclarationADefinition() const {
     return isCompleteDefinition();
   }
@@ -3136,6 +3213,17 @@
   /// \endcode
   bool isInjectedClassName() const;
 
+  /// \brief Determine whether this record is a class describing a lambda
+  /// function object.
+  bool isLambda() const;
+
+  /// \brief Determine whether this record is a record for captured variables in
+  /// CapturedStmt construct.
+  bool isCapturedRecord() const;
+  /// \brief Mark the record as a record for captured variables in CapturedStmt
+  /// construct.
+  void setCapturedRecord();
+
   /// getDefinition - Returns the RecordDecl that actually defines
   ///  this struct/union/class.  When determining whether or not a
   ///  struct/union/class is completely defined, one should use this
@@ -3181,6 +3269,11 @@
   /// commandline option.
   bool isMsStruct(const ASTContext &C) const;
 
+  /// \brief Whether we are allowed to insert extra padding between fields.
+  /// These padding are added to help AddressSanitizer detect
+  /// intra-object-overflow bugs.
+  bool mayInsertExtraPadding(bool EmitRemark = false) 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 607ca4e..984ab13 100644
--- a/include/clang/AST/DeclBase.h
+++ b/include/clang/AST/DeclBase.h
@@ -48,6 +48,7 @@
 class ObjCMethodDecl;
 class ObjCProtocolDecl;
 struct PrintingPolicy;
+class RecordDecl;
 class Stmt;
 class StoredDeclsMap;
 class TranslationUnitDecl;
@@ -515,9 +516,13 @@
   /// indicating the declaration is used.
   void markUsed(ASTContext &C);
 
-  /// \brief Whether this declaration was referenced.
+  /// \brief Whether any declaration of this entity was referenced.
   bool isReferenced() const;
 
+  /// \brief Whether this declaration was referenced. This should not be relied
+  /// upon for anything other than debugging.
+  bool isThisDeclarationReferenced() const { return Referenced; }
+
   void setReferenced(bool R = true) { Referenced = R; }
 
   /// \brief Whether this declaration is a top-level declaration (function,
@@ -675,9 +680,9 @@
     return const_cast<Decl*>(this)->getLexicalDeclContext();
   }
 
-  virtual bool isOutOfLine() const {
-    return getLexicalDeclContext() != getDeclContext();
-  }
+  /// Determine whether this declaration is declared out of line (outside its
+  /// semantic context).
+  virtual bool isOutOfLine() const;
 
   /// setDeclContext - Set both the semantic and lexical DeclContext
   /// to DC.
@@ -1234,6 +1239,12 @@
     return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
   }
 
+  /// \brief Retrieve the outermost lexically enclosing record context.
+  RecordDecl *getOuterLexicalRecordContext();
+  const RecordDecl *getOuterLexicalRecordContext() const {
+    return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
+  }
+
   /// \brief Test if this context is part of the enclosing namespace set of
   /// the context NS, as defined in C++0x [namespace.def]p9. If either context
   /// isn't a namespace, this is equivalent to Equals().
@@ -1642,7 +1653,7 @@
 
   void dumpDeclContext() const;
   void dumpLookups() const;
-  void dumpLookups(llvm::raw_ostream &OS) const;
+  void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false) const;
 
 private:
   void reconcileExternalVisibleStorage() const;
diff --git a/include/clang/AST/DeclCXX.h b/include/clang/AST/DeclCXX.h
index 72fad7c..062c152 100644
--- a/include/clang/AST/DeclCXX.h
+++ b/include/clang/AST/DeclCXX.h
@@ -538,6 +538,12 @@
         ManglingNumber(0), ContextDecl(nullptr), Captures(nullptr),
         MethodTyInfo(Info) {
       IsLambda = true;
+
+      // C++11 [expr.prim.lambda]p3:
+      //   This class type is neither an aggregate nor a literal type.
+      Aggregate = false;
+      PlainOldData = false;
+      HasNonLiteralTypeFieldsOrBases = true;
     }
 
     /// \brief Whether this lambda is known to be dependent, even if its
@@ -1371,6 +1377,15 @@
   /// \brief Set the kind of specialization or template instantiation this is.
   void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
 
+  /// \brief Retrieve the record declaration from which this record could be
+  /// instantiated. Returns null if this class is not a template instantiation.
+  const CXXRecordDecl *getTemplateInstantiationPattern() const;
+
+  CXXRecordDecl *getTemplateInstantiationPattern() {
+    return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
+                                           ->getTemplateInstantiationPattern());
+  }
+
   /// \brief Returns the destructor decl for this class.
   CXXDestructorDecl *getDestructor() const;
 
@@ -2104,8 +2119,8 @@
   }
   ArrayRef<VarDecl *> getArrayIndexes() {
     assert(getNumArrayIndices() != 0 && "Getting indexes for non-array init");
-    return ArrayRef<VarDecl *>(reinterpret_cast<VarDecl **>(this + 1),
-                               getNumArrayIndices());
+    return llvm::makeArrayRef(reinterpret_cast<VarDecl **>(this + 1),
+                              getNumArrayIndices());
   }
 
   /// \brief Get the initializer.
@@ -2636,7 +2651,8 @@
 /// \code
 /// namespace Foo = Bar;
 /// \endcode
-class NamespaceAliasDecl : public NamedDecl {
+class NamespaceAliasDecl : public NamedDecl,
+                           public Redeclarable<NamespaceAliasDecl> {
   void anchor() override;
 
   /// \brief The location of the \c namespace keyword.
@@ -2654,17 +2670,47 @@
   /// a NamespaceAliasDecl.
   NamedDecl *Namespace;
 
-  NamespaceAliasDecl(DeclContext *DC, SourceLocation NamespaceLoc,
-                     SourceLocation AliasLoc, IdentifierInfo *Alias,
-                     NestedNameSpecifierLoc QualifierLoc,
+  NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
+                     SourceLocation NamespaceLoc, SourceLocation AliasLoc,
+                     IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
                      SourceLocation IdentLoc, NamedDecl *Namespace)
-    : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias),
-      NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
-      QualifierLoc(QualifierLoc), Namespace(Namespace) { }
+      : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
+        NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
+        QualifierLoc(QualifierLoc), Namespace(Namespace) {}
+
+  typedef Redeclarable<NamespaceAliasDecl> redeclarable_base;
+  NamespaceAliasDecl *getNextRedeclarationImpl() override;
+  NamespaceAliasDecl *getPreviousDeclImpl() override;
+  NamespaceAliasDecl *getMostRecentDeclImpl() override;
 
   friend class ASTDeclReader;
 
 public:
+  static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
+                                    SourceLocation NamespaceLoc,
+                                    SourceLocation AliasLoc,
+                                    IdentifierInfo *Alias,
+                                    NestedNameSpecifierLoc QualifierLoc,
+                                    SourceLocation IdentLoc,
+                                    NamedDecl *Namespace);
+
+  static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+
+  typedef redeclarable_base::redecl_range redecl_range;
+  typedef redeclarable_base::redecl_iterator redecl_iterator;
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::redecls;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
+
+  NamespaceAliasDecl *getCanonicalDecl() override {
+    return getFirstDecl();
+  }
+  const NamespaceAliasDecl *getCanonicalDecl() const {
+    return getFirstDecl();
+  }
+
   /// \brief Retrieve the nested-name-specifier that qualifies the
   /// name of the namespace, with source-location information.
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
@@ -2701,16 +2747,6 @@
   /// may either be a NamespaceDecl or a NamespaceAliasDecl.
   NamedDecl *getAliasedNamespace() const { return Namespace; }
 
-  static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
-                                    SourceLocation NamespaceLoc,
-                                    SourceLocation AliasLoc,
-                                    IdentifierInfo *Alias,
-                                    NestedNameSpecifierLoc QualifierLoc,
-                                    SourceLocation IdentLoc,
-                                    NamedDecl *Namespace);
-
-  static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
-
   SourceRange getSourceRange() const override LLVM_READONLY {
     return SourceRange(NamespaceLoc, IdentLoc);
   }
@@ -2824,7 +2860,7 @@
 /// \code
 ///    using someNameSpace::someIdentifier;
 /// \endcode
-class UsingDecl : public NamedDecl {
+class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
   void anchor() override;
 
   /// \brief The source location of the 'using' keyword itself.
@@ -2948,6 +2984,10 @@
 
   SourceRange getSourceRange() const override LLVM_READONLY;
 
+  /// Retrieves the canonical declaration of this declaration.
+  UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
+  const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
+
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == Using; }
 
@@ -2966,7 +3006,8 @@
 ///   using Base<T>::foo;
 /// };
 /// \endcode
-class UnresolvedUsingValueDecl : public ValueDecl {
+class UnresolvedUsingValueDecl : public ValueDecl,
+                                 public Mergeable<UnresolvedUsingValueDecl> {
   void anchor() override;
 
   /// \brief The source location of the 'using' keyword
@@ -3022,6 +3063,14 @@
 
   SourceRange getSourceRange() const override LLVM_READONLY;
 
+  /// Retrieves the canonical declaration of this declaration.
+  UnresolvedUsingValueDecl *getCanonicalDecl() override {
+    return getFirstDecl();
+  }
+  const UnresolvedUsingValueDecl *getCanonicalDecl() const {
+    return getFirstDecl();
+  }
+
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
 
@@ -3040,7 +3089,9 @@
 ///
 /// The type associated with an unresolved using typename decl is
 /// currently always a typename type.
-class UnresolvedUsingTypenameDecl : public TypeDecl {
+class UnresolvedUsingTypenameDecl
+    : public TypeDecl,
+      public Mergeable<UnresolvedUsingTypenameDecl> {
   void anchor() override;
 
   /// \brief The source location of the 'typename' keyword
@@ -3084,6 +3135,14 @@
   static UnresolvedUsingTypenameDecl *
   CreateDeserialized(ASTContext &C, unsigned ID);
 
+  /// Retrieves the canonical declaration of this declaration.
+  UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
+    return getFirstDecl();
+  }
+  const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
+    return getFirstDecl();
+  }
+
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
 };
diff --git a/include/clang/AST/DeclObjC.h b/include/clang/AST/DeclObjC.h
index db3b084..55d4b0f 100644
--- a/include/clang/AST/DeclObjC.h
+++ b/include/clang/AST/DeclObjC.h
@@ -329,6 +329,7 @@
 
   QualType getReturnType() const { return MethodDeclType; }
   void setReturnType(QualType T) { MethodDeclType = T; }
+  SourceRange getReturnTypeSourceRange() const;
 
   /// \brief Determine the type of an expression that sends a message to this
   /// function.
@@ -378,8 +379,7 @@
   /// ignored.
   void setMethodParams(ASTContext &C,
                        ArrayRef<ParmVarDecl*> Params,
-                       ArrayRef<SourceLocation> SelLocs =
-                           ArrayRef<SourceLocation>());
+                       ArrayRef<SourceLocation> SelLocs = llvm::None);
 
   // Iterator access to parameter types.
   typedef std::const_mem_fun_t<QualType, ParmVarDecl> deref_fun;
@@ -591,7 +591,8 @@
   bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
   ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
 
-  ObjCPropertyDecl *FindPropertyDeclaration(IdentifierInfo *PropertyId) const;
+  ObjCPropertyDecl *
+  FindPropertyDeclaration(const IdentifierInfo *PropertyId) const;
 
   typedef llvm::DenseMap<IdentifierInfo*, ObjCPropertyDecl*> PropertyMap;
   
@@ -2354,7 +2355,7 @@
 
   /// Lookup a property by name in the specified DeclContext.
   static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
-                                            IdentifierInfo *propertyID);
+                                            const IdentifierInfo *propertyID);
 
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == ObjCProperty; }
diff --git a/include/clang/AST/DeclOpenMP.h b/include/clang/AST/DeclOpenMP.h
index 1b329dc..7f0616f 100644
--- a/include/clang/AST/DeclOpenMP.h
+++ b/include/clang/AST/DeclOpenMP.h
@@ -12,13 +12,14 @@
 ///
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_OPENMP_H
-#define LLVM_CLANG_AST_OPENMP_H
+#ifndef LLVM_CLANG_AST_DECLOPENMP_H
+#define LLVM_CLANG_AST_DECLOPENMP_H
 
 #include "clang/AST/DeclBase.h"
 #include "llvm/ADT/ArrayRef.h"
 
 namespace clang {
+class Expr;
 
 /// \brief This represents '#pragma omp threadprivate ...' directive.
 /// For example, in the following, both 'a' and 'A::b' are threadprivate:
@@ -42,9 +43,8 @@
     Decl(DK, DC, L), NumVars(0) { }
 
   ArrayRef<const Expr *> getVars() const {
-    return ArrayRef<const Expr *>(
-                   reinterpret_cast<const Expr * const *>(this + 1),
-                   NumVars);
+    return llvm::makeArrayRef(reinterpret_cast<const Expr * const *>(this + 1),
+                              NumVars);
   }
 
   MutableArrayRef<Expr *> getVars() {
diff --git a/include/clang/AST/DeclTemplate.h b/include/clang/AST/DeclTemplate.h
index 980a06e..9283d2d 100644
--- a/include/clang/AST/DeclTemplate.h
+++ b/include/clang/AST/DeclTemplate.h
@@ -87,10 +87,10 @@
   unsigned size() const { return NumParams; }
 
   ArrayRef<NamedDecl*> asArray() {
-    return ArrayRef<NamedDecl*>(begin(), size());
+    return llvm::makeArrayRef(begin(), end());
   }
   ArrayRef<const NamedDecl*> asArray() const {
-    return ArrayRef<const NamedDecl*>(begin(), size());
+    return llvm::makeArrayRef(begin(), size());
   }
 
   NamedDecl* getParam(unsigned Idx) {
@@ -204,7 +204,7 @@
 
   /// \brief Produce this as an array ref.
   ArrayRef<TemplateArgument> asArray() const {
-    return ArrayRef<TemplateArgument>(data(), size());
+    return llvm::makeArrayRef(data(), size());
   }
 
   /// \brief Retrieve the number of template arguments in this
@@ -236,7 +236,7 @@
       TemplateParams(nullptr) {}
 
   // Construct a template decl with the given name and parameters.
-  // Used when there is not templated element (tt-params, alias?).
+  // Used when there is not templated element (tt-params).
   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
                DeclarationName Name, TemplateParameterList *Params)
     : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
diff --git a/include/clang/AST/DeclarationName.h b/include/clang/AST/DeclarationName.h
index 3076b30..49e51e0 100644
--- a/include/clang/AST/DeclarationName.h
+++ b/include/clang/AST/DeclarationName.h
@@ -59,6 +59,7 @@
     CXXLiteralOperatorName,
     CXXUsingDirective
   };
+  static const unsigned NumNameKinds = CXXUsingDirective + 1;
 
 private:
   /// StoredNameKind - The kind of name that is actually stored in the
diff --git a/include/clang/AST/DependentDiagnostic.h b/include/clang/AST/DependentDiagnostic.h
index 63047ec..6306679 100644
--- a/include/clang/AST/DependentDiagnostic.h
+++ b/include/clang/AST/DependentDiagnostic.h
@@ -15,8 +15,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_DEPENDENT_DIAGNOSTIC_H
-#define LLVM_CLANG_AST_DEPENDENT_DIAGNOSTIC_H
+#ifndef LLVM_CLANG_AST_DEPENDENTDIAGNOSTIC_H
+#define LLVM_CLANG_AST_DEPENDENTDIAGNOSTIC_H
 
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/DeclContextInternals.h"
diff --git a/include/clang/AST/Expr.h b/include/clang/AST/Expr.h
index b4bb0b6..d94e225 100644
--- a/include/clang/AST/Expr.h
+++ b/include/clang/AST/Expr.h
@@ -45,6 +45,7 @@
   class ObjCPropertyRefExpr;
   class OpaqueValueExpr;
   class ParmVarDecl;
+  class StringLiteral;
   class TargetInfo;
   class ValueDecl;
 
@@ -124,8 +125,7 @@
   QualType getType() const { return TR; }
   void setType(QualType t) {
     // In C++, the type of an expression is always adjusted so that it
-    // will not have reference type an expression will never have
-    // reference type (C++ [expr]p6). Use
+    // will not have reference type (C++ [expr]p6). Use
     // QualType::getNonReferenceType() to retrieve the non-reference
     // type. Additionally, inspect Expr::isLvalue to determine whether
     // an expression that is adjusted in this manner should be
@@ -1161,7 +1161,7 @@
   friend class ASTStmtWriter;
 };
 
-/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
+/// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
 class PredefinedExpr : public Expr {
 public:
   enum IdentType {
@@ -1171,7 +1171,7 @@
     FuncDName,
     FuncSig,
     PrettyFunction,
-    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
+    /// \brief The same as PrettyFunction, except that the
     /// 'virtual' keyword is omitted for virtual member functions.
     PrettyFunctionNoVirtual
   };
@@ -1179,24 +1179,27 @@
 private:
   SourceLocation Loc;
   IdentType Type;
+  Stmt *FnName;
+
 public:
-  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
-    : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
-           type->isDependentType(), type->isDependentType(),
-           type->isInstantiationDependentType(),
-           /*ContainsUnexpandedParameterPack=*/false),
-      Loc(l), Type(IT) {}
+  PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
+                 StringLiteral *SL);
 
   /// \brief Construct an empty predefined expression.
   explicit PredefinedExpr(EmptyShell Empty)
-    : Expr(PredefinedExprClass, Empty) { }
+      : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
 
   IdentType getIdentType() const { return Type; }
-  void setIdentType(IdentType IT) { Type = IT; }
 
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation L) { Loc = L; }
 
+  StringLiteral *getFunctionName();
+  const StringLiteral *getFunctionName() const {
+    return const_cast<PredefinedExpr *>(this)->getFunctionName();
+  }
+
+  static StringRef getIdentTypeName(IdentType IT);
   static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
 
   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
@@ -1207,7 +1210,9 @@
   }
 
   // Iterators
-  child_range children() { return child_range(); }
+  child_range children() { return child_range(&FnName, &FnName + 1); }
+
+  friend class ASTStmtReader;
 };
 
 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
@@ -2212,11 +2217,11 @@
   /// getArg - Return the specified argument.
   Expr *getArg(unsigned Arg) {
     assert(Arg < NumArgs && "Arg access out of range!");
-    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
+    return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
   }
   const Expr *getArg(unsigned Arg) const {
     assert(Arg < NumArgs && "Arg access out of range!");
-    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
+    return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
   }
 
   /// setArg - Set the specified argument.
@@ -2256,8 +2261,8 @@
   /// interface.  This provides efficient reverse iteration of the
   /// subexpressions.  This is currently used for CFG construction.
   ArrayRef<Stmt*> getRawSubExprs() {
-    return ArrayRef<Stmt*>(SubExprs,
-                           getNumPreArgs() + PREARGS_START + getNumArgs());
+    return llvm::makeArrayRef(SubExprs,
+                              getNumPreArgs() + PREARGS_START + getNumArgs());
   }
 
   /// getNumCommas - Return the number of commas that must have been present in
@@ -2653,9 +2658,6 @@
 /// representation in the source code (ExplicitCastExpr's derived
 /// classes).
 class CastExpr : public Expr {
-public:
-  typedef clang::CastKind CastKind;
-
 private:
   Stmt *Op;
 
@@ -2673,20 +2675,23 @@
   }
 
 protected:
-  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
-           const CastKind kind, Expr *op, unsigned BasePathSize) :
-    Expr(SC, ty, VK, OK_Ordinary,
-         // Cast expressions are type-dependent if the type is
-         // dependent (C++ [temp.dep.expr]p3).
-         ty->isDependentType(),
-         // Cast expressions are value-dependent if the type is
-         // dependent or if the subexpression is value-dependent.
-         ty->isDependentType() || (op && op->isValueDependent()),
-         (ty->isInstantiationDependentType() ||
-          (op && op->isInstantiationDependent())),
-         (ty->containsUnexpandedParameterPack() ||
-          (op && op->containsUnexpandedParameterPack()))),
-    Op(op) {
+  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
+           Expr *op, unsigned BasePathSize)
+      : Expr(SC, ty, VK, OK_Ordinary,
+             // Cast expressions are type-dependent if the type is
+             // dependent (C++ [temp.dep.expr]p3).
+             ty->isDependentType(),
+             // Cast expressions are value-dependent if the type is
+             // dependent or if the subexpression is value-dependent.
+             ty->isDependentType() || (op && op->isValueDependent()),
+             (ty->isInstantiationDependentType() ||
+              (op && op->isInstantiationDependent())),
+             // An implicit cast expression doesn't (lexically) contain an
+             // unexpanded pack, even if its target type does.
+             ((SC != ImplicitCastExprClass &&
+               ty->containsUnexpandedParameterPack()) ||
+              (op && op->containsUnexpandedParameterPack()))),
+        Op(op) {
     assert(kind != CK_Invalid && "creating cast with invalid cast kind");
     CastExprBits.Kind = kind;
     setBasePathSize(BasePathSize);
@@ -4841,6 +4846,24 @@
     return child_range(SubExprs, SubExprs+NumSubExprs);
   }
 };
+
+/// TypoExpr - Internal placeholder for expressions where typo correction
+/// still needs to be performed and/or an error diagnostic emitted.
+class TypoExpr : public Expr {
+public:
+  TypoExpr(QualType T)
+      : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
+             /*isTypeDependent*/ true,
+             /*isValueDependent*/ true,
+             /*isInstantiationDependent*/ true,
+             /*containsUnexpandedParameterPack*/ false) {
+    assert(T->isDependentType() && "TypoExpr given a non-dependent type");
+  }
+
+  child_range children() { return child_range(); }
+  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
+  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
+};
 }  // end namespace clang
 
 #endif
diff --git a/include/clang/AST/ExprCXX.h b/include/clang/AST/ExprCXX.h
index 3a43d6d..040fbe7 100644
--- a/include/clang/AST/ExprCXX.h
+++ b/include/clang/AST/ExprCXX.h
@@ -967,8 +967,14 @@
   const FieldDecl *getField() const { return Field; }
 
   /// \brief Get the initialization expression that will be used.
-  const Expr *getExpr() const { return Field->getInClassInitializer(); }
-  Expr *getExpr() { return Field->getInClassInitializer(); }
+  const Expr *getExpr() const {
+    assert(Field->getInClassInitializer() && "initializer hasn't been parsed");
+    return Field->getInClassInitializer();
+  }
+  Expr *getExpr() {
+    assert(Field->getInClassInitializer() && "initializer hasn't been parsed");
+    return Field->getInClassInitializer();
+  }
 
   SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
   SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
@@ -1165,6 +1171,13 @@
 
   typedef ExprIterator arg_iterator;
   typedef ConstExprIterator const_arg_iterator;
+  typedef llvm::iterator_range<arg_iterator> arg_range;
+  typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
+
+  arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
+  arg_const_range arguments() const {
+    return arg_const_range(arg_begin(), arg_end());
+  }
 
   arg_iterator arg_begin() { return Args; }
   arg_iterator arg_end() { return Args + NumArgs; }
@@ -1569,12 +1582,12 @@
 public:
   /// \brief Create an explicitly-written scalar-value initialization
   /// expression.
-  CXXScalarValueInitExpr(QualType Type,
-                         TypeSourceInfo *TypeInfo,
-                         SourceLocation rParenLoc ) :
-    Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary,
-         false, false, Type->isInstantiationDependentType(), false),
-    RParenLoc(rParenLoc), TypeInfo(TypeInfo) {}
+  CXXScalarValueInitExpr(QualType Type, TypeSourceInfo *TypeInfo,
+                         SourceLocation rParenLoc)
+      : Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary,
+             false, false, Type->isInstantiationDependentType(),
+             Type->containsUnexpandedParameterPack()),
+        RParenLoc(rParenLoc), TypeInfo(TypeInfo) {}
 
   explicit CXXScalarValueInitExpr(EmptyShell Shell)
     : Expr(CXXScalarValueInitExprClass, Shell) { }
@@ -2113,7 +2126,7 @@
   
   /// \brief Retrieve the argument types.
   ArrayRef<TypeSourceInfo *> getArgs() const { 
-    return ArrayRef<TypeSourceInfo *>(getTypeSourceInfos(), getNumArgs());
+    return llvm::makeArrayRef(getTypeSourceInfos(), getNumArgs());
   }
   
   typedef TypeSourceInfo **arg_iterator;
@@ -2767,7 +2780,7 @@
                                   ArrayRef<CleanupObject> objects);
 
   ArrayRef<CleanupObject> getObjects() const {
-    return ArrayRef<CleanupObject>(getObjectsBuffer(), getNumObjects());
+    return llvm::makeArrayRef(getObjectsBuffer(), getNumObjects());
   }
 
   unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
@@ -3811,6 +3824,69 @@
   }
 };
 
+/// \brief Represents a folding of a pack over an operator.
+///
+/// This expression is always dependent and represents a pack expansion of the
+/// forms:
+///
+///    ( expr op ... )
+///    ( ... op expr )
+///    ( expr op ... op expr )
+class CXXFoldExpr : public Expr {
+  SourceLocation LParenLoc;
+  SourceLocation EllipsisLoc;
+  SourceLocation RParenLoc;
+  Stmt *SubExprs[2];
+  BinaryOperatorKind Opcode;
+
+  friend class ASTStmtReader;
+  friend class ASTStmtWriter;
+public:
+  CXXFoldExpr(QualType T, SourceLocation LParenLoc, Expr *LHS,
+              BinaryOperatorKind Opcode, SourceLocation EllipsisLoc, Expr *RHS,
+              SourceLocation RParenLoc)
+      : Expr(CXXFoldExprClass, T, VK_RValue, OK_Ordinary,
+             /*Dependent*/ true, true, true,
+             /*ContainsUnexpandedParameterPack*/ false),
+        LParenLoc(LParenLoc), EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc),
+        Opcode(Opcode) {
+    SubExprs[0] = LHS;
+    SubExprs[1] = RHS;
+  }
+  CXXFoldExpr(EmptyShell Empty) : Expr(CXXFoldExprClass, Empty) {}
+
+  Expr *getLHS() const { return static_cast<Expr*>(SubExprs[0]); }
+  Expr *getRHS() const { return static_cast<Expr*>(SubExprs[1]); }
+
+  /// Does this produce a right-associated sequence of operators?
+  bool isRightFold() const {
+    return getLHS() && getLHS()->containsUnexpandedParameterPack();
+  }
+  /// Does this produce a left-associated sequence of operators?
+  bool isLeftFold() const { return !isRightFold(); }
+  /// Get the pattern, that is, the operand that contains an unexpanded pack.
+  Expr *getPattern() const { return isLeftFold() ? getRHS() : getLHS(); }
+  /// Get the operand that doesn't contain a pack, for a binary fold.
+  Expr *getInit() const { return isLeftFold() ? getLHS() : getRHS(); }
+
+  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
+  BinaryOperatorKind getOperator() const { return Opcode; }
+
+  SourceLocation getLocStart() const LLVM_READONLY {
+    return LParenLoc;
+  }
+  SourceLocation getLocEnd() const LLVM_READONLY {
+    return RParenLoc;
+  }
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == CXXFoldExprClass;
+  }
+
+  // Iterators
+  child_range children() { return child_range(SubExprs, SubExprs + 2); }
+};
+
 }  // end namespace clang
 
 #endif
diff --git a/include/clang/AST/ExternalASTSource.h b/include/clang/AST/ExternalASTSource.h
index 1e8eff3..ff1d180 100644
--- a/include/clang/AST/ExternalASTSource.h
+++ b/include/clang/AST/ExternalASTSource.h
@@ -11,8 +11,8 @@
 //  construction of AST nodes from some external source.
 //
 //===----------------------------------------------------------------------===//
-#ifndef LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H
-#define LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H
+#ifndef LLVM_CLANG_AST_EXTERNALASTSOURCE_H
+#define LLVM_CLANG_AST_EXTERNALASTSOURCE_H
 
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/DeclBase.h"
@@ -650,4 +650,4 @@
 
 } // end namespace clang
 
-#endif // LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H
+#endif
diff --git a/include/clang/AST/LambdaCapture.h b/include/clang/AST/LambdaCapture.h
index 8633c97..a7468a0 100644
--- a/include/clang/AST/LambdaCapture.h
+++ b/include/clang/AST/LambdaCapture.h
@@ -68,13 +68,23 @@
 
   /// \brief Determine whether this capture handles the C++ \c this
   /// pointer.
-  bool capturesThis() const { return DeclAndBits.getPointer() == nullptr; }
+  bool capturesThis() const {
+    return (DeclAndBits.getPointer() == nullptr) &&
+           !(DeclAndBits.getInt() & Capture_ByCopy);
+  }
 
   /// \brief Determine whether this capture handles a variable.
   bool capturesVariable() const {
     return dyn_cast_or_null<VarDecl>(DeclAndBits.getPointer());
   }
 
+  /// \brief Determine whether this captures a variable length array bound
+  /// expression.
+  bool capturesVLAType() const {
+    return (DeclAndBits.getPointer() == nullptr) &&
+           (DeclAndBits.getInt() & Capture_ByCopy);
+  }
+
   /// \brief Determine whether this is an init-capture.
   bool isInitCapture() const {
     return capturesVariable() && getCapturedVar()->isInitCapture();
diff --git a/include/clang/AST/Mangle.h b/include/clang/AST/Mangle.h
index a8d1199..cbe08a1 100644
--- a/include/clang/AST/Mangle.h
+++ b/include/clang/AST/Mangle.h
@@ -156,6 +156,11 @@
   virtual void mangleItaniumThreadLocalWrapper(const VarDecl *D,
                                                raw_ostream &) = 0;
 
+  virtual void mangleCXXCtorComdat(const CXXConstructorDecl *D,
+                                   raw_ostream &) = 0;
+  virtual void mangleCXXDtorComdat(const CXXDestructorDecl *D,
+                                   raw_ostream &) = 0;
+
   static bool classof(const MangleContext *C) {
     return C->getKind() == MK_Itanium;
   }
diff --git a/include/clang/AST/MangleNumberingContext.h b/include/clang/AST/MangleNumberingContext.h
index 56c9952..7a81855 100644
--- a/include/clang/AST/MangleNumberingContext.h
+++ b/include/clang/AST/MangleNumberingContext.h
@@ -12,8 +12,8 @@
 //  literals.
 //
 //===----------------------------------------------------------------------===//
-#ifndef LLVM_CLANG_MANGLENUMBERINGCONTEXT_H
-#define LLVM_CLANG_MANGLENUMBERINGCONTEXT_H
+#ifndef LLVM_CLANG_AST_MANGLENUMBERINGCONTEXT_H
+#define LLVM_CLANG_AST_MANGLENUMBERINGCONTEXT_H
 
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/DenseMap.h"
@@ -30,23 +30,20 @@
 
 /// \brief Keeps track of the mangled names of lambda expressions and block
 /// literals within a particular context.
-class MangleNumberingContext 
-    : public RefCountedBase<MangleNumberingContext> {
-  llvm::DenseMap<const Type *, unsigned> ManglingNumbers;
-
+class MangleNumberingContext : public RefCountedBase<MangleNumberingContext> {
 public:
   virtual ~MangleNumberingContext() {}
 
   /// \brief Retrieve the mangling number of a new lambda expression with the
   /// given call operator within this context.
-  unsigned getManglingNumber(const CXXMethodDecl *CallOperator);
+  virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator) = 0;
 
   /// \brief Retrieve the mangling number of a new block literal within this
   /// context.
-  unsigned getManglingNumber(const BlockDecl *BD);
+  virtual unsigned getManglingNumber(const BlockDecl *BD) = 0;
 
   /// Static locals are numbered by source order.
-  unsigned getStaticLocalNumber(const VarDecl *VD);
+  virtual unsigned getStaticLocalNumber(const VarDecl *VD) = 0;
 
   /// \brief Retrieve the mangling number of a static local variable within
   /// this context.
@@ -58,6 +55,6 @@
   virtual unsigned getManglingNumber(const TagDecl *TD,
                                      unsigned MSLocalManglingNumber) = 0;
 };
-  
+
 } // end namespace clang
 #endif
diff --git a/include/clang/AST/NSAPI.h b/include/clang/AST/NSAPI.h
index 0b21b03..33fcce2 100644
--- a/include/clang/AST/NSAPI.h
+++ b/include/clang/AST/NSAPI.h
@@ -42,7 +42,8 @@
     NSStr_stringWithUTF8String,
     NSStr_stringWithCStringEncoding,
     NSStr_stringWithCString,
-    NSStr_initWithString
+    NSStr_initWithString,
+    NSStr_initWithUTF8String
   };
   static const unsigned NumNSStringMethods = 5;
 
@@ -100,8 +101,8 @@
     NSDict_objectForKey,
     NSMutableDict_setObjectForKey
   };
-  static const unsigned NumNSDictionaryMethods = 11;
-
+  static const unsigned NumNSDictionaryMethods = 12;
+  
   /// \brief The Objective-C NSDictionary selectors.
   Selector getNSDictionarySelector(NSDictionaryMethodKind MK) const;
 
@@ -184,6 +185,9 @@
   bool isObjCNSIntegerType(QualType T) const;
   /// \brief Returns true if \param T is a typedef of "NSUInteger" in objective-c.
   bool isObjCNSUIntegerType(QualType T) const;
+  /// \brief Returns one of NSIntegral typedef names if \param T is a typedef
+  /// of that name in objective-c.
+  StringRef GetNSIntegralKind(QualType T) const;
 
 private:
   bool isObjCTypedef(QualType T, StringRef name, IdentifierInfo *&II) const;
diff --git a/include/clang/AST/NestedNameSpecifier.h b/include/clang/AST/NestedNameSpecifier.h
index fc719bd..518f123 100644
--- a/include/clang/AST/NestedNameSpecifier.h
+++ b/include/clang/AST/NestedNameSpecifier.h
@@ -22,6 +22,7 @@
 namespace clang {
 
 class ASTContext;
+class CXXRecordDecl;
 class NamespaceAliasDecl;
 class NamespaceDecl;
 class IdentifierInfo;
@@ -45,7 +46,7 @@
   /// \brief Enumeration describing
   enum StoredSpecifierKind {
     StoredIdentifier = 0,
-    StoredNamespaceOrAlias = 1,
+    StoredDecl = 1,
     StoredTypeSpec = 2,
     StoredTypeSpecWithTemplate = 3
   };
@@ -83,7 +84,10 @@
     /// stored as a Type*.
     TypeSpecWithTemplate,
     /// \brief The global specifier '::'. There is no stored value.
-    Global
+    Global,
+    /// \brief Microsoft's '__super' specifier, stored as a CXXRecordDecl* of
+    /// the class it appeared in.
+    Super
   };
 
 private:
@@ -143,6 +147,11 @@
   /// scope.
   static NestedNameSpecifier *GlobalSpecifier(const ASTContext &Context);
 
+  /// \brief Returns the nested name specifier representing the __super scope
+  /// for the given CXXRecordDecl.
+  static NestedNameSpecifier *SuperSpecifier(const ASTContext &Context,
+                                             CXXRecordDecl *RD);
+
   /// \brief Return the prefix of this nested name specifier.
   ///
   /// The prefix contains all of the parts of the nested name
@@ -172,6 +181,10 @@
   /// specifier.
   NamespaceAliasDecl *getAsNamespaceAlias() const;
 
+  /// \brief Retrieve the record declaration stored in this nested name
+  /// specifier.
+  CXXRecordDecl *getAsRecordDecl() const;
+
   /// \brief Retrieve the type stored in this nested name specifier.
   const Type *getAsType() const {
     if (Prefix.getInt() == StoredTypeSpec ||
@@ -421,7 +434,22 @@
   /// \brief Turn this (empty) nested-name-specifier into the global
   /// nested-name-specifier '::'.
   void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
-
+  
+  /// \brief Turns this (empty) nested-name-specifier into '__super'
+  /// nested-name-specifier.
+  ///
+  /// \param Context The AST context in which this nested-name-specifier
+  /// resides.
+  ///
+  /// \param RD The declaration of the class in which nested-name-specifier
+  /// appeared.
+  ///
+  /// \param SuperLoc The location of the '__super' keyword.
+  /// name.
+  ///
+  /// \param ColonColonLoc The location of the trailing '::'.
+  void MakeSuper(ASTContext &Context, CXXRecordDecl *RD, 
+                 SourceLocation SuperLoc, SourceLocation ColonColonLoc);
   /// \brief Make a new nested-name-specifier from incomplete source-location
   /// information.
   ///
diff --git a/include/clang/AST/OpenMPClause.h b/include/clang/AST/OpenMPClause.h
index 3345959..0c3002c 100644
--- a/include/clang/AST/OpenMPClause.h
+++ b/include/clang/AST/OpenMPClause.h
@@ -61,7 +61,7 @@
   ConstStmtRange children() const {
     return const_cast<OMPClause *>(this)->children();
   }
-  static bool classof(const OMPClause *T) { return true; }
+  static bool classof(const OMPClause *) { return true; }
 };
 
 /// \brief This represents clauses with the list of variables like 'private',
@@ -135,10 +135,10 @@
 
   /// \brief Fetches list of all variables in the clause.
   ArrayRef<const Expr *> getVarRefs() const {
-    return ArrayRef<const Expr *>(
+    return llvm::makeArrayRef(
         reinterpret_cast<const Expr *const *>(
             reinterpret_cast<const char *>(this) +
-            llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>())),
+            llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<const Expr *>())),
         NumVars);
   }
 };
@@ -770,6 +770,153 @@
   StmtRange children() { return StmtRange(); }
 };
 
+/// \brief This represents 'read' clause in the '#pragma omp atomic' directive.
+///
+/// \code
+/// #pragma omp atomic read
+/// \endcode
+/// In this example directive '#pragma omp atomic' has 'read' clause.
+///
+class OMPReadClause : public OMPClause {
+public:
+  /// \brief Build 'read' clause.
+  ///
+  /// \param StartLoc Starting location of the clause.
+  /// \param EndLoc Ending location of the clause.
+  ///
+  OMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc)
+      : OMPClause(OMPC_read, StartLoc, EndLoc) {}
+
+  /// \brief Build an empty clause.
+  ///
+  OMPReadClause() : OMPClause(OMPC_read, SourceLocation(), SourceLocation()) {}
+
+  static bool classof(const OMPClause *T) {
+    return T->getClauseKind() == OMPC_read;
+  }
+
+  StmtRange children() { return StmtRange(); }
+};
+
+/// \brief This represents 'write' clause in the '#pragma omp atomic' directive.
+///
+/// \code
+/// #pragma omp atomic write
+/// \endcode
+/// In this example directive '#pragma omp atomic' has 'write' clause.
+///
+class OMPWriteClause : public OMPClause {
+public:
+  /// \brief Build 'write' clause.
+  ///
+  /// \param StartLoc Starting location of the clause.
+  /// \param EndLoc Ending location of the clause.
+  ///
+  OMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc)
+      : OMPClause(OMPC_write, StartLoc, EndLoc) {}
+
+  /// \brief Build an empty clause.
+  ///
+  OMPWriteClause()
+      : OMPClause(OMPC_write, SourceLocation(), SourceLocation()) {}
+
+  static bool classof(const OMPClause *T) {
+    return T->getClauseKind() == OMPC_write;
+  }
+
+  StmtRange children() { return StmtRange(); }
+};
+
+/// \brief This represents 'update' clause in the '#pragma omp atomic'
+/// directive.
+///
+/// \code
+/// #pragma omp atomic update
+/// \endcode
+/// In this example directive '#pragma omp atomic' has 'update' clause.
+///
+class OMPUpdateClause : public OMPClause {
+public:
+  /// \brief Build 'update' clause.
+  ///
+  /// \param StartLoc Starting location of the clause.
+  /// \param EndLoc Ending location of the clause.
+  ///
+  OMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc)
+      : OMPClause(OMPC_update, StartLoc, EndLoc) {}
+
+  /// \brief Build an empty clause.
+  ///
+  OMPUpdateClause()
+      : OMPClause(OMPC_update, SourceLocation(), SourceLocation()) {}
+
+  static bool classof(const OMPClause *T) {
+    return T->getClauseKind() == OMPC_update;
+  }
+
+  StmtRange children() { return StmtRange(); }
+};
+
+/// \brief This represents 'capture' clause in the '#pragma omp atomic'
+/// directive.
+///
+/// \code
+/// #pragma omp atomic capture
+/// \endcode
+/// In this example directive '#pragma omp atomic' has 'capture' clause.
+///
+class OMPCaptureClause : public OMPClause {
+public:
+  /// \brief Build 'capture' clause.
+  ///
+  /// \param StartLoc Starting location of the clause.
+  /// \param EndLoc Ending location of the clause.
+  ///
+  OMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc)
+      : OMPClause(OMPC_capture, StartLoc, EndLoc) {}
+
+  /// \brief Build an empty clause.
+  ///
+  OMPCaptureClause()
+      : OMPClause(OMPC_capture, SourceLocation(), SourceLocation()) {}
+
+  static bool classof(const OMPClause *T) {
+    return T->getClauseKind() == OMPC_capture;
+  }
+
+  StmtRange children() { return StmtRange(); }
+};
+
+/// \brief This represents 'seq_cst' clause in the '#pragma omp atomic'
+/// directive.
+///
+/// \code
+/// #pragma omp atomic seq_cst
+/// \endcode
+/// In this example directive '#pragma omp atomic' has 'seq_cst' clause.
+///
+class OMPSeqCstClause : public OMPClause {
+public:
+  /// \brief Build 'seq_cst' clause.
+  ///
+  /// \param StartLoc Starting location of the clause.
+  /// \param EndLoc Ending location of the clause.
+  ///
+  OMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc)
+      : OMPClause(OMPC_seq_cst, StartLoc, EndLoc) {}
+
+  /// \brief Build an empty clause.
+  ///
+  OMPSeqCstClause()
+      : OMPClause(OMPC_seq_cst, SourceLocation(), SourceLocation()) {}
+
+  static bool classof(const OMPClause *T) {
+    return T->getClauseKind() == OMPC_seq_cst;
+  }
+
+  StmtRange children() { return StmtRange(); }
+};
+
 /// \brief This represents clause 'private' in the '#pragma omp ...' directives.
 ///
 /// \code
@@ -779,6 +926,7 @@
 /// with the variables 'a' and 'b'.
 ///
 class OMPPrivateClause : public OMPVarListClause<OMPPrivateClause> {
+  friend class OMPClauseReader;
   /// \brief Build clause with number of variables \a N.
   ///
   /// \param StartLoc Starting location of the clause.
@@ -800,6 +948,20 @@
                                            SourceLocation(), SourceLocation(),
                                            N) {}
 
+  /// \brief Sets the list of references to private copies with initializers for
+  /// new private variables.
+  /// \param VL List of references.
+  void setPrivateCopies(ArrayRef<Expr *> VL);
+
+  /// \brief Gets the list of references to private copies with initializers for
+  /// new private variables.
+  MutableArrayRef<Expr *> getPrivateCopies() {
+    return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
+  }
+  ArrayRef<const Expr *> getPrivateCopies() const {
+    return llvm::makeArrayRef(varlist_end(), varlist_size());
+  }
+
 public:
   /// \brief Creates clause with a list of variables \a VL.
   ///
@@ -808,10 +970,12 @@
   /// \param LParenLoc Location of '('.
   /// \param EndLoc Ending location of the clause.
   /// \param VL List of references to the variables.
+  /// \param PrivateVL List of references to private copies with initializers.
   ///
   static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc,
                                   SourceLocation LParenLoc,
-                                  SourceLocation EndLoc, ArrayRef<Expr *> VL);
+                                  SourceLocation EndLoc, ArrayRef<Expr *> VL,
+                                  ArrayRef<Expr *> PrivateVL);
   /// \brief Creates an empty clause with the place for \a N variables.
   ///
   /// \param C AST context.
@@ -819,6 +983,21 @@
   ///
   static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N);
 
+  typedef MutableArrayRef<Expr *>::iterator private_copies_iterator;
+  typedef ArrayRef<const Expr *>::iterator private_copies_const_iterator;
+  typedef llvm::iterator_range<private_copies_iterator> private_copies_range;
+  typedef llvm::iterator_range<private_copies_const_iterator>
+      private_copies_const_range;
+
+  private_copies_range private_copies() {
+    return private_copies_range(getPrivateCopies().begin(),
+                                getPrivateCopies().end());
+  }
+  private_copies_const_range private_copies() const {
+    return private_copies_const_range(getPrivateCopies().begin(),
+                                      getPrivateCopies().end());
+  }
+
   StmtRange children() {
     return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
                      reinterpret_cast<Stmt **>(varlist_end()));
@@ -839,6 +1018,8 @@
 /// with the variables 'a' and 'b'.
 ///
 class OMPFirstprivateClause : public OMPVarListClause<OMPFirstprivateClause> {
+  friend class OMPClauseReader;
+
   /// \brief Build clause with number of variables \a N.
   ///
   /// \param StartLoc Starting location of the clause.
@@ -859,6 +1040,33 @@
       : OMPVarListClause<OMPFirstprivateClause>(
             OMPC_firstprivate, SourceLocation(), SourceLocation(),
             SourceLocation(), N) {}
+  /// \brief Sets the list of references to private copies with initializers for
+  /// new private variables.
+  /// \param VL List of references.
+  void setPrivateCopies(ArrayRef<Expr *> VL);
+
+  /// \brief Gets the list of references to private copies with initializers for
+  /// new private variables.
+  MutableArrayRef<Expr *> getPrivateCopies() {
+    return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
+  }
+  ArrayRef<const Expr *> getPrivateCopies() const {
+    return llvm::makeArrayRef(varlist_end(), varlist_size());
+  }
+
+  /// \brief Sets the list of references to initializer variables for new
+  /// private variables.
+  /// \param VL List of references.
+  void setInits(ArrayRef<Expr *> VL);
+
+  /// \brief Gets the list of references to initializer variables for new
+  /// private variables.
+  MutableArrayRef<Expr *> getInits() {
+    return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size());
+  }
+  ArrayRef<const Expr *> getInits() const {
+    return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size());
+  }
 
 public:
   /// \brief Creates clause with a list of variables \a VL.
@@ -867,11 +1075,16 @@
   /// \param StartLoc Starting location of the clause.
   /// \param LParenLoc Location of '('.
   /// \param EndLoc Ending location of the clause.
-  /// \param VL List of references to the variables.
+  /// \param VL List of references to the original variables.
+  /// \param PrivateVL List of references to private copies with initializers.
+  /// \param InitVL List of references to auto generated variables used for
+  /// initialization of a single array element. Used if firstprivate variable is
+  /// of array type.
   ///
   static OMPFirstprivateClause *
   Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
-         SourceLocation EndLoc, ArrayRef<Expr *> VL);
+         SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL,
+         ArrayRef<Expr *> InitVL);
   /// \brief Creates an empty clause with the place for \a N variables.
   ///
   /// \param C AST context.
@@ -879,6 +1092,33 @@
   ///
   static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
 
+  typedef MutableArrayRef<Expr *>::iterator private_copies_iterator;
+  typedef ArrayRef<const Expr *>::iterator private_copies_const_iterator;
+  typedef llvm::iterator_range<private_copies_iterator> private_copies_range;
+  typedef llvm::iterator_range<private_copies_const_iterator>
+      private_copies_const_range;
+
+  private_copies_range private_copies() {
+    return private_copies_range(getPrivateCopies().begin(),
+                                getPrivateCopies().end());
+  }
+  private_copies_const_range private_copies() const {
+    return private_copies_const_range(getPrivateCopies().begin(),
+                                      getPrivateCopies().end());
+  }
+
+  typedef MutableArrayRef<Expr *>::iterator inits_iterator;
+  typedef ArrayRef<const Expr *>::iterator inits_const_iterator;
+  typedef llvm::iterator_range<inits_iterator> inits_range;
+  typedef llvm::iterator_range<inits_const_iterator> inits_const_range;
+
+  inits_range inits() {
+    return inits_range(getInits().begin(), getInits().end());
+  }
+  inits_const_range inits() const {
+    return inits_const_range(getInits().begin(), getInits().end());
+  }
+
   StmtRange children() {
     return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
                      reinterpret_cast<Stmt **>(varlist_end()));
@@ -1390,13 +1630,17 @@
   }
 };
 
-/// \brief This represents pseudo clause 'flush' for the '#pragma omp flush'
+/// \brief This represents implicit clause 'flush' for the '#pragma omp flush'
 /// directive.
+/// This clause does not exist by itself, it can be only as a part of 'omp
+/// flush' directive. This clause is introduced to keep the original structure
+/// of \a OMPExecutableDirective class and its derivatives and to use the
+/// existing infrastructure of clauses with the list of variables.
 ///
 /// \code
 /// #pragma omp flush(a,b)
 /// \endcode
-/// In this example directive '#pragma omp flush' has pseudo clause 'flush'
+/// In this example directive '#pragma omp flush' has implicit clause 'flush'
 /// with the variables 'a' and 'b'.
 ///
 class OMPFlushClause : public OMPVarListClause<OMPFlushClause> {
@@ -1453,3 +1697,4 @@
 } // end namespace clang
 
 #endif
+
diff --git a/include/clang/AST/OperationKinds.h b/include/clang/AST/OperationKinds.h
index aba88d6..e3f0126 100644
--- a/include/clang/AST/OperationKinds.h
+++ b/include/clang/AST/OperationKinds.h
@@ -12,8 +12,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_OPERATION_KINDS_H
-#define LLVM_CLANG_AST_OPERATION_KINDS_H
+#ifndef LLVM_CLANG_AST_OPERATIONKINDS_H
+#define LLVM_CLANG_AST_OPERATIONKINDS_H
 
 namespace clang {
   
diff --git a/include/clang/AST/ParentMap.h b/include/clang/AST/ParentMap.h
index eece851..8945c41 100644
--- a/include/clang/AST/ParentMap.h
+++ b/include/clang/AST/ParentMap.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_PARENTMAP_H
-#define LLVM_CLANG_PARENTMAP_H
+#ifndef LLVM_CLANG_AST_PARENTMAP_H
+#define LLVM_CLANG_AST_PARENTMAP_H
 
 namespace clang {
 class Stmt;
diff --git a/include/clang/AST/PrettyPrinter.h b/include/clang/AST/PrettyPrinter.h
index 349f4c4..35ceabb 100644
--- a/include/clang/AST/PrettyPrinter.h
+++ b/include/clang/AST/PrettyPrinter.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_PRETTY_PRINTER_H
-#define LLVM_CLANG_AST_PRETTY_PRINTER_H
+#ifndef LLVM_CLANG_AST_PRETTYPRINTER_H
+#define LLVM_CLANG_AST_PRETTYPRINTER_H
 
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/LangOptions.h"
diff --git a/include/clang/AST/RawCommentList.h b/include/clang/AST/RawCommentList.h
index 8ba85c4..2e005dd 100644
--- a/include/clang/AST/RawCommentList.h
+++ b/include/clang/AST/RawCommentList.h
@@ -7,8 +7,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_RAW_COMMENT_LIST_H
-#define LLVM_CLANG_AST_RAW_COMMENT_LIST_H
+#ifndef LLVM_CLANG_AST_RAWCOMMENTLIST_H
+#define LLVM_CLANG_AST_RAWCOMMENTLIST_H
 
 #include "clang/Basic/CommentOptions.h"
 #include "clang/Basic/SourceManager.h"
diff --git a/include/clang/AST/RecordLayout.h b/include/clang/AST/RecordLayout.h
index 4befb45..7b77998 100644
--- a/include/clang/AST/RecordLayout.h
+++ b/include/clang/AST/RecordLayout.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_LAYOUTINFO_H
-#define LLVM_CLANG_AST_LAYOUTINFO_H
+#ifndef LLVM_CLANG_AST_RECORDLAYOUT_H
+#define LLVM_CLANG_AST_RECORDLAYOUT_H
 
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/DeclCXX.h"
diff --git a/include/clang/AST/RecursiveASTVisitor.h b/include/clang/AST/RecursiveASTVisitor.h
index ff46ffb..a1d3618 100644
--- a/include/clang/AST/RecursiveASTVisitor.h
+++ b/include/clang/AST/RecursiveASTVisitor.h
@@ -429,6 +429,7 @@
   bool TraverseFunctionHelper(FunctionDecl *D);
   bool TraverseVarHelper(VarDecl *D);
   bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
+  bool TraverseOMPLoopDirective(OMPLoopDirective *S);
   bool TraverseOMPClause(OMPClause *C);
 #define OPENMP_CLAUSE(Name, Class) bool Visit##Class(Class *C);
 #include "clang/Basic/OpenMPKinds.def"
@@ -689,6 +690,7 @@
   case NestedNameSpecifier::Namespace:
   case NestedNameSpecifier::NamespaceAlias:
   case NestedNameSpecifier::Global:
+  case NestedNameSpecifier::Super:
     return true;
 
   case NestedNameSpecifier::TypeSpec:
@@ -713,6 +715,7 @@
   case NestedNameSpecifier::Namespace:
   case NestedNameSpecifier::NamespaceAlias:
   case NestedNameSpecifier::Global:
+  case NestedNameSpecifier::Super:
     return true;
 
   case NestedNameSpecifier::TypeSpec:
@@ -940,6 +943,9 @@
   for (const auto &E : T->exceptions()) {
     TRY_TO(TraverseType(E));
   }
+
+  if (Expr *NE = T->getNoexceptExpr())
+    TRY_TO(TraverseStmt(NE));
 })
 
 DEF_TRAVERSE_TYPE(UnresolvedUsingType, {})
@@ -1148,6 +1154,9 @@
   for (const auto &E : T->exceptions()) {
     TRY_TO(TraverseType(E));
   }
+
+  if (Expr *NE = T->getNoexceptExpr())
+    TRY_TO(TraverseStmt(NE));
 })
 
 DEF_TRAVERSE_TYPELOC(UnresolvedUsingType, {})
@@ -2144,21 +2153,29 @@
     TRY_TO(TraverseLambdaCapture(S, C));
   }
 
-  if (S->hasExplicitParameters() || S->hasExplicitResultType()) {
-    TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
-    if (S->hasExplicitParameters() && S->hasExplicitResultType()) {
-      // Visit the whole type.
-      TRY_TO(TraverseTypeLoc(TL));
-    } else if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
-      if (S->hasExplicitParameters()) {
-        // Visit parameters.
-        for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) {
-          TRY_TO(TraverseDecl(Proto.getParam(I)));
-        }
-      } else {
-        TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
+  TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
+  FunctionProtoTypeLoc Proto = TL.castAs<FunctionProtoTypeLoc>();
+
+  if (S->hasExplicitParameters() && S->hasExplicitResultType()) {
+    // Visit the whole type.
+    TRY_TO(TraverseTypeLoc(TL));
+  } else {
+    if (S->hasExplicitParameters()) {
+      // Visit parameters.
+      for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) {
+        TRY_TO(TraverseDecl(Proto.getParam(I)));
       }
+    } else if (S->hasExplicitResultType()) {
+      TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
     }
+
+    auto *T = Proto.getTypePtr();
+    for (const auto &E : T->exceptions()) {
+      TRY_TO(TraverseType(E));
+    }
+
+    if (Expr *NE = T->getNoexceptExpr())
+      TRY_TO(TraverseStmt(NE));
   }
 
   TRY_TO(TraverseLambdaBody(S));
@@ -2259,6 +2276,7 @@
 
 DEF_TRAVERSE_STMT(CXXOperatorCallExpr, {})
 DEF_TRAVERSE_STMT(OpaqueValueExpr, {})
+DEF_TRAVERSE_STMT(TypoExpr, {})
 DEF_TRAVERSE_STMT(CUDAKernelCallExpr, {})
 
 // These operators (all of them) do not need any action except
@@ -2275,6 +2293,7 @@
 DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmExpr, {})
 DEF_TRAVERSE_STMT(FunctionParmPackExpr, {})
 DEF_TRAVERSE_STMT(MaterializeTemporaryExpr, {})
+DEF_TRAVERSE_STMT(CXXFoldExpr, {})
 DEF_TRAVERSE_STMT(AtomicExpr, {})
 
 // These literals (all of them) do not need any action.
@@ -2301,6 +2320,12 @@
   return true;
 }
 
+template <typename Derived>
+bool
+RecursiveASTVisitor<Derived>::TraverseOMPLoopDirective(OMPLoopDirective *S) {
+  return TraverseOMPExecutableDirective(S);
+}
+
 DEF_TRAVERSE_STMT(OMPParallelDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
@@ -2310,6 +2335,9 @@
 DEF_TRAVERSE_STMT(OMPForDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
+DEF_TRAVERSE_STMT(OMPForSimdDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
 DEF_TRAVERSE_STMT(OMPSectionsDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
@@ -2330,6 +2358,9 @@
 DEF_TRAVERSE_STMT(OMPParallelForDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
+DEF_TRAVERSE_STMT(OMPParallelForSimdDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
 DEF_TRAVERSE_STMT(OMPParallelSectionsDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
@@ -2348,6 +2379,18 @@
 DEF_TRAVERSE_STMT(OMPFlushDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
+DEF_TRAVERSE_STMT(OMPOrderedDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
+DEF_TRAVERSE_STMT(OMPAtomicDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
+DEF_TRAVERSE_STMT(OMPTargetDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
+DEF_TRAVERSE_STMT(OMPTeamsDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
 // OpenMP clauses.
 template <typename Derived>
 bool RecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
@@ -2437,6 +2480,31 @@
 }
 
 template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPReadClause(OMPReadClause *) {
+  return true;
+}
+
+template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPWriteClause(OMPWriteClause *) {
+  return true;
+}
+
+template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPUpdateClause(OMPUpdateClause *) {
+  return true;
+}
+
+template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPCaptureClause(OMPCaptureClause *) {
+  return true;
+}
+
+template <typename Derived>
+bool RecursiveASTVisitor<Derived>::VisitOMPSeqCstClause(OMPSeqCstClause *) {
+  return true;
+}
+
+template <typename Derived>
 template <typename T>
 bool RecursiveASTVisitor<Derived>::VisitOMPClauseList(T *Node) {
   for (auto *E : Node->varlists()) {
@@ -2448,6 +2516,9 @@
 template <typename Derived>
 bool RecursiveASTVisitor<Derived>::VisitOMPPrivateClause(OMPPrivateClause *C) {
   TRY_TO(VisitOMPClauseList(C));
+  for (auto *E : C->private_copies()) {
+    TRY_TO(TraverseStmt(E));
+  }
   return true;
 }
 
@@ -2455,6 +2526,12 @@
 bool RecursiveASTVisitor<Derived>::VisitOMPFirstprivateClause(
     OMPFirstprivateClause *C) {
   TRY_TO(VisitOMPClauseList(C));
+  for (auto *E : C->private_copies()) {
+    TRY_TO(TraverseStmt(E));
+  }
+  for (auto *E : C->inits()) {
+    TRY_TO(TraverseStmt(E));
+  }
   return true;
 }
 
diff --git a/include/clang/AST/Stmt.h b/include/clang/AST/Stmt.h
index fb94097..380c3b9 100644
--- a/include/clang/AST/Stmt.h
+++ b/include/clang/AST/Stmt.h
@@ -393,6 +393,10 @@
   /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes.
   Stmt *IgnoreImplicit();
 
+  /// \brief Skip no-op (attributed, compound) container stmts and skip captured
+  /// stmt at the top, if \a IgnoreCaptured is true.
+  Stmt *IgnoreContainers(bool IgnoreCaptured = false);
+
   const Stmt *stripLabelLikeStatements() const;
   Stmt *stripLabelLikeStatements() {
     return const_cast<Stmt*>(
@@ -548,14 +552,17 @@
 ///
 class CompoundStmt : public Stmt {
   Stmt** Body;
-  SourceLocation LBracLoc, RBracLoc;
+  SourceLocation LBraceLoc, RBraceLoc;
+
+  friend class ASTStmtReader;
+
 public:
   CompoundStmt(const ASTContext &C, ArrayRef<Stmt*> Stmts,
                SourceLocation LB, SourceLocation RB);
 
   // \brief Build an empty compound statement with a location.
   explicit CompoundStmt(SourceLocation Loc)
-    : Stmt(CompoundStmtClass), Body(nullptr), LBracLoc(Loc), RBracLoc(Loc) {
+    : Stmt(CompoundStmtClass), Body(nullptr), LBraceLoc(Loc), RBraceLoc(Loc) {
     CompoundStmtBits.NumStmts = 0;
   }
 
@@ -614,13 +621,11 @@
     return const_reverse_body_iterator(body_begin());
   }
 
-  SourceLocation getLocStart() const LLVM_READONLY { return LBracLoc; }
-  SourceLocation getLocEnd() const LLVM_READONLY { return RBracLoc; }
+  SourceLocation getLocStart() const LLVM_READONLY { return LBraceLoc; }
+  SourceLocation getLocEnd() const LLVM_READONLY { return RBraceLoc; }
 
-  SourceLocation getLBracLoc() const { return LBracLoc; }
-  void setLBracLoc(SourceLocation L) { LBracLoc = L; }
-  SourceLocation getRBracLoc() const { return RBracLoc; }
-  void setRBracLoc(SourceLocation L) { RBracLoc = L; }
+  SourceLocation getLBracLoc() const { return LBraceLoc; }
+  SourceLocation getRBracLoc() const { return RBraceLoc; }
 
   static bool classof(const Stmt *T) {
     return T->getStmtClass() == CompoundStmtClass;
@@ -846,7 +851,7 @@
 
   SourceLocation getAttrLoc() const { return AttrLoc; }
   ArrayRef<const Attr*> getAttrs() const {
-    return ArrayRef<const Attr*>(getAttrArrayPtr(), NumAttrs);
+    return llvm::makeArrayRef(getAttrArrayPtr(), NumAttrs);
   }
   Stmt *getSubStmt() { return SubStmt; }
   const Stmt *getSubStmt() const { return SubStmt; }
@@ -1580,18 +1585,21 @@
     Kind MyKind;
     std::string Str;
     unsigned OperandNo;
+
+    // Source range for operand references.
+    CharSourceRange Range;
   public:
     AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {}
-    AsmStringPiece(unsigned OpNo, char Modifier)
-      : MyKind(Operand), Str(), OperandNo(OpNo) {
-      Str += Modifier;
+    AsmStringPiece(unsigned OpNo, const std::string &S, SourceLocation Begin,
+                   SourceLocation End)
+      : MyKind(Operand), Str(S), OperandNo(OpNo),
+        Range(CharSourceRange::getCharRange(Begin, End)) {
     }
 
     bool isString() const { return MyKind == String; }
     bool isOperand() const { return MyKind == Operand; }
 
     const std::string &getString() const {
-      assert(isString());
       return Str;
     }
 
@@ -1600,12 +1608,14 @@
       return OperandNo;
     }
 
+    CharSourceRange getRange() const {
+      assert(isOperand() && "Range is currently used only for Operands.");
+      return Range;
+    }
+
     /// getModifier - Get the modifier for this operand, if present.  This
     /// returns '\0' if there was no modifier.
-    char getModifier() const {
-      assert(isOperand());
-      return Str[0];
-    }
+    char getModifier() const;
   };
 
   /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
@@ -1780,14 +1790,14 @@
   //===--- Other ---===//
 
   ArrayRef<StringRef> getAllConstraints() const {
-    return ArrayRef<StringRef>(Constraints, NumInputs + NumOutputs);
+    return llvm::makeArrayRef(Constraints, NumInputs + NumOutputs);
   }
   ArrayRef<StringRef> getClobbers() const {
-    return ArrayRef<StringRef>(Clobbers, NumClobbers);
+    return llvm::makeArrayRef(Clobbers, NumClobbers);
   }
   ArrayRef<Expr*> getAllExprs() const {
-    return ArrayRef<Expr*>(reinterpret_cast<Expr**>(Exprs),
-                           NumInputs + NumOutputs);
+    return llvm::makeArrayRef(reinterpret_cast<Expr**>(Exprs),
+                              NumInputs + NumOutputs);
   }
 
   StringRef getClobber(unsigned i) const { return getClobbers()[i]; }
@@ -1892,24 +1902,22 @@
   bool            IsCXXTry;
   SourceLocation  TryLoc;
   Stmt           *Children[2];
-  int             HandlerIndex;
-  int             HandlerParentIndex;
 
   enum { TRY = 0, HANDLER = 1 };
 
   SEHTryStmt(bool isCXXTry, // true if 'try' otherwise '__try'
-             SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler,
-             int HandlerIndex, int HandlerParentIndex);
+             SourceLocation TryLoc,
+             Stmt *TryBlock,
+             Stmt *Handler);
 
   friend class ASTReader;
   friend class ASTStmtReader;
   explicit SEHTryStmt(EmptyShell E) : Stmt(SEHTryStmtClass, E) { }
 
 public:
-  static SEHTryStmt *Create(const ASTContext &C, bool isCXXTry,
+  static SEHTryStmt* Create(const ASTContext &C, bool isCXXTry,
                             SourceLocation TryLoc, Stmt *TryBlock,
-                            Stmt *Handler, int HandlerIndex,
-                            int HandlerParentIndex);
+                            Stmt *Handler);
 
   SourceLocation getLocStart() const LLVM_READONLY { return getTryLoc(); }
   SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
@@ -1936,9 +1944,6 @@
   static bool classof(const Stmt *T) {
     return T->getStmtClass() == SEHTryStmtClass;
   }
-
-  int getHandlerIndex() const { return HandlerIndex; }
-  int getHandlerParentIndex() const { return HandlerParentIndex; }
 };
 
 /// Represents a __leave statement.
@@ -1977,15 +1982,18 @@
 /// @endcode
 class CapturedStmt : public Stmt {
 public:
-  /// \brief The different capture forms: by 'this' or by reference, etc.
+  /// \brief The different capture forms: by 'this', by reference, capture for
+  /// variable-length array type etc.
   enum VariableCaptureKind {
     VCK_This,
-    VCK_ByRef
+    VCK_ByRef,
+    VCK_VLAType,
   };
 
-  /// \brief Describes the capture of either a variable or 'this'.
+  /// \brief Describes the capture of either a variable, or 'this', or
+  /// variable-length array type.
   class Capture {
-    llvm::PointerIntPair<VarDecl *, 1, VariableCaptureKind> VarAndKind;
+    llvm::PointerIntPair<VarDecl *, 2, VariableCaptureKind> VarAndKind;
     SourceLocation Loc;
 
   public:
@@ -2007,6 +2015,10 @@
       case VCK_ByRef:
         assert(Var && "capturing by reference must have a variable!");
         break;
+      case VCK_VLAType:
+        assert(!Var &&
+               "Variable-length array type capture cannot have a variable!");
+        break;
       }
     }
 
@@ -2021,13 +2033,20 @@
     bool capturesThis() const { return getCaptureKind() == VCK_This; }
 
     /// \brief Determine whether this capture handles a variable.
-    bool capturesVariable() const { return getCaptureKind() != VCK_This; }
+    bool capturesVariable() const { return getCaptureKind() == VCK_ByRef; }
+
+    /// \brief Determine whether this capture handles a variable-length array
+    /// type.
+    bool capturesVariableArrayType() const {
+      return getCaptureKind() == VCK_VLAType;
+    }
 
     /// \brief Retrieve the declaration of the variable being captured.
     ///
-    /// This operation is only valid if this capture does not capture 'this'.
+    /// This operation is only valid if this capture captures a variable.
     VarDecl *getCapturedVar() const {
-      assert(!capturesThis() && "No variable available for 'this' capture");
+      assert(capturesVariable() &&
+             "No variable available for 'this' or VAT capture");
       return VarAndKind.getPointer();
     }
     friend class ASTStmtReader;
diff --git a/include/clang/AST/StmtGraphTraits.h b/include/clang/AST/StmtGraphTraits.h
index a3e9e1e..ab636a5 100644
--- a/include/clang/AST/StmtGraphTraits.h
+++ b/include/clang/AST/StmtGraphTraits.h
@@ -12,8 +12,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_STMT_GRAPHTRAITS_H
-#define LLVM_CLANG_AST_STMT_GRAPHTRAITS_H
+#ifndef LLVM_CLANG_AST_STMTGRAPHTRAITS_H
+#define LLVM_CLANG_AST_STMTGRAPHTRAITS_H
 
 #include "clang/AST/Stmt.h"
 #include "llvm/ADT/DepthFirstIterator.h"
diff --git a/include/clang/AST/StmtIterator.h b/include/clang/AST/StmtIterator.h
index 18c5516..6ffe74f 100644
--- a/include/clang/AST/StmtIterator.h
+++ b/include/clang/AST/StmtIterator.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_STMT_ITR_H
-#define LLVM_CLANG_AST_STMT_ITR_H
+#ifndef LLVM_CLANG_AST_STMTITERATOR_H
+#define LLVM_CLANG_AST_STMTITERATOR_H
 
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/DataTypes.h"
diff --git a/include/clang/AST/StmtOpenMP.h b/include/clang/AST/StmtOpenMP.h
index db02afe..6a2832c 100644
--- a/include/clang/AST/StmtOpenMP.h
+++ b/include/clang/AST/StmtOpenMP.h
@@ -128,6 +128,13 @@
     operator bool() { return Current != End; }
   };
 
+  /// \brief Gets a single clause of the specified kind \a K associated with the
+  /// current directive iff there is only one clause of this kind (and assertion
+  /// is fired if there is more than one clause is associated with the
+  /// directive). Returns nullptr if no clause of kind \a K is associated with
+  /// the directive.
+  const OMPClause *getSingleClause(OpenMPClauseKind K) const;
+
   /// \brief Returns starting location of directive kind.
   SourceLocation getLocStart() const { return StartLoc; }
   /// \brief Returns ending location of directive.
@@ -238,6 +245,168 @@
   }
 };
 
+/// \brief This is a common base class for loop directives ('omp simd', 'omp
+/// for', 'omp for simd' etc.). It is responsible for the loop code generation.
+///
+class OMPLoopDirective : public OMPExecutableDirective {
+  friend class ASTStmtReader;
+  /// \brief Number of collapsed loops as specified by 'collapse' clause.
+  unsigned CollapsedNum;
+
+  /// \brief Offsets to the stored exprs.
+  enum {
+    AssociatedStmtOffset = 0,
+    IterationVariableOffset = 1,
+    LastIterationOffset = 2,
+    CalcLastIterationOffset = 3,
+    PreConditionOffset = 4,
+    CondOffset = 5,
+    SeparatedCondOffset = 6,
+    InitOffset = 7,
+    IncOffset = 8,
+    ArraysOffset = 9
+  };
+
+  /// \brief Get the counters storage.
+  MutableArrayRef<Expr *> getCounters() {
+    Expr **Storage =
+        reinterpret_cast<Expr **>(&(*(std::next(child_begin(), ArraysOffset))));
+    return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+  }
+
+  /// \brief Get the updates storage.
+  MutableArrayRef<Expr *> getUpdates() {
+    Expr **Storage = reinterpret_cast<Expr **>(
+        &*std::next(child_begin(), ArraysOffset + 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));
+    return MutableArrayRef<Expr *>(Storage, CollapsedNum);
+  }
+
+protected:
+  /// \brief Build instance of loop directive of class \a Kind.
+  ///
+  /// \param SC Statement class.
+  /// \param Kind Kind of OpenMP directive.
+  /// \param StartLoc Starting location of the directive (directive keyword).
+  /// \param EndLoc Ending location of the directive.
+  /// \param CollapsedNum Number of collapsed loops from 'collapse' clause.
+  /// \param NumClauses Number of clauses.
+  /// \param NumSpecialChildren Number of additional directive-specific stmts.
+  ///
+  template <typename T>
+  OMPLoopDirective(const T *That, StmtClass SC, OpenMPDirectiveKind Kind,
+                   SourceLocation StartLoc, SourceLocation EndLoc,
+                   unsigned CollapsedNum, unsigned NumClauses,
+                   unsigned NumSpecialChildren = 0)
+      : OMPExecutableDirective(That, SC, Kind, StartLoc, EndLoc, NumClauses,
+                               numLoopChildren(CollapsedNum) +
+                                   NumSpecialChildren),
+        CollapsedNum(CollapsedNum) {}
+
+  /// \brief Children number.
+  static unsigned numLoopChildren(unsigned CollapsedNum) {
+    return ArraysOffset + 3 * CollapsedNum; // Counters, Updates and Finals
+  }
+
+  void setIterationVariable(Expr *IV) {
+    *std::next(child_begin(), IterationVariableOffset) = IV;
+  }
+  void setLastIteration(Expr *LI) {
+    *std::next(child_begin(), LastIterationOffset) = LI;
+  }
+  void setCalcLastIteration(Expr *CLI) {
+    *std::next(child_begin(), CalcLastIterationOffset) = CLI;
+  }
+  void setPreCond(Expr *PC) {
+    *std::next(child_begin(), PreConditionOffset) = PC;
+  }
+  void setCond(Expr *Cond, Expr *SeparatedCond) {
+    *std::next(child_begin(), CondOffset) = Cond;
+    *std::next(child_begin(), SeparatedCondOffset) = SeparatedCond;
+  }
+  void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; }
+  void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; }
+  void setCounters(ArrayRef<Expr *> A);
+  void setUpdates(ArrayRef<Expr *> A);
+  void setFinals(ArrayRef<Expr *> A);
+
+public:
+  /// \brief Get number of collapsed loops.
+  unsigned getCollapsedNumber() const { return CollapsedNum; }
+
+  Expr *getIterationVariable() const {
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), IterationVariableOffset)));
+  }
+  Expr *getLastIteration() const {
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), LastIterationOffset)));
+  }
+  Expr *getCalcLastIteration() const {
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), CalcLastIterationOffset)));
+  }
+  Expr *getPreCond() const {
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), PreConditionOffset)));
+  }
+  Expr *getCond(bool SeparateIter) const {
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(),
+                   (SeparateIter ? SeparatedCondOffset : CondOffset))));
+  }
+  Expr *getInit() const {
+    return const_cast<Expr *>(
+        reinterpret_cast<const Expr *>(*std::next(child_begin(), InitOffset)));
+  }
+  Expr *getInc() const {
+    return const_cast<Expr *>(
+        reinterpret_cast<const Expr *>(*std::next(child_begin(), IncOffset)));
+  }
+  const Stmt *getBody() const {
+    // This relies on the loop form is already checked by Sema.
+    Stmt *Body = getAssociatedStmt()->IgnoreContainers(true);
+    Body = cast<ForStmt>(Body)->getBody();
+    for (unsigned Cnt = 1; Cnt < CollapsedNum; ++Cnt) {
+      Body = Body->IgnoreContainers();
+      Body = cast<ForStmt>(Body)->getBody();
+    }
+    return Body;
+  }
+
+  ArrayRef<Expr *> counters() { return getCounters(); }
+
+  ArrayRef<Expr *> counters() const {
+    return const_cast<OMPLoopDirective *>(this)->getCounters();
+  }
+
+  ArrayRef<Expr *> updates() { return getUpdates(); }
+
+  ArrayRef<Expr *> updates() const {
+    return const_cast<OMPLoopDirective *>(this)->getUpdates();
+  }
+
+  ArrayRef<Expr *> finals() { return getFinals(); }
+
+  ArrayRef<Expr *> finals() const {
+    return const_cast<OMPLoopDirective *>(this)->getFinals();
+  }
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == OMPSimdDirectiveClass ||
+           T->getStmtClass() == OMPForDirectiveClass ||
+           T->getStmtClass() == OMPForSimdDirectiveClass ||
+           T->getStmtClass() == OMPParallelForDirectiveClass ||
+           T->getStmtClass() == OMPParallelForSimdDirectiveClass;
+  }
+};
+
 /// \brief This represents '#pragma omp simd' directive.
 ///
 /// \code
@@ -247,10 +416,8 @@
 /// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and
 /// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'.
 ///
-class OMPSimdDirective : public OMPExecutableDirective {
+class OMPSimdDirective : public OMPLoopDirective {
   friend class ASTStmtReader;
-  /// \brief Number of collapsed loops as specified by 'collapse' clause.
-  unsigned CollapsedNum;
   /// \brief Build directive with the given start and end location.
   ///
   /// \param StartLoc Starting location of the directive kind.
@@ -260,9 +427,8 @@
   ///
   OMPSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
                    unsigned CollapsedNum, unsigned NumClauses)
-      : OMPExecutableDirective(this, OMPSimdDirectiveClass, OMPD_simd, StartLoc,
-                               EndLoc, NumClauses, 1),
-        CollapsedNum(CollapsedNum) {}
+      : OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, StartLoc,
+                         EndLoc, CollapsedNum, NumClauses) {}
 
   /// \brief Build an empty directive.
   ///
@@ -270,10 +436,9 @@
   /// \param NumClauses Number of clauses.
   ///
   explicit OMPSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
-      : OMPExecutableDirective(this, OMPSimdDirectiveClass, OMPD_simd,
-                               SourceLocation(), SourceLocation(), NumClauses,
-                               1),
-        CollapsedNum(CollapsedNum) {}
+      : OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd,
+                         SourceLocation(), SourceLocation(), CollapsedNum,
+                         NumClauses) {}
 
 public:
   /// \brief Creates directive with a list of \a Clauses.
@@ -284,11 +449,24 @@
   /// \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.
   ///
-  static OMPSimdDirective *Create(const ASTContext &C, SourceLocation StartLoc,
-                                  SourceLocation EndLoc, unsigned CollapsedNum,
-                                  ArrayRef<OMPClause *> Clauses,
-                                  Stmt *AssociatedStmt);
+  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);
 
   /// \brief Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -300,8 +478,6 @@
   static OMPSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
                                        unsigned CollapsedNum, EmptyShell);
 
-  unsigned getCollapsedNumber() const { return CollapsedNum; }
-
   static bool classof(const Stmt *T) {
     return T->getStmtClass() == OMPSimdDirectiveClass;
   }
@@ -316,10 +492,8 @@
 /// variables 'a' and 'b' and 'reduction' with operator '+' and variables 'c'
 /// and 'd'.
 ///
-class OMPForDirective : public OMPExecutableDirective {
+class OMPForDirective : public OMPLoopDirective {
   friend class ASTStmtReader;
-  /// \brief Number of collapsed loops as specified by 'collapse' clause.
-  unsigned CollapsedNum;
   /// \brief Build directive with the given start and end location.
   ///
   /// \param StartLoc Starting location of the directive kind.
@@ -329,9 +503,8 @@
   ///
   OMPForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
                   unsigned CollapsedNum, unsigned NumClauses)
-      : OMPExecutableDirective(this, OMPForDirectiveClass, OMPD_for, StartLoc,
-                               EndLoc, NumClauses, 1),
-        CollapsedNum(CollapsedNum) {}
+      : OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, StartLoc, EndLoc,
+                         CollapsedNum, NumClauses) {}
 
   /// \brief Build an empty directive.
   ///
@@ -339,10 +512,8 @@
   /// \param NumClauses Number of clauses.
   ///
   explicit OMPForDirective(unsigned CollapsedNum, unsigned NumClauses)
-      : OMPExecutableDirective(this, OMPForDirectiveClass, OMPD_for,
-                               SourceLocation(), SourceLocation(), NumClauses,
-                               1),
-        CollapsedNum(CollapsedNum) {}
+      : OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, SourceLocation(),
+                         SourceLocation(), CollapsedNum, NumClauses) {}
 
 public:
   /// \brief Creates directive with a list of \a Clauses.
@@ -353,11 +524,24 @@
   /// \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.
   ///
-  static OMPForDirective *Create(const ASTContext &C, SourceLocation StartLoc,
-                                 SourceLocation EndLoc, unsigned CollapsedNum,
-                                 ArrayRef<OMPClause *> Clauses,
-                                 Stmt *AssociatedStmt);
+  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);
 
   /// \brief Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -369,13 +553,88 @@
   static OMPForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
                                       unsigned CollapsedNum, EmptyShell);
 
-  unsigned getCollapsedNumber() const { return CollapsedNum; }
-
   static bool classof(const Stmt *T) {
     return T->getStmtClass() == OMPForDirectiveClass;
   }
 };
 
+/// \brief This represents '#pragma omp for simd' directive.
+///
+/// \code
+/// #pragma omp for simd private(a,b) linear(i,j:s) reduction(+:c,d)
+/// \endcode
+/// In this example directive '#pragma omp for simd' has clauses 'private'
+/// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and
+/// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'.
+///
+class OMPForSimdDirective : public OMPLoopDirective {
+  friend class ASTStmtReader;
+  /// \brief Build directive with the given start and end location.
+  ///
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending location of the directive.
+  /// \param CollapsedNum Number of collapsed nested loops.
+  /// \param NumClauses Number of clauses.
+  ///
+  OMPForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
+                      unsigned CollapsedNum, unsigned NumClauses)
+      : OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd,
+                         StartLoc, EndLoc, CollapsedNum, NumClauses) {}
+
+  /// \brief Build an empty directive.
+  ///
+  /// \param CollapsedNum Number of collapsed nested loops.
+  /// \param NumClauses Number of clauses.
+  ///
+  explicit OMPForSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
+      : OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd,
+                         SourceLocation(), SourceLocation(), CollapsedNum,
+                         NumClauses) {}
+
+public:
+  /// \brief Creates directive with a list of \a Clauses.
+  ///
+  /// \param C AST context.
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending Location of the directive.
+  /// \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.
+  ///
+  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);
+
+  /// \brief Creates an empty directive with the place
+  /// for \a NumClauses clauses.
+  ///
+  /// \param C AST context.
+  /// \param CollapsedNum Number of collapsed nested loops.
+  /// \param NumClauses Number of clauses.
+  ///
+  static OMPForSimdDirective *CreateEmpty(const ASTContext &C,
+                                          unsigned NumClauses,
+                                          unsigned CollapsedNum, EmptyShell);
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == OMPForSimdDirectiveClass;
+  }
+};
+
 /// \brief This represents '#pragma omp sections' directive.
 ///
 /// \code
@@ -657,10 +916,8 @@
 /// with the variables 'a' and 'b' and 'reduction' with operator '+' and
 /// variables 'c' and 'd'.
 ///
-class OMPParallelForDirective : public OMPExecutableDirective {
+class OMPParallelForDirective : public OMPLoopDirective {
   friend class ASTStmtReader;
-  /// \brief Number of collapsed loops as specified by 'collapse' clause.
-  unsigned CollapsedNum;
   /// \brief Build directive with the given start and end location.
   ///
   /// \param StartLoc Starting location of the directive kind.
@@ -670,10 +927,8 @@
   ///
   OMPParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
                           unsigned CollapsedNum, unsigned NumClauses)
-      : OMPExecutableDirective(this, OMPParallelForDirectiveClass,
-                               OMPD_parallel_for, StartLoc, EndLoc, NumClauses,
-                               1),
-        CollapsedNum(CollapsedNum) {}
+      : OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for,
+                         StartLoc, EndLoc, CollapsedNum, NumClauses) {}
 
   /// \brief Build an empty directive.
   ///
@@ -681,10 +936,9 @@
   /// \param NumClauses Number of clauses.
   ///
   explicit OMPParallelForDirective(unsigned CollapsedNum, unsigned NumClauses)
-      : OMPExecutableDirective(this, OMPParallelForDirectiveClass,
-                               OMPD_parallel_for, SourceLocation(),
-                               SourceLocation(), NumClauses, 1),
-        CollapsedNum(CollapsedNum) {}
+      : OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for,
+                         SourceLocation(), SourceLocation(), CollapsedNum,
+                         NumClauses) {}
 
 public:
   /// \brief Creates directive with a list of \a Clauses.
@@ -695,11 +949,24 @@
   /// \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.
   ///
   static OMPParallelForDirective *
   Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
          unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
-         Stmt *AssociatedStmt);
+         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);
 
   /// \brief Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -713,13 +980,92 @@
                                               unsigned CollapsedNum,
                                               EmptyShell);
 
-  unsigned getCollapsedNumber() const { return CollapsedNum; }
-
   static bool classof(const Stmt *T) {
     return T->getStmtClass() == OMPParallelForDirectiveClass;
   }
 };
 
+/// \brief This represents '#pragma omp parallel for simd' directive.
+///
+/// \code
+/// #pragma omp parallel for simd private(a,b) linear(i,j:s) reduction(+:c,d)
+/// \endcode
+/// In this example directive '#pragma omp parallel for simd' has clauses
+/// 'private' with the variables 'a' and 'b', 'linear' with variables 'i', 'j'
+/// and linear step 's', 'reduction' with operator '+' and variables 'c' and
+/// 'd'.
+///
+class OMPParallelForSimdDirective : public OMPLoopDirective {
+  friend class ASTStmtReader;
+  /// \brief Build directive with the given start and end location.
+  ///
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending location of the directive.
+  /// \param CollapsedNum Number of collapsed nested loops.
+  /// \param NumClauses Number of clauses.
+  ///
+  OMPParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
+                              unsigned CollapsedNum, unsigned NumClauses)
+      : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass,
+                         OMPD_parallel_for_simd, StartLoc, EndLoc, CollapsedNum,
+                         NumClauses) {}
+
+  /// \brief Build an empty directive.
+  ///
+  /// \param CollapsedNum Number of collapsed nested loops.
+  /// \param NumClauses Number of clauses.
+  ///
+  explicit OMPParallelForSimdDirective(unsigned CollapsedNum,
+                                       unsigned NumClauses)
+      : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass,
+                         OMPD_parallel_for_simd, SourceLocation(),
+                         SourceLocation(), CollapsedNum, NumClauses) {}
+
+public:
+  /// \brief Creates directive with a list of \a Clauses.
+  ///
+  /// \param C AST context.
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending Location of the directive.
+  /// \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.
+  ///
+  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);
+
+  /// \brief Creates an empty directive with the place
+  /// for \a NumClauses clauses.
+  ///
+  /// \param C AST context.
+  /// \param CollapsedNum Number of collapsed nested loops.
+  /// \param NumClauses Number of clauses.
+  ///
+  static OMPParallelForSimdDirective *CreateEmpty(const ASTContext &C,
+                                                  unsigned NumClauses,
+                                                  unsigned CollapsedNum,
+                                                  EmptyShell);
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == OMPParallelForSimdDirectiveClass;
+  }
+};
+
 /// \brief This represents '#pragma omp parallel sections' directive.
 ///
 /// \code
@@ -1028,6 +1374,253 @@
   }
 };
 
+/// \brief This represents '#pragma omp ordered' directive.
+///
+/// \code
+/// #pragma omp ordered
+/// \endcode
+///
+class OMPOrderedDirective : public OMPExecutableDirective {
+  friend class ASTStmtReader;
+  /// \brief Build directive with the given start and end location.
+  ///
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending location of the directive.
+  ///
+  OMPOrderedDirective(SourceLocation StartLoc, SourceLocation EndLoc)
+      : OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered,
+                               StartLoc, EndLoc, 0, 1) {}
+
+  /// \brief Build an empty directive.
+  ///
+  explicit OMPOrderedDirective()
+      : OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered,
+                               SourceLocation(), SourceLocation(), 0, 1) {}
+
+public:
+  /// \brief Creates directive.
+  ///
+  /// \param C AST context.
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending Location of the directive.
+  /// \param AssociatedStmt Statement, associated with the directive.
+  ///
+  static OMPOrderedDirective *Create(const ASTContext &C,
+                                     SourceLocation StartLoc,
+                                     SourceLocation EndLoc,
+                                     Stmt *AssociatedStmt);
+
+  /// \brief Creates an empty directive.
+  ///
+  /// \param C AST context.
+  ///
+  static OMPOrderedDirective *CreateEmpty(const ASTContext &C, EmptyShell);
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == OMPOrderedDirectiveClass;
+  }
+};
+
+/// \brief This represents '#pragma omp atomic' directive.
+///
+/// \code
+/// #pragma omp atomic capture
+/// \endcode
+/// In this example directive '#pragma omp atomic' has clause 'capture'.
+///
+class OMPAtomicDirective : public OMPExecutableDirective {
+  friend class ASTStmtReader;
+  /// \brief Build directive with the given start and end location.
+  ///
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending location of the directive.
+  /// \param NumClauses Number of clauses.
+  ///
+  OMPAtomicDirective(SourceLocation StartLoc, SourceLocation EndLoc,
+                     unsigned NumClauses)
+      : OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic,
+                               StartLoc, EndLoc, NumClauses, 4) {}
+
+  /// \brief Build an empty directive.
+  ///
+  /// \param NumClauses Number of clauses.
+  ///
+  explicit OMPAtomicDirective(unsigned NumClauses)
+      : OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic,
+                               SourceLocation(), SourceLocation(), NumClauses,
+                               4) {}
+
+  /// \brief Set 'x' part of the associated expression/statement.
+  void setX(Expr *X) { *std::next(child_begin()) = X; }
+  /// \brief Set 'v' part of the associated expression/statement.
+  void setV(Expr *V) { *std::next(child_begin(), 2) = V; }
+  /// \brief Set 'expr' part of the associated expression/statement.
+  void setExpr(Expr *E) { *std::next(child_begin(), 3) = E; }
+
+public:
+  /// \brief Creates directive with a list of \a Clauses and 'x', 'v' and 'expr'
+  /// parts of the atomic construct (see Section 2.12.6, atomic Construct, for
+  /// detailed description of 'x', 'v' and 'expr').
+  ///
+  /// \param C AST context.
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending Location of the directive.
+  /// \param Clauses List of clauses.
+  /// \param AssociatedStmt Statement, associated with the directive.
+  /// \param X 'x' part of the associated expression/statement.
+  /// \param V 'v' part of the associated expression/statement.
+  /// \param E 'expr' part of the associated expression/statement.
+  ///
+  static OMPAtomicDirective *
+  Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
+         ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, Expr *X, Expr *V,
+         Expr *E);
+
+  /// \brief Creates an empty directive with the place for \a NumClauses
+  /// clauses.
+  ///
+  /// \param C AST context.
+  /// \param NumClauses Number of clauses.
+  ///
+  static OMPAtomicDirective *CreateEmpty(const ASTContext &C,
+                                         unsigned NumClauses, EmptyShell);
+
+  /// \brief Get 'x' part of the associated expression/statement.
+  Expr *getX() { return cast_or_null<Expr>(*std::next(child_begin())); }
+  const Expr *getX() const {
+    return cast_or_null<Expr>(*std::next(child_begin()));
+  }
+  /// \brief Get 'v' part of the associated expression/statement.
+  Expr *getV() { return cast_or_null<Expr>(*std::next(child_begin(), 2)); }
+  const Expr *getV() const {
+    return cast_or_null<Expr>(*std::next(child_begin(), 2));
+  }
+  /// \brief Get 'expr' part of the associated expression/statement.
+  Expr *getExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 3)); }
+  const Expr *getExpr() const {
+    return cast_or_null<Expr>(*std::next(child_begin(), 3));
+  }
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == OMPAtomicDirectiveClass;
+  }
+};
+
+/// \brief This represents '#pragma omp target' directive.
+///
+/// \code
+/// #pragma omp target if(a)
+/// \endcode
+/// In this example directive '#pragma omp target' has clause 'if' with
+/// condition 'a'.
+///
+class OMPTargetDirective : public OMPExecutableDirective {
+  friend class ASTStmtReader;
+  /// \brief Build directive with the given start and end location.
+  ///
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending location of the directive.
+  /// \param NumClauses Number of clauses.
+  ///
+  OMPTargetDirective(SourceLocation StartLoc, SourceLocation EndLoc,
+                     unsigned NumClauses)
+      : OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target,
+                               StartLoc, EndLoc, NumClauses, 1) {}
+
+  /// \brief Build an empty directive.
+  ///
+  /// \param NumClauses Number of clauses.
+  ///
+  explicit OMPTargetDirective(unsigned NumClauses)
+      : OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target,
+                               SourceLocation(), SourceLocation(), NumClauses,
+                               1) {}
+
+public:
+  /// \brief Creates directive with a list of \a Clauses.
+  ///
+  /// \param C AST context.
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending Location of the directive.
+  /// \param Clauses List of clauses.
+  /// \param AssociatedStmt Statement, associated with the directive.
+  ///
+  static OMPTargetDirective *
+  Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
+         ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
+
+  /// \brief Creates an empty directive with the place for \a NumClauses
+  /// clauses.
+  ///
+  /// \param C AST context.
+  /// \param NumClauses Number of clauses.
+  ///
+  static OMPTargetDirective *CreateEmpty(const ASTContext &C,
+                                         unsigned NumClauses, EmptyShell);
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == OMPTargetDirectiveClass;
+  }
+};
+
+/// \brief This represents '#pragma omp teams' directive.
+///
+/// \code
+/// #pragma omp teams if(a)
+/// \endcode
+/// In this example directive '#pragma omp teams' has clause 'if' with
+/// condition 'a'.
+///
+class OMPTeamsDirective : public OMPExecutableDirective {
+  friend class ASTStmtReader;
+  /// \brief Build directive with the given start and end location.
+  ///
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending location of the directive.
+  /// \param NumClauses Number of clauses.
+  ///
+  OMPTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
+                    unsigned NumClauses)
+      : OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams,
+                               StartLoc, EndLoc, NumClauses, 1) {}
+
+  /// \brief Build an empty directive.
+  ///
+  /// \param NumClauses Number of clauses.
+  ///
+  explicit OMPTeamsDirective(unsigned NumClauses)
+      : OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams,
+                               SourceLocation(), SourceLocation(), NumClauses,
+                               1) {}
+
+public:
+  /// \brief Creates directive with a list of \a Clauses.
+  ///
+  /// \param C AST context.
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending Location of the directive.
+  /// \param Clauses List of clauses.
+  /// \param AssociatedStmt Statement, associated with the directive.
+  ///
+  static OMPTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc,
+                                   SourceLocation EndLoc,
+                                   ArrayRef<OMPClause *> Clauses,
+                                   Stmt *AssociatedStmt);
+
+  /// \brief Creates an empty directive with the place for \a NumClauses
+  /// clauses.
+  ///
+  /// \param C AST context.
+  /// \param NumClauses Number of clauses.
+  ///
+  static OMPTeamsDirective *CreateEmpty(const ASTContext &C,
+                                        unsigned NumClauses, EmptyShell);
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == OMPTeamsDirectiveClass;
+  }
+};
+
 } // end namespace clang
 
 #endif
diff --git a/include/clang/AST/TemplateBase.h b/include/clang/AST/TemplateBase.h
index 1026a78..f3c6440 100644
--- a/include/clang/AST/TemplateBase.h
+++ b/include/clang/AST/TemplateBase.h
@@ -76,7 +76,7 @@
 
   struct DA {
     unsigned Kind;
-    bool ForRefParam;
+    void *QT;
     ValueDecl *D;
   };
   struct I {
@@ -132,11 +132,11 @@
   /// \brief Construct a template argument that refers to a
   /// declaration, which is either an external declaration or a
   /// template declaration.
-  TemplateArgument(ValueDecl *D, bool ForRefParam) {
+  TemplateArgument(ValueDecl *D, QualType QT) {
     assert(D && "Expected decl");
     DeclArg.Kind = Declaration;
+    DeclArg.QT = QT.getAsOpaquePtr();
     DeclArg.D = D;
-    DeclArg.ForRefParam = ForRefParam;
   }
 
   /// \brief Construct an integral constant template argument. The memory to
@@ -249,11 +249,9 @@
     return DeclArg.D;
   }
 
-  /// \brief Retrieve whether a declaration is binding to a
-  /// reference parameter in a declaration non-type template argument.
-  bool isDeclForReferenceParam() const {
+  QualType getParamTypeForDecl() const {
     assert(getKind() == Declaration && "Unexpected kind");
-    return DeclArg.ForRefParam;
+    return QualType::getFromOpaquePtr(DeclArg.QT);
   }
 
   /// \brief Retrieve the type for null non-type template argument.
@@ -344,7 +342,7 @@
   /// \brief Return the array of arguments in this template argument pack.
   ArrayRef<TemplateArgument> getPackAsArray() const {
     assert(getKind() == Pack);
-    return ArrayRef<TemplateArgument>(Args.Args, Args.NumArgs);
+    return llvm::makeArrayRef(Args.Args, Args.NumArgs);
   }
 
   /// \brief Determines whether two template arguments are superficially the
diff --git a/include/clang/AST/Type.h b/include/clang/AST/Type.h
index 09862e4f..9c3af07 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"
@@ -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
@@ -1245,6 +1261,7 @@
 
   class FunctionTypeBitfields {
     friend class FunctionType;
+    friend class FunctionProtoType;
 
     unsigned : NumTypeBits;
 
@@ -1259,6 +1276,11 @@
     /// C++ 8.3.5p4: The return type, the parameter type list and the
     /// cv-qualifier-seq, [...], are part of the function type.
     unsigned TypeQuals : 3;
+
+    /// \brief The ref-qualifier associated with a \c FunctionProtoType.
+    ///
+    /// This is a value of type \c RefQualifierKind.
+    unsigned RefQualifier : 2;
   };
 
   class ObjCObjectTypeBitfields {
@@ -1982,6 +2004,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); }
 
@@ -2765,7 +2803,7 @@
 
 protected:
   FunctionType(TypeClass tc, QualType res,
-               unsigned typeQuals, QualType Canonical, bool Dependent,
+               QualType Canonical, bool Dependent,
                bool InstantiationDependent,
                bool VariablyModified, bool ContainsUnexpandedParameterPack,
                ExtInfo Info)
@@ -2773,7 +2811,6 @@
            ContainsUnexpandedParameterPack),
       ResultType(res) {
     FunctionTypeBits.ExtInfo = Info.Bits;
-    FunctionTypeBits.TypeQuals = typeQuals;
   }
   unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
 
@@ -2810,7 +2847,7 @@
 /// no information available about its arguments.
 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
   FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
-    : FunctionType(FunctionNoProto, Result, 0, Canonical,
+    : FunctionType(FunctionNoProto, Result, Canonical,
                    /*Dependent=*/false, /*InstantiationDependent=*/false,
                    Result->isVariablyModifiedType(),
                    /*ContainsUnexpandedParameterPack=*/false, Info) {}
@@ -2844,33 +2881,51 @@
 /// type.
 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
 public:
+  struct ExceptionSpecInfo {
+    ExceptionSpecInfo()
+        : Type(EST_None), NoexceptExpr(nullptr),
+          SourceDecl(nullptr), SourceTemplate(nullptr) {}
+
+    ExceptionSpecInfo(ExceptionSpecificationType EST)
+        : Type(EST), NoexceptExpr(nullptr), SourceDecl(nullptr),
+          SourceTemplate(nullptr) {}
+
+    /// The kind of exception specification this is.
+    ExceptionSpecificationType Type;
+    /// Explicitly-specified list of exception types.
+    ArrayRef<QualType> Exceptions;
+    /// Noexcept expression, if this is EST_ComputedNoexcept.
+    Expr *NoexceptExpr;
+    /// The function whose exception specification this is, for
+    /// EST_Unevaluated and EST_Uninstantiated.
+    FunctionDecl *SourceDecl;
+    /// The function template whose exception specification this is instantiated
+    /// from, for EST_Uninstantiated.
+    FunctionDecl *SourceTemplate;
+  };
+
   /// ExtProtoInfo - Extra information about a function prototype.
   struct ExtProtoInfo {
     ExtProtoInfo()
         : Variadic(false), HasTrailingReturn(false), TypeQuals(0),
-          ExceptionSpecType(EST_None), RefQualifier(RQ_None), NumExceptions(0),
-          Exceptions(nullptr), NoexceptExpr(nullptr),
-          ExceptionSpecDecl(nullptr), ExceptionSpecTemplate(nullptr),
-          ConsumedParameters(nullptr) {}
+          RefQualifier(RQ_None), ConsumedParameters(nullptr) {}
 
     ExtProtoInfo(CallingConv CC)
         : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
-          ExceptionSpecType(EST_None), RefQualifier(RQ_None), NumExceptions(0),
-          Exceptions(nullptr), NoexceptExpr(nullptr),
-          ExceptionSpecDecl(nullptr), ExceptionSpecTemplate(nullptr),
-          ConsumedParameters(nullptr) {}
+          RefQualifier(RQ_None), ConsumedParameters(nullptr) {}
+
+    ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
+      ExtProtoInfo Result(*this);
+      Result.ExceptionSpec = O;
+      return Result;
+    }
 
     FunctionType::ExtInfo ExtInfo;
     bool Variadic : 1;
     bool HasTrailingReturn : 1;
     unsigned char TypeQuals;
-    ExceptionSpecificationType ExceptionSpecType;
     RefQualifierKind RefQualifier;
-    unsigned NumExceptions;
-    const QualType *Exceptions;
-    Expr *NoexceptExpr;
-    FunctionDecl *ExceptionSpecDecl;
-    FunctionDecl *ExceptionSpecTemplate;
+    ExceptionSpecInfo ExceptionSpec;
     const bool *ConsumedParameters;
   };
 
@@ -2896,7 +2951,7 @@
   unsigned NumExceptions : 9;
 
   /// ExceptionSpecType - The type of exception specification this function has.
-  unsigned ExceptionSpecType : 3;
+  unsigned ExceptionSpecType : 4;
 
   /// HasAnyConsumedParams - Whether this function has any consumed parameters.
   unsigned HasAnyConsumedParams : 1;
@@ -2907,11 +2962,6 @@
   /// HasTrailingReturn - Whether this function has a trailing return type.
   unsigned HasTrailingReturn : 1;
 
-  /// \brief The ref-qualifier associated with a \c FunctionProtoType.
-  ///
-  /// This is a value of type \c RefQualifierKind.
-  unsigned RefQualifier : 2;
-
   // ParamInfo - There is an variable size array after the class in memory that
   // holds the parameter types.
 
@@ -2952,7 +3002,7 @@
     return param_type_begin()[i];
   }
   ArrayRef<QualType> getParamTypes() const {
-    return ArrayRef<QualType>(param_type_begin(), param_type_end());
+    return llvm::makeArrayRef(param_type_begin(), param_type_end());
   }
 
   ExtProtoInfo getExtProtoInfo() const {
@@ -2960,19 +3010,18 @@
     EPI.ExtInfo = getExtInfo();
     EPI.Variadic = isVariadic();
     EPI.HasTrailingReturn = hasTrailingReturn();
-    EPI.ExceptionSpecType = getExceptionSpecType();
+    EPI.ExceptionSpec.Type = getExceptionSpecType();
     EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
     EPI.RefQualifier = getRefQualifier();
-    if (EPI.ExceptionSpecType == EST_Dynamic) {
-      EPI.NumExceptions = NumExceptions;
-      EPI.Exceptions = exception_begin();
-    } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
-      EPI.NoexceptExpr = getNoexceptExpr();
-    } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
-      EPI.ExceptionSpecDecl = getExceptionSpecDecl();
-      EPI.ExceptionSpecTemplate = getExceptionSpecTemplate();
-    } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
-      EPI.ExceptionSpecDecl = getExceptionSpecDecl();
+    if (EPI.ExceptionSpec.Type == EST_Dynamic) {
+      EPI.ExceptionSpec.Exceptions = exceptions();
+    } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
+      EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
+    } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
+      EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
+      EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
+    } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
+      EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
     }
     if (hasAnyConsumedParams())
       EPI.ConsumedParameters = getConsumedParamsBuffer();
@@ -2995,6 +3044,8 @@
   bool hasNoexceptExceptionSpec() const {
     return isNoexceptExceptionSpec(getExceptionSpecType());
   }
+  /// \brief Return whether this function has a dependent exception spec.
+  bool hasDependentExceptionSpec() const;
   /// \brief Result type of getNoexceptSpec().
   enum NoexceptResult {
     NR_NoNoexcept,  ///< There is no noexcept specifier.
@@ -3057,7 +3108,7 @@
 
   /// \brief Retrieve the ref-qualifier associated with this function type.
   RefQualifierKind getRefQualifier() const {
-    return static_cast<RefQualifierKind>(RefQualifier);
+    return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
   }
 
   typedef const QualType *param_type_iterator;
@@ -3074,10 +3125,9 @@
   }
 
   typedef const QualType *exception_iterator;
-  typedef llvm::iterator_range<exception_iterator> exception_range;
 
-  exception_range exceptions() const {
-    return exception_range(exception_begin(), exception_end());
+  ArrayRef<QualType> exceptions() const {
+    return llvm::makeArrayRef(exception_begin(), exception_end());
   }
   exception_iterator exception_begin() const {
     // exceptions begin where arguments end
@@ -3416,6 +3466,7 @@
     attr_stdcall,
     attr_thiscall,
     attr_pascal,
+    attr_vectorcall,
     attr_pnaclcall,
     attr_inteloclbicc,
     attr_ms_abi,
@@ -5231,8 +5282,8 @@
   ArrayType_cannot_be_used_with_getAs<T> at;
   (void) at;
 
-  assert(isa<T>(CanonicalType));
   if (const T *ty = dyn_cast<T>(this)) return ty;
+  assert(isa<T>(CanonicalType));
   return cast<T>(getUnqualifiedDesugaredType());
 }
 
diff --git a/include/clang/AST/TypeLoc.h b/include/clang/AST/TypeLoc.h
index 3648d2a..4f3c811 100644
--- a/include/clang/AST/TypeLoc.h
+++ b/include/clang/AST/TypeLoc.h
@@ -1208,7 +1208,7 @@
   }
 
   ArrayRef<ParmVarDecl *> getParams() const {
-    return ArrayRef<ParmVarDecl *>(getParmArray(), getNumParams());
+    return llvm::makeArrayRef(getParmArray(), getNumParams());
   }
 
   // ParmVarDecls* are stored after Info, one for each parameter.
@@ -1567,6 +1567,8 @@
   void setUnderlyingTInfo(TypeSourceInfo* TI) const {
     this->getLocalData()->UnderlyingTInfo = TI;
   }
+
+  void initializeLocal(ASTContext &Context, SourceLocation Loc);
 };
 
 // FIXME: location of the 'decltype' and parens.
diff --git a/include/clang/AST/TypeOrdering.h b/include/clang/AST/TypeOrdering.h
index 9c9f15e..392e544 100644
--- a/include/clang/AST/TypeOrdering.h
+++ b/include/clang/AST/TypeOrdering.h
@@ -16,8 +16,8 @@
 ///
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_TYPE_ORDERING_H
-#define LLVM_CLANG_TYPE_ORDERING_H
+#ifndef LLVM_CLANG_AST_TYPEORDERING_H
+#define LLVM_CLANG_AST_TYPEORDERING_H
 
 #include "clang/AST/CanonicalType.h"
 #include "clang/AST/Type.h"
diff --git a/include/clang/AST/UnresolvedSet.h b/include/clang/AST/UnresolvedSet.h
index 2ef5800..a11f22d 100644
--- a/include/clang/AST/UnresolvedSet.h
+++ b/include/clang/AST/UnresolvedSet.h
@@ -98,7 +98,7 @@
 private:
   template <unsigned N> friend class UnresolvedSet;
   UnresolvedSetImpl() {}
-  UnresolvedSetImpl(const UnresolvedSetImpl &) LLVM_DELETED_FUNCTION;
+  UnresolvedSetImpl(const UnresolvedSetImpl &) {}
 
 public:
   // We don't currently support assignment through this iterator, so we might
diff --git a/include/clang/ASTMatchers/ASTMatchFinder.h b/include/clang/ASTMatchers/ASTMatchFinder.h
index 8af0546..ce2674e 100644
--- a/include/clang/ASTMatchers/ASTMatchFinder.h
+++ b/include/clang/ASTMatchers/ASTMatchFinder.h
@@ -38,10 +38,12 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCH_FINDER_H
-#define LLVM_CLANG_AST_MATCHERS_AST_MATCH_FINDER_H
+#ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHFINDER_H
+#define LLVM_CLANG_ASTMATCHERS_ASTMATCHFINDER_H
 
 #include "clang/ASTMatchers/ASTMatchers.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/Support/Timer.h"
 
 namespace clang {
 
@@ -102,6 +104,12 @@
     ///
     /// Optionally override to do per translation unit tasks.
     virtual void onEndOfTranslationUnit() {}
+
+    /// \brief An id used to group the matchers.
+    ///
+    /// This id is used, for example, for the profiling output.
+    /// It defaults to "<unknown>".
+    virtual StringRef getID() const;
   };
 
   /// \brief Called when parsing is finished. Intended for testing only.
@@ -111,7 +119,22 @@
     virtual void run() = 0;
   };
 
-  MatchFinder();
+  struct MatchFinderOptions {
+    struct Profiling {
+      Profiling(llvm::StringMap<llvm::TimeRecord> &Records)
+          : Records(Records) {}
+
+      /// \brief Per bucket timing information.
+      llvm::StringMap<llvm::TimeRecord> &Records;
+    };
+
+    /// \brief Enables per-check timers.
+    ///
+    /// It prints a report after match.
+    llvm::Optional<Profiling> CheckProfiling;
+  };
+
+  MatchFinder(MatchFinderOptions Options = MatchFinderOptions());
   ~MatchFinder();
 
   /// \brief Adds a matcher to execute when running over the AST.
@@ -148,7 +171,7 @@
                          MatchCallback *Action);
 
   /// \brief Creates a clang ASTConsumer that finds all matches.
-  clang::ASTConsumer *newASTConsumer();
+  std::unique_ptr<clang::ASTConsumer> newASTConsumer();
 
   /// \brief Calls the registered callbacks on all matches on the given \p Node.
   ///
@@ -173,11 +196,25 @@
   /// Each call to FindAll(...) will call the closure once.
   void registerTestCallbackAfterParsing(ParsingDoneTestCallback *ParsingDone);
 
-private:
-  /// \brief For each \c DynTypedMatcher a \c MatchCallback that will be called
+  /// \brief For each \c Matcher<> a \c MatchCallback that will be called
   /// when it matches.
-  std::vector<std::pair<internal::DynTypedMatcher, MatchCallback *> >
-    MatcherCallbackPairs;
+  struct MatchersByType {
+    std::vector<std::pair<internal::DynTypedMatcher, MatchCallback *>>
+        DeclOrStmt;
+    std::vector<std::pair<TypeMatcher, MatchCallback *>> Type;
+    std::vector<std::pair<NestedNameSpecifierMatcher, MatchCallback *>>
+        NestedNameSpecifier;
+    std::vector<std::pair<NestedNameSpecifierLocMatcher, MatchCallback *>>
+        NestedNameSpecifierLoc;
+    std::vector<std::pair<TypeLocMatcher, MatchCallback *>> TypeLoc;
+    /// \brief All the callbacks in one container to simplify iteration.
+    std::vector<MatchCallback *> AllCallbacks;
+  };
+
+private:
+  MatchersByType Matchers;
+
+  MatchFinderOptions Options;
 
   /// \brief Called when parsing is done.
   ParsingDoneTestCallback *ParsingDone;
@@ -210,16 +247,14 @@
 ///
 /// This is useful in combanation with \c match():
 /// \code
-///   Decl *D = selectFirst<Decl>("id", match(Matcher.bind("id"),
-///                                           Node, Context));
+///   const Decl *D = selectFirst<Decl>("id", match(Matcher.bind("id"),
+///                                                 Node, Context));
 /// \endcode
 template <typename NodeT>
-NodeT *
+const NodeT *
 selectFirst(StringRef BoundTo, const SmallVectorImpl<BoundNodes> &Results) {
-  for (SmallVectorImpl<BoundNodes>::const_iterator I = Results.begin(),
-                                                   E = Results.end();
-       I != E; ++I) {
-    if (NodeT *Node = I->getNodeAs<NodeT>(BoundTo))
+  for (const BoundNodes &N : Results) {
+    if (const NodeT *Node = N.getNodeAs<NodeT>(BoundTo))
       return Node;
   }
   return nullptr;
@@ -243,7 +278,7 @@
   MatchFinder Finder;
   Finder.addMatcher(Matcher, &Callback);
   Finder.match(Node, Context);
-  return Callback.Nodes;
+  return std::move(Callback.Nodes);
 }
 
 template <typename MatcherT, typename NodeT>
@@ -255,4 +290,4 @@
 } // end namespace ast_matchers
 } // end namespace clang
 
-#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCH_FINDER_H
+#endif
diff --git a/include/clang/ASTMatchers/ASTMatchers.h b/include/clang/ASTMatchers/ASTMatchers.h
index 1ff4ab3..cbdca79 100644
--- a/include/clang/ASTMatchers/ASTMatchers.h
+++ b/include/clang/ASTMatchers/ASTMatchers.h
@@ -42,11 +42,12 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
-#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
+#ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
+#define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
 
 #include "clang/AST/DeclFriend.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchersInternal.h"
 #include "clang/ASTMatchers/ASTMatchersMacros.h"
 #include "llvm/ADT/Twine.h"
@@ -140,9 +141,97 @@
 /// \endcode
 ///
 /// Usable as: Any Matcher
-inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>
-anything() {
-  return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
+inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
+
+/// \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.
@@ -156,6 +245,17 @@
 /// \endcode
 const internal::VariadicAllOfMatcher<Decl> decl;
 
+/// \brief Matches a declaration of a linkage specification.
+///
+/// Given
+/// \code
+///   extern "C" {}
+/// \endcode
+/// linkageSpecDecl()
+///   matches "extern "C" {}"
+const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
+    linkageSpecDecl;
+
 /// \brief Matches a declaration of anything that could have a name.
 ///
 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
@@ -263,6 +363,17 @@
 /// \endcode
 const internal::VariadicAllOfMatcher<CXXCtorInitializer> ctorInitializer;
 
+/// \brief Matches template arguments.
+///
+/// Given
+/// \code
+///   template <typename T> struct C {};
+///   C<int> c;
+/// \endcode
+/// templateArgument()
+///   matches 'int' in C<int>.
+const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
+
 /// \brief Matches public C++ declarations.
 ///
 /// Given
@@ -441,6 +552,23 @@
   return InnerMatcher.matches(List[N], Finder, Builder);
 }
 
+/// \brief Matches if the number of template arguments equals \p N.
+///
+/// Given
+/// \code
+///   template<typename T> struct C {};
+///   C<int> c;
+/// \endcode
+/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
+///   matches C<int>.
+AST_POLYMORPHIC_MATCHER_P(
+    templateArgumentCountIs,
+    AST_POLYMORPHIC_SUPPORTED_TYPES_2(ClassTemplateSpecializationDecl,
+                                      TemplateSpecializationType),
+    unsigned, N) {
+  return internal::getTemplateSpecializationArgs(Node).size() == N;
+}
+
 /// \brief Matches a TemplateArgument that refers to a certain type.
 ///
 /// Given
@@ -497,6 +625,68 @@
   return false;
 }
 
+/// \brief Matches a TemplateArgument that is an integral value.
+///
+/// Given
+/// \code
+///   template<int T> struct A {};
+///   C<42> c;
+/// \endcode
+/// classTemplateSpecializationDecl(
+///   hasAnyTemplateArgument(isIntegral()))
+///   matches the implicit instantiation of C in C<42>
+///   with isIntegral() matching 42.
+AST_MATCHER(TemplateArgument, isIntegral) {
+  return Node.getKind() == TemplateArgument::Integral;
+}
+
+/// \brief Matches a TemplateArgument that referes to an integral type.
+///
+/// Given
+/// \code
+///   template<int T> struct A {};
+///   C<42> c;
+/// \endcode
+/// classTemplateSpecializationDecl(
+///   hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
+///   matches the implicit instantiation of C in C<42>.
+AST_MATCHER_P(TemplateArgument, refersToIntegralType,
+              internal::Matcher<QualType>, InnerMatcher) {
+  if (Node.getKind() != TemplateArgument::Integral)
+    return false;
+  return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
+}
+
+/// \brief Matches a TemplateArgument of integral type with a given value.
+///
+/// Note that 'Value' is a string as the template argument's value is
+/// an arbitrary precision integer. 'Value' must be euqal to the canonical
+/// representation of that integral value in base 10.
+///
+/// Given
+/// \code
+///   template<int T> struct A {};
+///   C<42> c;
+/// \endcode
+/// classTemplateSpecializationDecl(
+///   hasAnyTemplateArgument(equalsIntegralValue("42")))
+///   matches the implicit instantiation of C in C<42>.
+AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
+              std::string, Value) {
+  if (Node.getKind() != TemplateArgument::Integral)
+    return false;
+  return Node.getAsIntegral().toString(10) == Value;
+}
+
+/// \brief Matches any value declaration.
+///
+/// Example matches A, B, C and F
+/// \code
+///   enum X { A, B, C };
+///   void F();
+/// \endcode
+const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
+
 /// \brief Matches C++ constructor declarations.
 ///
 /// Example matches Foo::Foo() and Foo::Foo(int)
@@ -1414,21 +1604,21 @@
 ///
 /// Usable as: Any Matcher
 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
-  internal::EachOfVariadicOperator
+  internal::DynTypedMatcher::VO_EachOf
 };
 
 /// \brief Matches if any of the given matchers matches.
 ///
 /// Usable as: Any Matcher
 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
-  internal::AnyOfVariadicOperator
+  internal::DynTypedMatcher::VO_AnyOf
 };
 
 /// \brief Matches if all given matchers match.
 ///
 /// Usable as: Any Matcher
 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
-  internal::AllOfVariadicOperator
+  internal::DynTypedMatcher::VO_AllOf
 };
 
 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
@@ -1502,16 +1692,8 @@
 /// \code
 ///   namespace a { namespace b { class X; } }
 /// \endcode
-AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
-  assert(!Name.empty());
-  const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
-  const StringRef FullName = FullNameString;
-  const StringRef Pattern = Name;
-  if (Pattern.startswith("::")) {
-    return FullName == Pattern;
-  } else {
-    return FullName.endswith(("::" + Pattern).str());
-  }
+inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
+  return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Name));
 }
 
 /// \brief Matches NamedDecl nodes whose fully qualified names contain
@@ -1558,7 +1740,7 @@
 inline internal::PolymorphicMatcherWithParam1<
     internal::HasOverloadedOperatorNameMatcher, StringRef,
     AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, FunctionDecl)>
-hasOverloadedOperatorName(const StringRef Name) {
+hasOverloadedOperatorName(StringRef Name) {
   return internal::PolymorphicMatcherWithParam1<
       internal::HasOverloadedOperatorNameMatcher, StringRef,
       AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, FunctionDecl)>(
@@ -1768,7 +1950,7 @@
 ///
 /// Usable as: Any Matcher
 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
-  internal::NotUnaryOperator
+  internal::DynTypedMatcher::VO_UnaryNot
 };
 
 /// \brief Matches a node if the declaration associated with that node
@@ -1844,7 +2026,7 @@
 /// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
 /// \code
 ///   class Y { public: void x(); };
-///   void z() { Y y; y.x();
+///   void z() { Y y; y.x(); }
 /// \endcode
 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
                        1) {
@@ -1952,6 +2134,7 @@
 ///     void a(X b) {
 ///       X &x = b;
 ///       const X &y = b;
+///     }
 ///   };
 /// \endcode
 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
@@ -2280,11 +2463,10 @@
 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
                                               CallExpr, CXXConstructExpr),
                           internal::Matcher<Expr>, InnerMatcher) {
-  for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
+  for (const Expr *Arg : Node.arguments()) {
     BoundNodesTreeBuilder Result(*Builder);
-    if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder,
-                             &Result)) {
-      *Builder = Result;
+    if (InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, &Result)) {
+      *Builder = std::move(Result);
       return true;
     }
   }
@@ -2372,6 +2554,19 @@
   return Node.isExternC();
 }
 
+/// \brief Matches deleted function declarations.
+///
+/// Given:
+/// \code
+///   void Func();
+///   void DeletedFunc() = delete;
+/// \endcode
+/// functionDecl(isDeleted())
+///   matches the declaration of DeletedFunc, but not Func.
+AST_MATCHER(FunctionDecl, isDeleted) {
+  return Node.isDeleted();
+}
+
 /// \brief Matches the condition expression of an if statement, for loop,
 /// or conditional operator.
 ///
@@ -2953,6 +3148,46 @@
           TSK_ExplicitInstantiationDefinition);
 }
 
+/// \brief Matches declarations that are template instantiations or are inside
+/// template instantiations.
+///
+/// Given
+/// \code
+///   template<typename T> void A(T t) { T i; }
+///   A(0);
+///   A(0U);
+/// \endcode
+/// functionDecl(isInstantiated())
+///   matches 'A(int) {...};' and 'A(unsigned) {...}'.
+AST_MATCHER(Decl, isInstantiated) {
+  auto IsInstantiation = decl(anyOf(recordDecl(isTemplateInstantiation()),
+                                    functionDecl(isTemplateInstantiation())));
+  auto InnerMatcher =
+      decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
+  return InnerMatcher.matches(Node, Finder, Builder);
+}
+
+/// \brief Matches statements inside of a template instantiation.
+///
+/// Given
+/// \code
+///   int j;
+///   template<typename T> void A(T t) { T i; j += 42;}
+///   A(0);
+///   A(0U);
+/// \endcode
+/// 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.
+AST_MATCHER(Stmt, isInTemplateInstantiation) {
+  auto InnerMatcher =
+      stmt(hasAncestor(decl(anyOf(recordDecl(isTemplateInstantiation()),
+                                  functionDecl(isTemplateInstantiation())))));
+  return InnerMatcher.matches(Node, Finder, Builder);
+}
+
 /// \brief Matches explicit template specializations of function, class, or
 /// static member variable template instantiations.
 ///
@@ -3094,6 +3329,7 @@
 ///     int a[] = { 2, 3 }
 ///     int b[42];
 ///     int c[a[0]];
+///   }
 /// \endcode
 /// variableArrayType()
 ///   matches "int c[a[0]]"
@@ -3432,8 +3668,9 @@
 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
 /// declaration of \c class \c D.
 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
-  return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
-                              Finder, Builder);
+  const DeclContext *DC = Node.getDeclContext();
+  if (!DC) return false;
+  return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
 }
 
 /// \brief Matches nested name specifiers.
@@ -3599,7 +3836,7 @@
       Result.addMatch(CaseBuilder);
     }
   }
-  *Builder = Result;
+  *Builder = std::move(Result);
   return Matched;
 }
 
@@ -3622,7 +3859,7 @@
       Result.addMatch(InitBuilder);
     }
   }
-  *Builder = Result;
+  *Builder = std::move(Result);
   return Matched;
 }
 
@@ -3643,7 +3880,32 @@
   return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
 }
 
+/// \brief Matches declaration that has a given attribute.
+///
+/// Given
+/// \code
+///   __attribute__((device)) void f() { ... }
+/// \endcode
+/// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
+/// f.
+AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
+  for (const auto *Attr : Node.attrs()) {
+    if (Attr->getKind() == AttrKind)
+      return true;
+  }
+  return false;
+}
+
+/// \brief Matches CUDA kernel call expression.
+///
+/// Example matches,
+/// \code
+///   kernel<<<i,j>>>();
+/// \endcode
+const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
+    CUDAKernelCallExpr;
+
 } // end namespace ast_matchers
 } // end namespace clang
 
-#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
+#endif
diff --git a/include/clang/ASTMatchers/ASTMatchersInternal.h b/include/clang/ASTMatchers/ASTMatchersInternal.h
index 94435fd..3aecf4b 100644
--- a/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ b/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -32,8 +32,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
-#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
+#ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H
+#define LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H
 
 #include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/Decl.h"
@@ -61,9 +61,8 @@
   /// \brief Adds \c Node to the map with key \c ID.
   ///
   /// The node's base type should be in NodeBaseType or it will be unaccessible.
-  template <typename T>
-  void addNode(StringRef ID, const T* Node) {
-    NodeMap[ID] = ast_type_traits::DynTypedNode::create(*Node);
+  void addNode(StringRef ID, const ast_type_traits::DynTypedNode& DynNode) {
+    NodeMap[ID] = DynNode;
   }
 
   /// \brief Returns the AST node bound to \c ID.
@@ -103,6 +102,16 @@
     return NodeMap;
   }
 
+  /// \brief Returns \c true if this \c BoundNodesMap can be compared, i.e. all
+  /// stored nodes have memoization data.
+  bool isComparable() const {
+    for (const auto &IDAndNode : NodeMap) {
+      if (!IDAndNode.second.getMemoizationData())
+        return false;
+    }
+    return true;
+  }
+
 private:
   IDToNodeMap NodeMap;
 };
@@ -126,11 +135,12 @@
   };
 
   /// \brief Add a binding from an id to a node.
-  template <typename T> void setBinding(const std::string &Id, const T *Node) {
+  void setBinding(const std::string &Id,
+                  const ast_type_traits::DynTypedNode &DynNode) {
     if (Bindings.empty())
       Bindings.push_back(BoundNodesMap());
-    for (unsigned i = 0, e = Bindings.size(); i != e; ++i)
-      Bindings[i].addNode(Id, Node);
+    for (BoundNodesMap &Binding : Bindings)
+      Binding.addNode(Id, DynNode);
   }
 
   /// \brief Adds a branch in the tree.
@@ -153,12 +163,38 @@
     return Bindings < Other.Bindings;
   }
 
+  /// \brief Returns \c true if this \c BoundNodesTreeBuilder can be compared,
+  /// i.e. all stored node maps have memoization data.
+  bool isComparable() const {
+    for (const BoundNodesMap &NodesMap : Bindings) {
+      if (!NodesMap.isComparable())
+        return false;
+    }
+    return true;
+  }
+
 private:
   SmallVector<BoundNodesMap, 16> Bindings;
 };
 
 class ASTMatchFinder;
 
+/// \brief Generic interface for all matchers.
+///
+/// Used by the implementation of Matcher<T> and DynTypedMatcher.
+/// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T>
+/// instead.
+class DynMatcherInterface : public RefCountedBaseVPTR {
+public:
+  /// \brief Returns true if \p DynNode can be matched.
+  ///
+  /// May bind \p DynNode to an ID via \p Builder, or recurse into
+  /// the AST via \p Finder.
+  virtual bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
+                          ASTMatchFinder *Finder,
+                          BoundNodesTreeBuilder *Builder) const = 0;
+};
+
 /// \brief Generic interface for matchers on an AST node of type T.
 ///
 /// Implement this if your matcher may need to inspect the children or
@@ -167,7 +203,7 @@
 /// current node and doesn't care about its children or descendants,
 /// implement SingleNodeMatcherInterface instead.
 template <typename T>
-class MatcherInterface : public RefCountedBaseVPTR {
+class MatcherInterface : public DynMatcherInterface {
 public:
   virtual ~MatcherInterface() {}
 
@@ -178,6 +214,15 @@
   virtual bool matches(const T &Node,
                        ASTMatchFinder *Finder,
                        BoundNodesTreeBuilder *Builder) const = 0;
+
+  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;
+  }
 };
 
 /// \brief Interface for matchers that only evaluate properties on a single
@@ -199,6 +244,145 @@
   }
 };
 
+template <typename> class Matcher;
+
+/// \brief Matcher that works on a \c DynTypedNode.
+///
+/// It is constructed from a \c Matcher<T> object and redirects most calls to
+/// underlying matcher.
+/// It checks whether the \c DynTypedNode is convertible into the type of the
+/// underlying matcher and then do the actual match on the actual node, or
+/// return false if it is not convertible.
+class DynTypedMatcher {
+public:
+  /// \brief Takes ownership of the provided implementation pointer.
+  template <typename T>
+  DynTypedMatcher(MatcherInterface<T> *Implementation)
+      : AllowBind(false),
+        SupportedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()),
+        RestrictKind(SupportedKind), Implementation(Implementation) {}
+
+  /// \brief Construct from a variadic function.
+  enum VariadicOperator {
+    /// \brief Matches nodes for which all provided matchers match.
+    VO_AllOf,
+    /// \brief Matches nodes for which at least one of the provided matchers
+    /// matches.
+    VO_AnyOf,
+    /// \brief Matches nodes for which at least one of the provided matchers
+    /// matches, but doesn't stop at the first match.
+    VO_EachOf,
+    /// \brief Matches nodes that do not match the provided matcher.
+    ///
+    /// Uses the variadic matcher interface, but fails if
+    /// InnerMatchers.size() != 1.
+    VO_UnaryNot
+  };
+  static DynTypedMatcher
+  constructVariadic(VariadicOperator Op,
+                    std::vector<DynTypedMatcher> InnerMatchers);
+
+  /// \brief Get a "true" matcher for \p NodeKind.
+  ///
+  /// It only checks that the node is of the right kind.
+  static DynTypedMatcher trueMatcher(ast_type_traits::ASTNodeKind NodeKind);
+
+  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;
+
+  /// \brief Returns true if the matcher matches the given \c DynNode.
+  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<>.
+  llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const;
+
+  /// \brief Returns a unique \p ID for the matcher.
+  ///
+  /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the
+  /// same \c Implementation pointer, but different \c RestrictKind. We need to
+  /// include both in the ID to make it unique.
+  ///
+  /// \c MatcherIDType supports operator< and provides strict weak ordering.
+  typedef std::pair<ast_type_traits::ASTNodeKind, uint64_t> MatcherIDType;
+  MatcherIDType getID() const {
+    /// FIXME: Document the requirements this imposes on matcher
+    /// implementations (no new() implementation_ during a Matches()).
+    return std::make_pair(RestrictKind,
+                          reinterpret_cast<uint64_t>(Implementation.get()));
+  }
+
+  /// \brief Returns the type this matcher works on.
+  ///
+  /// \c matches() will always return false unless the node passed is of this
+  /// or a derived type.
+  ast_type_traits::ASTNodeKind getSupportedKind() const {
+    return SupportedKind;
+  }
+
+  /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted
+  ///   to a \c Matcher<T>.
+  ///
+  /// This method verifies that the underlying matcher in \c Other can process
+  /// nodes of types T.
+  template <typename T> bool canConvertTo() const {
+    return canConvertTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
+  }
+  bool canConvertTo(ast_type_traits::ASTNodeKind To) const;
+
+  /// \brief Construct a \c Matcher<T> interface around the dynamic matcher.
+  ///
+  /// This method asserts that \c canConvertTo() is \c true. Callers
+  /// should call \c canConvertTo() first to make sure that \c this is
+  /// compatible with T.
+  template <typename T> Matcher<T> convertTo() const {
+    assert(canConvertTo<T>());
+    return unconditionalConvertTo<T>();
+  }
+
+  /// \brief Same as \c convertTo(), but does not check that the underlying
+  ///   matcher can handle a value of T.
+  ///
+  /// If it is not compatible, then this matcher will never match anything.
+  template <typename T> Matcher<T> unconditionalConvertTo() const;
+
+private:
+ DynTypedMatcher(ast_type_traits::ASTNodeKind SupportedKind,
+                 ast_type_traits::ASTNodeKind RestrictKind,
+                 IntrusiveRefCntPtr<DynMatcherInterface> Implementation)
+     : AllowBind(false),
+       SupportedKind(SupportedKind),
+       RestrictKind(RestrictKind),
+       Implementation(std::move(Implementation)) {}
+
+  bool AllowBind;
+  ast_type_traits::ASTNodeKind SupportedKind;
+  /// \brief A potentially stricter node kind.
+  ///
+  /// It allows to perform implicit and dynamic cast of matchers without
+  /// needing to change \c Implementation.
+  ast_type_traits::ASTNodeKind RestrictKind;
+  IntrusiveRefCntPtr<DynMatcherInterface> Implementation;
+};
+
 /// \brief Wrapper of a MatcherInterface<T> *that allows copying.
 ///
 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
@@ -221,7 +405,10 @@
   Matcher(const Matcher<From> &Other,
           typename std::enable_if<std::is_base_of<From, T>::value &&
                                   !std::is_same<From, T>::value>::type * = 0)
-      : Implementation(new ImplicitCastMatcher<From>(Other)) {}
+      : Implementation(restrictMatcher(Other.Implementation)) {
+    assert(Implementation.getSupportedKind().isSame(
+        ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
+  }
 
   /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
   ///
@@ -233,26 +420,34 @@
             std::is_same<TypeT, Type>::value>::type* = 0)
       : Implementation(new TypeToQualType<TypeT>(Other)) {}
 
+  /// \brief Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the
+  /// argument.
+  /// \c To must be a base class of \c T.
+  template <typename To>
+  Matcher<To> dynCastTo() const {
+    static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
+    return Matcher<To>(Implementation);
+  }
+
   /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
   bool matches(const T &Node,
                ASTMatchFinder *Finder,
                BoundNodesTreeBuilder *Builder) const {
-    if (Implementation->matches(Node, 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 = BoundNodesTreeBuilder();
-    return false;
+    return Implementation.matches(ast_type_traits::DynTypedNode::create(Node),
+                                  Finder, Builder);
   }
 
   /// \brief Returns an ID that uniquely identifies the matcher.
-  uint64_t getID() const {
-    /// FIXME: Document the requirements this imposes on matcher
-    /// implementations (no new() implementation_ during a Matches()).
-    return reinterpret_cast<uint64_t>(Implementation.get());
+  DynTypedMatcher::MatcherIDType getID() const {
+    return Implementation.getID();
   }
 
+  /// \brief Extract the dynamic matcher.
+  ///
+  /// The returned matcher keeps the same restrictions as \c this and remembers
+  /// that it is meant to support nodes of type \c T.
+  operator DynTypedMatcher() const { return Implementation; }
+
   /// \brief Allows the conversion of a \c Matcher<Type> to a \c
   /// Matcher<QualType>.
   ///
@@ -276,24 +471,22 @@
   };
 
 private:
-  /// \brief Allows conversion from Matcher<Base> to Matcher<T> if T
-  /// is derived from Base.
-  template <typename Base>
-  class ImplicitCastMatcher : public MatcherInterface<T> {
-  public:
-    explicit ImplicitCastMatcher(const Matcher<Base> &From)
-        : From(From) {}
+  // For Matcher<T> <=> Matcher<U> conversions.
+  template <typename U> friend class Matcher;
+  // For DynTypedMatcher::unconditionalConvertTo<T>.
+  friend class DynTypedMatcher;
 
-    bool matches(const T &Node, ASTMatchFinder *Finder,
-                 BoundNodesTreeBuilder *Builder) const override {
-      return From.matches(Node, Finder, Builder);
-    }
+  static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
+    return Other.dynCastTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
+  }
 
-  private:
-    const Matcher<Base> From;
-  };
+  explicit Matcher(const DynTypedMatcher &Implementation)
+      : Implementation(restrictMatcher(Implementation)) {
+    assert(this->Implementation.getSupportedKind()
+               .isSame(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
+  }
 
-  IntrusiveRefCntPtr< MatcherInterface<T> > Implementation;
+  DynTypedMatcher Implementation;
 };  // class Matcher
 
 /// \brief A convenient helper for creating a Matcher<T> without specifying
@@ -303,153 +496,10 @@
   return Matcher<T>(Implementation);
 }
 
-template <typename T> class BindableMatcher;
-
-/// \brief Matcher that works on a \c DynTypedNode.
-///
-/// It is constructed from a \c Matcher<T> object and redirects most calls to
-/// underlying matcher.
-/// It checks whether the \c DynTypedNode is convertible into the type of the
-/// underlying matcher and then do the actual match on the actual node, or
-/// return false if it is not convertible.
-class DynTypedMatcher {
-public:
-  /// \brief Construct from a \c Matcher<T>. Copies the matcher.
-  template <typename T> inline DynTypedMatcher(const Matcher<T> &M);
-
-  /// \brief Construct from a bindable \c Matcher<T>. Copies the matcher.
-  ///
-  /// This version enables \c tryBind() on the \c DynTypedMatcher.
-  template <typename T> inline DynTypedMatcher(const BindableMatcher<T> &M);
-
-  /// \brief Returns true if the matcher matches the given \c DynNode.
-  bool matches(const ast_type_traits::DynTypedNode DynNode,
-               ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const {
-    return Storage->matches(DynNode, Finder, Builder);
-  }
-
-  /// \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<>.
-  llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const {
-    return Storage->tryBind(ID);
-  }
-
-  /// \brief Returns a unique \p ID for the matcher.
-  uint64_t getID() const { return Storage->getID(); }
-
-  /// \brief Returns the type this matcher works on.
-  ///
-  /// \c matches() will always return false unless the node passed is of this
-  /// or a derived type.
-  ast_type_traits::ASTNodeKind getSupportedKind() const {
-    return Storage->getSupportedKind();
-  }
-
-  /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted
-  ///   to a \c Matcher<T>.
-  ///
-  /// This method verifies that the underlying matcher in \c Other can process
-  /// nodes of types T.
-  template <typename T> bool canConvertTo() const {
-    return getSupportedKind().isBaseOf(
-        ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
-  }
-
-  /// \brief Construct a \c Matcher<T> interface around the dynamic matcher.
-  ///
-  /// This method asserts that \c canConvertTo() is \c true. Callers
-  /// should call \c canConvertTo() first to make sure that \c this is
-  /// compatible with T.
-  template <typename T> Matcher<T> convertTo() const {
-    assert(canConvertTo<T>());
-    return unconditionalConvertTo<T>();
-  }
-
-  /// \brief Same as \c convertTo(), but does not check that the underlying
-  ///   matcher can handle a value of T.
-  ///
-  /// If it is not compatible, then this matcher will never match anything.
-  template <typename T> Matcher<T> unconditionalConvertTo() const;
-
-private:
-  class MatcherStorage : public RefCountedBaseVPTR {
-  public:
-    MatcherStorage(ast_type_traits::ASTNodeKind SupportedKind, uint64_t ID)
-        : SupportedKind(SupportedKind), ID(ID) {}
-    virtual ~MatcherStorage();
-
-    virtual bool matches(const ast_type_traits::DynTypedNode DynNode,
-                         ASTMatchFinder *Finder,
-                         BoundNodesTreeBuilder *Builder) const = 0;
-
-    virtual llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const = 0;
-
-    ast_type_traits::ASTNodeKind getSupportedKind() const {
-      return SupportedKind;
-    }
-
-    uint64_t getID() const { return ID; }
-
-  private:
-    const ast_type_traits::ASTNodeKind SupportedKind;
-    const uint64_t ID;
-  };
-
-  /// \brief Typed implementation of \c MatcherStorage.
-  template <typename T> class TypedMatcherStorage;
-
-  IntrusiveRefCntPtr<const MatcherStorage> Storage;
-};
-
-template <typename T>
-class DynTypedMatcher::TypedMatcherStorage : public MatcherStorage {
-public:
-  TypedMatcherStorage(const Matcher<T> &Other, bool AllowBind)
-      : MatcherStorage(ast_type_traits::ASTNodeKind::getFromNodeKind<T>(),
-                       Other.getID()),
-        InnerMatcher(Other), AllowBind(AllowBind) {}
-
-  bool matches(const ast_type_traits::DynTypedNode DynNode,
-               ASTMatchFinder *Finder,
-               BoundNodesTreeBuilder *Builder) const override {
-    if (const T *Node = DynNode.get<T>()) {
-      return InnerMatcher.matches(*Node, Finder, Builder);
-    }
-    return false;
-  }
-
-  llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const override {
-    if (!AllowBind)
-      return llvm::Optional<DynTypedMatcher>();
-    return DynTypedMatcher(BindableMatcher<T>(InnerMatcher).bind(ID));
-  }
-
-private:
-  const Matcher<T> InnerMatcher;
-  const bool AllowBind;
-};
-
-template <typename T>
-inline DynTypedMatcher::DynTypedMatcher(const Matcher<T> &M)
-    : Storage(new TypedMatcherStorage<T>(M, false)) {}
-
-template <typename T>
-inline DynTypedMatcher::DynTypedMatcher(const BindableMatcher<T> &M)
-    : Storage(new TypedMatcherStorage<T>(M, true)) {}
-
 /// \brief Specialization of the conversion functions for QualType.
 ///
-/// These specializations provide the Matcher<Type>->Matcher<QualType>
+/// This specialization provides the Matcher<Type>->Matcher<QualType>
 /// conversion that the static API does.
-template <> inline bool DynTypedMatcher::canConvertTo<QualType>() const {
-  const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind();
-  return SourceKind.isSame(
-             ast_type_traits::ASTNodeKind::getFromNodeKind<Type>()) ||
-         SourceKind.isSame(
-             ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>());
-}
-
 template <>
 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
   assert(canConvertTo<QualType>());
@@ -470,7 +520,7 @@
   for (IteratorT I = Start; I != End; ++I) {
     BoundNodesTreeBuilder Result(*Builder);
     if (Matcher.matches(*I, Finder, &Result)) {
-      *Builder = Result;
+      *Builder = std::move(Result);
       return true;
     }
   }
@@ -486,7 +536,7 @@
   for (IteratorT I = Start; I != End; ++I) {
     BoundNodesTreeBuilder Result(*Builder);
     if (Matcher.matches(**I, Finder, &Result)) {
-      *Builder = Result;
+      *Builder = std::move(Result);
       return true;
     }
   }
@@ -549,6 +599,33 @@
   std::string Name;
 };
 
+/// \brief Matches named declarations with a specific name.
+///
+/// See \c hasName() in ASTMatchers.h for details.
+class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
+ public:
+  explicit HasNameMatcher(StringRef Name);
+
+  bool matchesNode(const NamedDecl &Node) const override;
+
+ private:
+  /// \brief Unqualified match routine.
+  ///
+  /// It is much faster than the full match, but it only works for unqualified
+  /// matches.
+  bool matchesNodeUnqualified(const NamedDecl &Node) const;
+
+  /// \brief Full match routine
+  ///
+  /// It generates the fully qualified name of the declaration (which is
+  /// expensive) before trying to match.
+  /// It is slower but simple and works on all cases.
+  bool matchesNodeFull(const NamedDecl &Node) const;
+
+  const bool UseUnqualifiedMatch;
+  const std::string Name;
+};
+
 /// \brief Matches declarations for QualType and CallExpr.
 ///
 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
@@ -973,48 +1050,18 @@
 ///
 /// This is useful when a matcher syntactically requires a child matcher,
 /// but the context doesn't care. See for example: anything().
-///
-/// FIXME: Alternatively we could also create a IsAMatcher or something
-/// that checks that a dyn_cast is possible. This is purely needed for the
-/// difference between calling for example:
-///   record()
-/// and
-///   record(SomeMatcher)
-/// In the second case we need the correct type we were dyn_cast'ed to in order
-/// to get the right type for the inner matcher. In the first case we don't need
-/// that, but we use the type conversion anyway and insert a TrueMatcher.
-template <typename T>
-class TrueMatcher : public SingleNodeMatcherInterface<T>  {
-public:
-  bool matchesNode(const T &Node) const override {
-    return true;
+class TrueMatcher {
+ public:
+  typedef AllNodeBaseTypes ReturnTypes;
+
+  template <typename T>
+  operator Matcher<T>() const {
+    return DynTypedMatcher::trueMatcher(
+               ast_type_traits::ASTNodeKind::getFromNodeKind<T>())
+        .template unconditionalConvertTo<T>();
   }
 };
 
-/// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node
-/// to an ID if the inner matcher matches on the node.
-template <typename T>
-class IdMatcher : public MatcherInterface<T> {
-public:
-  /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches
-  /// the node.
-  IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher)
-      : ID(ID), InnerMatcher(InnerMatcher) {}
-
-  bool matches(const T &Node, ASTMatchFinder *Finder,
-               BoundNodesTreeBuilder *Builder) const override {
-    bool Result = InnerMatcher.matches(Node, Finder, Builder);
-    if (Result) {
-      Builder->setBinding(ID, &Node);
-    }
-    return Result;
-  }
-
-private:
-  const std::string ID;
-  const Matcher<T> InnerMatcher;
-};
-
 /// \brief A Matcher that allows binding the node it matches to an id.
 ///
 /// BindableMatcher provides a \a bind() method that allows binding the
@@ -1031,7 +1078,17 @@
   /// The returned matcher is equivalent to this matcher, but will
   /// bind the matched node on a match.
   Matcher<T> bind(StringRef ID) const {
-    return Matcher<T>(new IdMatcher<T>(ID, *this));
+    return DynTypedMatcher(*this)
+        .tryBind(ID)
+        ->template unconditionalConvertTo<T>();
+  }
+
+  /// \brief Same as Matcher<T>'s conversion operator, but enables binding on
+  /// the returned matcher.
+  operator DynTypedMatcher() const {
+    DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
+    Result.setAllowBind(true);
+    return Result;
   }
 };
 
@@ -1089,36 +1146,11 @@
 /// \brief VariadicOperatorMatcher related types.
 /// @{
 
-/// \brief Function signature for any variadic operator. It takes the inner
-///   matchers as an array of DynTypedMatcher.
-typedef bool (*VariadicOperatorFunction)(
-    const ast_type_traits::DynTypedNode DynNode, ASTMatchFinder *Finder,
-    BoundNodesTreeBuilder *Builder, ArrayRef<DynTypedMatcher> InnerMatchers);
-
-/// \brief \c MatcherInterface<T> implementation for an variadic operator.
-template <typename T>
-class VariadicOperatorMatcherInterface : public MatcherInterface<T> {
-public:
-  VariadicOperatorMatcherInterface(VariadicOperatorFunction Func,
-                                   std::vector<DynTypedMatcher> InnerMatchers)
-      : Func(Func), InnerMatchers(std::move(InnerMatchers)) {}
-
-  bool matches(const T &Node, ASTMatchFinder *Finder,
-               BoundNodesTreeBuilder *Builder) const override {
-    return Func(ast_type_traits::DynTypedNode::create(Node), Finder, Builder,
-                InnerMatchers);
-  }
-
-private:
-  const VariadicOperatorFunction Func;
-  const std::vector<DynTypedMatcher> InnerMatchers;
-};
-
 /// \brief "No argument" placeholder to use as template paratemers.
 struct VariadicOperatorNoArg {};
 
-/// \brief Polymorphic matcher object that uses a \c VariadicOperatorFunction
-///   operator.
+/// \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
@@ -1133,7 +1165,8 @@
           typename P9 = VariadicOperatorNoArg>
 class VariadicOperatorMatcher {
 public:
-  VariadicOperatorMatcher(VariadicOperatorFunction Func, const P1 &Param1,
+  VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op,
+                          const P1 &Param1,
                           const P2 &Param2 = VariadicOperatorNoArg(),
                           const P3 &Param3 = VariadicOperatorNoArg(),
                           const P4 &Param4 = VariadicOperatorNoArg(),
@@ -1142,7 +1175,7 @@
                           const P7 &Param7 = VariadicOperatorNoArg(),
                           const P8 &Param8 = VariadicOperatorNoArg(),
                           const P9 &Param9 = VariadicOperatorNoArg())
-      : Func(Func), Param1(Param1), Param2(Param2), Param3(Param3),
+      : Op(Op), Param1(Param1), Param2(Param2), Param3(Param3),
         Param4(Param4), Param5(Param5), Param6(Param6), Param7(Param7),
         Param8(Param8), Param9(Param9) {}
 
@@ -1157,8 +1190,8 @@
     addMatcher<T>(Param7, Matchers);
     addMatcher<T>(Param8, Matchers);
     addMatcher<T>(Param9, Matchers);
-    return Matcher<T>(
-        new VariadicOperatorMatcherInterface<T>(Func, std::move(Matchers)));
+    return DynTypedMatcher::constructVariadic(Op, std::move(Matchers))
+        .template unconditionalConvertTo<T>();
   }
 
 private:
@@ -1173,7 +1206,7 @@
   static void addMatcher(VariadicOperatorNoArg,
                          std::vector<DynTypedMatcher> &Matchers) {}
 
-  const VariadicOperatorFunction Func;
+  const DynTypedMatcher::VariadicOperator Op;
   const P1 Param1;
   const P2 Param2;
   const P3 Param3;
@@ -1191,7 +1224,7 @@
 /// It supports 1-9 argument overloaded operator(). More can be added if needed.
 template <unsigned MinCount, unsigned MaxCount>
 struct VariadicOperatorMatcherFunc {
-  VariadicOperatorFunction Func;
+  DynTypedMatcher::VariadicOperator Op;
 
   template <unsigned Count, typename T>
   struct EnableIfValidArity
@@ -1200,30 +1233,29 @@
   template <typename M1>
   typename EnableIfValidArity<1, VariadicOperatorMatcher<M1> >::type
   operator()(const M1 &P1) const {
-    return VariadicOperatorMatcher<M1>(Func, P1);
+    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>(Func, P1, P2);
+    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>(Func, P1, P2, P3);
+    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>(Func, P1, P2, P3, P4);
+    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>(Func, P1, P2, P3, P4,
-                                                       P5);
+    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>
@@ -1232,7 +1264,7 @@
   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>(
-        Func, P1, P2, P3, P4, P5, P6);
+        Op, P1, P2, P3, P4, P5, P6);
   }
   template <typename M1, typename M2, typename M3, typename M4, typename M5,
             typename M6, typename M7>
@@ -1241,7 +1273,7 @@
   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>(
-        Func, P1, P2, P3, P4, P5, P6, P7);
+        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>
@@ -1250,7 +1282,7 @@
   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>(
-        Func, P1, P2, P3, P4, P5, P6, P7, P8);
+        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>
@@ -1260,55 +1292,40 @@
              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>(
-        Func, P1, P2, P3, P4, P5, P6, P7, P8, P9);
+        Op, P1, P2, P3, P4, P5, P6, P7, P8, P9);
   }
 };
 
 /// @}
 
-/// \brief Matches nodes that do not match the provided matcher.
-///
-/// Uses the variadic matcher interface, but fails if InnerMatchers.size()!=1.
-bool NotUnaryOperator(const ast_type_traits::DynTypedNode DynNode,
-                      ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
-                      ArrayRef<DynTypedMatcher> InnerMatchers);
-
-/// \brief Matches nodes for which all provided matchers match.
-bool AllOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode,
-                           ASTMatchFinder *Finder,
-                           BoundNodesTreeBuilder *Builder,
-                           ArrayRef<DynTypedMatcher> InnerMatchers);
-
-/// \brief Matches nodes for which at least one of the provided matchers
-/// matches, but doesn't stop at the first match.
-bool EachOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode,
-                            ASTMatchFinder *Finder,
-                            BoundNodesTreeBuilder *Builder,
-                            ArrayRef<DynTypedMatcher> InnerMatchers);
-
-/// \brief Matches nodes for which at least one of the provided matchers
-/// matches.
-bool AnyOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode,
-                           ASTMatchFinder *Finder,
-                           BoundNodesTreeBuilder *Builder,
-                           ArrayRef<DynTypedMatcher> InnerMatchers);
-
 template <typename T>
 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
-  return Matcher<T>(new VariadicOperatorMatcherInterface<T>(
-      AllOfVariadicOperator, llvm::makeArrayRef(*this)));
+  return Matcher<T>(*this);
 }
 
 /// \brief Creates a Matcher<T> that matches if all inner matchers match.
 template<typename T>
 BindableMatcher<T> makeAllOfComposite(
     ArrayRef<const Matcher<T> *> InnerMatchers) {
-  std::vector<DynTypedMatcher> DynMatchers;
-  for (size_t i = 0, e = InnerMatchers.size(); i != e; ++i) {
-    DynMatchers.push_back(*InnerMatchers[i]);
+  // For the size() == 0 case, we return a "true" matcher.
+  if (InnerMatchers.size() == 0) {
+    return BindableMatcher<T>(TrueMatcher());
   }
-  return BindableMatcher<T>(new VariadicOperatorMatcherInterface<T>(
-      AllOfVariadicOperator, std::move(DynMatchers)));
+  // For the size() == 1 case, we simply return that one matcher.
+  // No need to wrap it in a variadic operation.
+  if (InnerMatchers.size() == 1) {
+    return BindableMatcher<T>(*InnerMatchers[0]);
+  }
+
+  std::vector<DynTypedMatcher> DynMatchers;
+  DynMatchers.reserve(InnerMatchers.size());
+  for (const auto *InnerMatcher : InnerMatchers) {
+    DynMatchers.push_back(*InnerMatcher);
+  }
+  return BindableMatcher<T>(
+      DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf,
+                                         std::move(DynMatchers))
+          .template unconditionalConvertTo<T>());
 }
 
 /// \brief Creates a Matcher<T> that matches if
@@ -1320,8 +1337,8 @@
 template<typename T, typename InnerT>
 BindableMatcher<T> makeDynCastAllOfComposite(
     ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
-  return BindableMatcher<T>(DynTypedMatcher(makeAllOfComposite(InnerMatchers))
-                                .unconditionalConvertTo<T>());
+  return BindableMatcher<T>(
+      makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
 }
 
 /// \brief Matches nodes of type T that have at least one descendant node of
@@ -1627,7 +1644,7 @@
 
 inline ArrayRef<TemplateArgument>
 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
-  return ArrayRef<TemplateArgument>(T.getArgs(), T.getNumArgs());
+  return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
 }
 
 struct NotEqualsBoundNodePredicate {
@@ -1642,4 +1659,4 @@
 } // end namespace ast_matchers
 } // end namespace clang
 
-#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
+#endif
diff --git a/include/clang/ASTMatchers/ASTMatchersMacros.h b/include/clang/ASTMatchers/ASTMatchersMacros.h
index 563372a..4d57b94 100644
--- a/include/clang/ASTMatchers/ASTMatchersMacros.h
+++ b/include/clang/ASTMatchers/ASTMatchersMacros.h
@@ -34,8 +34,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_MACROS_H
-#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_MACROS_H
+#ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERSMACROS_H
+#define LLVM_CLANG_ASTMATCHERS_ASTMATCHERSMACROS_H
 
 /// \brief AST_MATCHER_FUNCTION_P(ReturnType, DefineMatcher, ParamType, Param) {
 /// defines a single-parameter function named DefineMatcher() that returns a
@@ -352,4 +352,4 @@
       internal::TypeLocTraverseMatcher, ReturnTypesF>::Func MatcherName##Loc;  \
   AST_TYPE_TRAVERSE_MATCHER(MatcherName, FunctionName##Type, ReturnTypesF)
 
-#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_MACROS_H
+#endif
diff --git a/include/clang/ASTMatchers/Dynamic/Diagnostics.h b/include/clang/ASTMatchers/Dynamic/Diagnostics.h
index 82a14f1..ef93ac5 100644
--- a/include/clang/ASTMatchers/Dynamic/Diagnostics.h
+++ b/include/clang/ASTMatchers/Dynamic/Diagnostics.h
@@ -12,8 +12,8 @@
 ///
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_MATCHERS_DYNAMIC_DIAGNOSTICS_H
-#define LLVM_CLANG_AST_MATCHERS_DYNAMIC_DIAGNOSTICS_H
+#ifndef LLVM_CLANG_ASTMATCHERS_DYNAMIC_DIAGNOSTICS_H
+#define LLVM_CLANG_ASTMATCHERS_DYNAMIC_DIAGNOSTICS_H
 
 #include "clang/ASTMatchers/Dynamic/VariantValue.h"
 #include "clang/Basic/LLVM.h"
diff --git a/include/clang/ASTMatchers/Dynamic/Parser.h b/include/clang/ASTMatchers/Dynamic/Parser.h
index 4045f57..bd006b6 100644
--- a/include/clang/ASTMatchers/Dynamic/Parser.h
+++ b/include/clang/ASTMatchers/Dynamic/Parser.h
@@ -31,8 +31,8 @@
 ///
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_MATCHERS_DYNAMIC_PARSER_H
-#define LLVM_CLANG_AST_MATCHERS_DYNAMIC_PARSER_H
+#ifndef LLVM_CLANG_ASTMATCHERS_DYNAMIC_PARSER_H
+#define LLVM_CLANG_ASTMATCHERS_DYNAMIC_PARSER_H
 
 #include "clang/ASTMatchers/Dynamic/Diagnostics.h"
 #include "clang/ASTMatchers/Dynamic/Registry.h"
@@ -63,17 +63,6 @@
   public:
     virtual ~Sema();
 
-    /// \brief Lookup a value by name.
-    ///
-    /// This can be used in the Sema layer to declare known constants or to
-    /// allow to split an expression in pieces.
-    ///
-    /// \param Name The name of the value to lookup.
-    ///
-    /// \return The named value. It could be any type that VariantValue
-    ///   supports. An empty value means that the name is not recognized.
-    virtual VariantValue getNamedValue(StringRef Name);
-
     /// \brief Process a matcher expression.
     ///
     /// All the arguments passed here have already been processed.
@@ -105,6 +94,29 @@
     /// found.
     virtual llvm::Optional<MatcherCtor>
     lookupMatcherCtor(StringRef MatcherName) = 0;
+
+    /// \brief Compute the list of completion types for \p Context.
+    ///
+    /// Each element of \p Context represents a matcher invocation, going from
+    /// outermost to innermost. Elements are pairs consisting of a reference to
+    /// the matcher constructor and the index of the next element in the
+    /// argument list of that matcher (or for the last element, the index of
+    /// the completion point in the argument list). An empty list requests
+    /// completion for the root matcher.
+    virtual std::vector<ArgKind> getAcceptedCompletionTypes(
+        llvm::ArrayRef<std::pair<MatcherCtor, unsigned>> Context);
+
+    /// \brief Compute the list of completions that match any of
+    /// \p AcceptedTypes.
+    ///
+    /// \param AcceptedTypes All types accepted for this completion.
+    ///
+    /// \return All completions for the specified types.
+    /// Completions should be valid when used in \c lookupMatcherCtor().
+    /// The matcher constructed from the return of \c lookupMatcherCtor()
+    /// should be convertible to some type in \p AcceptedTypes.
+    virtual std::vector<MatcherCompletion>
+    getMatcherCompletions(llvm::ArrayRef<ArgKind> AcceptedTypes);
   };
 
   /// \brief Sema implementation that uses the matcher registry to process the
@@ -121,58 +133,91 @@
                                           StringRef BindID,
                                           ArrayRef<ParserValue> Args,
                                           Diagnostics *Error) override;
+
+    std::vector<ArgKind> getAcceptedCompletionTypes(
+        llvm::ArrayRef<std::pair<MatcherCtor, unsigned>> Context) override;
+
+    std::vector<MatcherCompletion>
+    getMatcherCompletions(llvm::ArrayRef<ArgKind> AcceptedTypes) override;
   };
 
-  /// \brief Parse a matcher expression, creating matchers from the registry.
-  ///
-  /// This overload creates matchers calling directly into the registry. If the
-  /// caller needs more control over how the matchers are created, then it can
-  /// use the overload below that takes a Sema.
-  ///
-  /// \param MatcherCode The matcher expression to parse.
-  ///
-  /// \return The matcher object constructed, or an empty Optional if an error
-  ///   occurred.
-  ///   In that case, \c Error will contain a description of the error.
-  ///   The caller takes ownership of the DynTypedMatcher object returned.
-  static llvm::Optional<DynTypedMatcher>
-  parseMatcherExpression(StringRef MatcherCode, Diagnostics *Error);
+  typedef llvm::StringMap<VariantValue> NamedValueMap;
 
   /// \brief Parse a matcher expression.
   ///
   /// \param MatcherCode The matcher expression to parse.
   ///
   /// \param S The Sema instance that will help the parser
-  ///   construct the matchers.
+  ///   construct the matchers. If null, it uses the default registry.
+  ///
+  /// \param NamedValues A map of precomputed named values.  This provides
+  ///   the dictionary for the <NamedValue> rule of the grammar.
+  ///   If null, it is ignored.
+  ///
   /// \return The matcher object constructed by the processor, or an empty
   ///   Optional if an error occurred. In that case, \c Error will contain a
   ///   description of the error.
   ///   The caller takes ownership of the DynTypedMatcher object returned.
   static llvm::Optional<DynTypedMatcher>
-  parseMatcherExpression(StringRef MatcherCode, Sema *S, Diagnostics *Error);
-
-  /// \brief Parse an expression, creating matchers from the registry.
-  ///
-  /// Parses any expression supported by this parser. In general, the
-  /// \c parseMatcherExpression function is a better approach to get a matcher
-  /// object.
-  static bool parseExpression(StringRef Code, VariantValue *Value,
-                              Diagnostics *Error);
+  parseMatcherExpression(StringRef MatcherCode, Sema *S,
+                         const NamedValueMap *NamedValues,
+                         Diagnostics *Error);
+  static llvm::Optional<DynTypedMatcher>
+  parseMatcherExpression(StringRef MatcherCode, Sema *S,
+                         Diagnostics *Error) {
+    return parseMatcherExpression(MatcherCode, S, nullptr, Error);
+  }
+  static llvm::Optional<DynTypedMatcher>
+  parseMatcherExpression(StringRef MatcherCode, Diagnostics *Error) {
+    return parseMatcherExpression(MatcherCode, nullptr, Error);
+  }
 
   /// \brief Parse an expression.
   ///
   /// Parses any expression supported by this parser. In general, the
   /// \c parseMatcherExpression function is a better approach to get a matcher
   /// object.
+  ///
+  /// \param S The Sema instance that will help the parser
+  ///   construct the matchers. If null, it uses the default registry.
+  ///
+  /// \param NamedValues A map of precomputed named values.  This provides
+  ///   the dictionary for the <NamedValue> rule of the grammar.
+  ///   If null, it is ignored.
   static bool parseExpression(StringRef Code, Sema *S,
+                              const NamedValueMap *NamedValues,
                               VariantValue *Value, Diagnostics *Error);
+  static bool parseExpression(StringRef Code, Sema *S,
+                              VariantValue *Value, Diagnostics *Error) {
+    return parseExpression(Code, S, nullptr, Value, Error);
+  }
+  static bool parseExpression(StringRef Code, VariantValue *Value,
+                              Diagnostics *Error) {
+    return parseExpression(Code, nullptr, Value, Error);
+  }
 
   /// \brief Complete an expression at the given offset.
   ///
+  /// \param S The Sema instance that will help the parser
+  ///   construct the matchers. If null, it uses the default registry.
+  ///
+  /// \param NamedValues A map of precomputed named values.  This provides
+  ///   the dictionary for the <NamedValue> rule of the grammar.
+  ///   If null, it is ignored.
+  ///
   /// \return The list of completions, which may be empty if there are no
   /// available completions or if an error occurred.
   static std::vector<MatcherCompletion>
-  completeExpression(StringRef Code, unsigned CompletionOffset);
+  completeExpression(StringRef Code, unsigned CompletionOffset, Sema *S,
+                     const NamedValueMap *NamedValues);
+  static std::vector<MatcherCompletion>
+  completeExpression(StringRef Code, unsigned CompletionOffset, Sema *S) {
+    return completeExpression(Code, CompletionOffset, S, nullptr);
+  }
+  static std::vector<MatcherCompletion>
+  completeExpression(StringRef Code, unsigned CompletionOffset) {
+    return completeExpression(Code, CompletionOffset, nullptr);
+  }
 
 private:
   class CodeTokenizer;
@@ -180,6 +225,7 @@
   struct TokenInfo;
 
   Parser(CodeTokenizer *Tokenizer, Sema *S,
+         const NamedValueMap *NamedValues,
          Diagnostics *Error);
 
   bool parseExpressionImpl(VariantValue *Value);
@@ -187,12 +233,16 @@
                                   VariantValue *Value);
   bool parseIdentifierPrefixImpl(VariantValue *Value);
 
-  void addCompletion(const TokenInfo &CompToken, StringRef TypedText,
-                     StringRef Decl);
+  void addCompletion(const TokenInfo &CompToken,
+                     const MatcherCompletion &Completion);
   void addExpressionCompletions();
 
+  std::vector<MatcherCompletion>
+  getNamedValueCompletions(ArrayRef<ArgKind> AcceptedTypes);
+
   CodeTokenizer *const Tokenizer;
   Sema *const S;
+  const NamedValueMap *const NamedValues;
   Diagnostics *const Error;
 
   typedef std::vector<std::pair<MatcherCtor, unsigned> > ContextStackTy;
diff --git a/include/clang/ASTMatchers/Dynamic/Registry.h b/include/clang/ASTMatchers/Dynamic/Registry.h
index faa9254..ad24a8d 100644
--- a/include/clang/ASTMatchers/Dynamic/Registry.h
+++ b/include/clang/ASTMatchers/Dynamic/Registry.h
@@ -14,8 +14,8 @@
 ///
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_MATCHERS_DYNAMIC_REGISTRY_H
-#define LLVM_CLANG_AST_MATCHERS_DYNAMIC_REGISTRY_H
+#ifndef LLVM_CLANG_ASTMATCHERS_DYNAMIC_REGISTRY_H
+#define LLVM_CLANG_ASTMATCHERS_DYNAMIC_REGISTRY_H
 
 #include "clang/ASTMatchers/Dynamic/Diagnostics.h"
 #include "clang/ASTMatchers/Dynamic/VariantValue.h"
@@ -36,8 +36,10 @@
 
 struct MatcherCompletion {
   MatcherCompletion() {}
-  MatcherCompletion(StringRef TypedText, StringRef MatcherDecl)
-      : TypedText(TypedText), MatcherDecl(MatcherDecl) {}
+  MatcherCompletion(StringRef TypedText, StringRef MatcherDecl,
+                    unsigned Specificity)
+      : TypedText(TypedText), MatcherDecl(MatcherDecl),
+        Specificity(Specificity) {}
 
   /// \brief The text to type to select this matcher.
   std::string TypedText;
@@ -45,6 +47,13 @@
   /// \brief The "declaration" of the matcher, with type information.
   std::string MatcherDecl;
 
+  /// \brief Value corresponding to the "specificity" of the converted matcher.
+  ///
+  /// Zero specificity indicates that this conversion would produce a trivial
+  /// matcher that will either always or never match.
+  /// Such matchers are excluded from code completion results.
+  unsigned Specificity;
+
   bool operator==(const MatcherCompletion &Other) const {
     return TypedText == Other.TypedText && MatcherDecl == Other.MatcherDecl;
   }
@@ -58,28 +67,28 @@
   /// constructor, or Optional<MatcherCtor>() if not found.
   static llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName);
 
-  /// \brief Compute the list of completions for \p Context.
+  /// \brief Compute the list of completion types for \p Context.
   ///
   /// Each element of \p Context represents a matcher invocation, going from
-  /// outermost to innermost. Elements are pairs consisting of a reference to the
-  /// matcher constructor and the index of the next element in the argument list
-  /// of that matcher (or for the last element, the index of the completion
-  /// point in the argument list). An empty list requests completion for the
-  /// root matcher.
+  /// outermost to innermost. Elements are pairs consisting of a reference to
+  /// the matcher constructor and the index of the next element in the
+  /// argument list of that matcher (or for the last element, the index of
+  /// the completion point in the argument list). An empty list requests
+  /// completion for the root matcher.
+  static std::vector<ArgKind> getAcceptedCompletionTypes(
+      llvm::ArrayRef<std::pair<MatcherCtor, unsigned>> Context);
+
+  /// \brief Compute the list of completions that match any of
+  /// \p AcceptedTypes.
   ///
-  /// The completions are ordered first by decreasing relevance, then
-  /// alphabetically.  Relevance is determined by how closely the matcher's
-  /// type matches that of the context. For example, if the innermost matcher
-  /// takes a FunctionDecl matcher, the FunctionDecl matchers are returned
-  /// first, followed by the ValueDecl matchers, then NamedDecl, then Decl, then
-  /// polymorphic matchers.
+  /// \param AcceptedTypes All types accepted for this completion.
   ///
-  /// Matchers which are technically convertible to the innermost context but
-  /// which would match either all or no nodes are excluded. For example,
-  /// namedDecl and varDecl are excluded in a FunctionDecl context, because
-  /// those matchers would match respectively all or no nodes in such a context.
+  /// \return All completions for the specified types.
+  /// Completions should be valid when used in \c lookupMatcherCtor().
+  /// The matcher constructed from the return of \c lookupMatcherCtor()
+  /// should be convertible to some type in \p AcceptedTypes.
   static std::vector<MatcherCompletion>
-  getCompletions(ArrayRef<std::pair<MatcherCtor, unsigned> > Context);
+  getMatcherCompletions(ArrayRef<ArgKind> AcceptedTypes);
 
   /// \brief Construct a matcher from the registry.
   ///
diff --git a/include/clang/ASTMatchers/Dynamic/VariantValue.h b/include/clang/ASTMatchers/Dynamic/VariantValue.h
index b25267b..a9bd3d5 100644
--- a/include/clang/ASTMatchers/Dynamic/VariantValue.h
+++ b/include/clang/ASTMatchers/Dynamic/VariantValue.h
@@ -14,8 +14,8 @@
 ///
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_AST_MATCHERS_DYNAMIC_VARIANT_VALUE_H
-#define LLVM_CLANG_AST_MATCHERS_DYNAMIC_VARIANT_VALUE_H
+#ifndef LLVM_CLANG_ASTMATCHERS_DYNAMIC_VARIANTVALUE_H
+#define LLVM_CLANG_ASTMATCHERS_DYNAMIC_VARIANTVALUE_H
 
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/ASTMatchers/ASTMatchersInternal.h"
@@ -29,6 +29,51 @@
 namespace ast_matchers {
 namespace dynamic {
 
+/// \brief Kind identifier.
+///
+/// It supports all types that VariantValue can contain.
+class ArgKind {
+ public:
+  enum Kind {
+    AK_Matcher,
+    AK_Unsigned,
+    AK_String
+  };
+  /// \brief Constructor for non-matcher types.
+  ArgKind(Kind K) : K(K) { assert(K != AK_Matcher); }
+
+  /// \brief Constructor for matcher types.
+  ArgKind(ast_type_traits::ASTNodeKind MatcherKind)
+      : K(AK_Matcher), MatcherKind(MatcherKind) {}
+
+  Kind getArgKind() const { return K; }
+  ast_type_traits::ASTNodeKind getMatcherKind() const {
+    assert(K == AK_Matcher);
+    return MatcherKind;
+  }
+
+  /// \brief Determines if this type can be converted to \p To.
+  ///
+  /// \param To the requested destination type.
+  ///
+  /// \param Specificity value corresponding to the "specificity" of the
+  ///   convertion.
+  bool isConvertibleTo(ArgKind To, unsigned *Specificity) const;
+
+  bool operator<(const ArgKind &Other) const {
+    if (K == AK_Matcher && Other.K == AK_Matcher)
+      return MatcherKind < Other.MatcherKind;
+    return K < Other.K;
+  }
+
+  /// \brief String representation of the type.
+  std::string asString() const;
+
+private:
+  Kind K;
+  ast_type_traits::ASTNodeKind MatcherKind;
+};
+
 using ast_matchers::internal::DynTypedMatcher;
 
 /// \brief A variant matcher object.
@@ -48,13 +93,28 @@
   /// \brief Methods that depend on T from hasTypedMatcher/getTypedMatcher.
   class MatcherOps {
   public:
-    virtual ~MatcherOps();
-    virtual bool canConstructFrom(const DynTypedMatcher &Matcher,
-                                  bool &IsExactMatch) const = 0;
-    virtual void constructFrom(const DynTypedMatcher &Matcher) = 0;
-    virtual void constructVariadicOperator(
-        ast_matchers::internal::VariadicOperatorFunction Func,
-        ArrayRef<VariantMatcher> InnerMatchers) = 0;
+    MatcherOps(ast_type_traits::ASTNodeKind NodeKind) : NodeKind(NodeKind) {}
+
+    bool canConstructFrom(const DynTypedMatcher &Matcher,
+                          bool &IsExactMatch) const;
+
+    /// \brief Convert \p Matcher the destination type and return it as a new
+    /// DynTypedMatcher.
+    virtual DynTypedMatcher
+    convertMatcher(const DynTypedMatcher &Matcher) const = 0;
+
+    /// \brief Constructs a variadic typed matcher from \p InnerMatchers.
+    /// Will try to convert each inner matcher to the destination type and
+    /// return llvm::None if it fails to do so.
+    llvm::Optional<DynTypedMatcher>
+    constructVariadicOperator(DynTypedMatcher::VariadicOperator Op,
+                              ArrayRef<VariantMatcher> InnerMatchers) const;
+
+  protected:
+    ~MatcherOps() {}
+
+  private:
+    ast_type_traits::ASTNodeKind NodeKind;
   };
 
   /// \brief Payload interface to be specialized by each matcher type.
@@ -65,7 +125,10 @@
     virtual ~Payload();
     virtual llvm::Optional<DynTypedMatcher> getSingleMatcher() const = 0;
     virtual std::string getTypeAsString() const = 0;
-    virtual void makeTypedMatcher(MatcherOps &Ops) const = 0;
+    virtual llvm::Optional<DynTypedMatcher>
+    getTypedMatcher(const MatcherOps &Ops) const = 0;
+    virtual bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind,
+                                 unsigned *Specificity) const = 0;
   };
 
 public:
@@ -84,9 +147,9 @@
   /// \brief Creates a 'variadic' operator matcher.
   ///
   /// It will bind to the appropriate type on getTypedMatcher<T>().
-  static VariantMatcher VariadicOperatorMatcher(
-      ast_matchers::internal::VariadicOperatorFunction Func,
-      std::vector<VariantMatcher> Args);
+  static VariantMatcher
+  VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op,
+                          std::vector<VariantMatcher> Args);
 
   /// \brief Makes the matcher the "null" matcher.
   void reset();
@@ -111,9 +174,21 @@
   /// that can, the result would be ambiguous and false is returned.
   template <class T>
   bool hasTypedMatcher() const {
-    TypedMatcherOps<T> Ops;
-    if (Value) Value->makeTypedMatcher(Ops);
-    return Ops.hasMatcher();
+    if (!Value) return false;
+    return Value->getTypedMatcher(TypedMatcherOps<T>()).hasValue();
+  }
+
+  /// \brief Determines if the contained matcher can be converted to \p Kind.
+  ///
+  /// \param Kind the requested destination type.
+  ///
+  /// \param Specificity value corresponding to the "specificity" of the
+  ///   convertion.
+  bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind,
+                       unsigned *Specificity) const {
+    if (Value)
+      return Value->isConvertibleTo(Kind, Specificity);
+    return false;
   }
 
   /// \brief Return this matcher as a \c Matcher<T>.
@@ -122,10 +197,9 @@
   /// Asserts that \c hasTypedMatcher<T>() is true.
   template <class T>
   ast_matchers::internal::Matcher<T> getTypedMatcher() const {
-    TypedMatcherOps<T> Ops;
-    Value->makeTypedMatcher(Ops);
-    assert(Ops.hasMatcher() && "hasTypedMatcher<T>() == false");
-    return Ops.matcher();
+    assert(hasTypedMatcher<T>() && "hasTypedMatcher<T>() == false");
+    return Value->getTypedMatcher(TypedMatcherOps<T>())
+        ->template convertTo<T>();
   }
 
   /// \brief String representation of the type of the value.
@@ -137,53 +211,27 @@
 private:
   explicit VariantMatcher(Payload *Value) : Value(Value) {}
 
+  template <typename T> struct TypedMatcherOps;
+
   class SinglePayload;
   class PolymorphicPayload;
   class VariadicOpPayload;
 
-  template <typename T>
-  class TypedMatcherOps : public MatcherOps {
-  public:
-    typedef ast_matchers::internal::Matcher<T> MatcherT;
-
-    virtual bool canConstructFrom(const DynTypedMatcher &Matcher,
-                                  bool &IsExactMatch) const {
-      IsExactMatch = Matcher.getSupportedKind().isSame(
-          ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
-      return Matcher.canConvertTo<T>();
-    }
-
-    virtual void constructFrom(const DynTypedMatcher& Matcher) {
-      Out.reset(new MatcherT(Matcher.convertTo<T>()));
-    }
-
-    virtual void constructVariadicOperator(
-        ast_matchers::internal::VariadicOperatorFunction Func,
-        ArrayRef<VariantMatcher> InnerMatchers) {
-      std::vector<DynTypedMatcher> DynMatchers;
-      for (size_t i = 0, e = InnerMatchers.size(); i != e; ++i) {
-        // Abort if any of the inner matchers can't be converted to
-        // Matcher<T>.
-        if (!InnerMatchers[i].hasTypedMatcher<T>()) {
-          return;
-        }
-        DynMatchers.push_back(InnerMatchers[i].getTypedMatcher<T>());
-      }
-      Out.reset(new MatcherT(
-          new ast_matchers::internal::VariadicOperatorMatcherInterface<T>(
-              Func, DynMatchers)));
-    }
-
-    bool hasMatcher() const { return Out.get() != nullptr; }
-    const MatcherT &matcher() const { return *Out; }
-
-  private:
-    std::unique_ptr<MatcherT> Out;
-  };
-
   IntrusiveRefCntPtr<const Payload> Value;
 };
 
+template <typename T>
+struct VariantMatcher::TypedMatcherOps final : VariantMatcher::MatcherOps {
+  TypedMatcherOps()
+      : MatcherOps(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()) {}
+  typedef ast_matchers::internal::Matcher<T> MatcherT;
+
+  DynTypedMatcher
+  convertMatcher(const DynTypedMatcher &Matcher) const override {
+    return DynTypedMatcher(Matcher.convertTo<T>());
+  }
+};
+
 /// \brief Variant value class.
 ///
 /// Basically, a tagged union with value type semantics.
@@ -228,6 +276,24 @@
   const VariantMatcher &getMatcher() const;
   void setMatcher(const VariantMatcher &Matcher);
 
+  /// \brief Determines if the contained value can be converted to \p Kind.
+  ///
+  /// \param Kind the requested destination type.
+  ///
+  /// \param Specificity value corresponding to the "specificity" of the
+  ///   convertion.
+  bool isConvertibleTo(ArgKind Kind, unsigned* Specificity) const;
+
+  /// \brief Determines if the contained value can be converted to any kind
+  /// in \p Kinds.
+  ///
+  /// \param Kinds the requested destination types.
+  ///
+  /// \param Specificity value corresponding to the "specificity" of the
+  ///   convertion. It is the maximum specificity of all the possible
+  ///   conversions.
+  bool isConvertibleTo(ArrayRef<ArgKind> Kinds, unsigned *Specificity) const;
+
   /// \brief String representation of the type of the value.
   std::string getTypeAsString() const;
 
diff --git a/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h b/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h
index a61d9e4..cc14c7b 100644
--- a/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h
+++ b/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h
@@ -13,8 +13,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef CLANG_ANALYSIS_CFG_REACHABILITY
-#define CLANG_ANALYSIS_CFG_REACHABILITY
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_CFGREACHABILITYANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_CFGREACHABILITYANALYSIS_H
 
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/DenseMap.h"
diff --git a/include/clang/Analysis/Analyses/Consumed.h b/include/clang/Analysis/Analyses/Consumed.h
index 36e07c2..a710923 100644
--- a/include/clang/Analysis/Analyses/Consumed.h
+++ b/include/clang/Analysis/Analyses/Consumed.h
@@ -12,8 +12,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_CONSUMED_H
-#define LLVM_CLANG_CONSUMED_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_CONSUMED_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_CONSUMED_H
 
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/ExprCXX.h"
diff --git a/include/clang/Analysis/Analyses/Dominators.h b/include/clang/Analysis/Analyses/Dominators.h
index 6c6d923..fcef0fc 100644
--- a/include/clang/Analysis/Analyses/Dominators.h
+++ b/include/clang/Analysis/Analyses/Dominators.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_DOMINATORS_H
-#define LLVM_CLANG_DOMINATORS_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_DOMINATORS_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_DOMINATORS_H
 
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Analysis/CFG.h"
diff --git a/include/clang/Analysis/Analyses/FormatString.h b/include/clang/Analysis/Analyses/FormatString.h
index 76fe9dd..174cce4 100644
--- a/include/clang/Analysis/Analyses/FormatString.h
+++ b/include/clang/Analysis/Analyses/FormatString.h
@@ -16,8 +16,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_FORMAT_H
-#define LLVM_CLANG_FORMAT_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_FORMATSTRING_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_FORMATSTRING_H
 
 #include "clang/AST/CanonicalType.h"
 
@@ -79,6 +79,7 @@
     AsLongDouble, // 'L'
     AsAllocate,   // for '%as', GNU extension to C90 scanf
     AsMAllocate,  // for '%ms', GNU extension to scanf
+    AsWide,       // 'w' (MSVCRT, like l but only for c, C, s, S, or Z
     AsWideChar = AsLong // for '%ls', only makes sense for printf
   };
 
@@ -154,6 +155,8 @@
 
     // ** Printf-specific **
 
+    ZArg, // MS extension
+
     // Objective-C specific specifiers.
     ObjCObjArg,  // '@'
     ObjCBeg = ObjCObjArg, ObjCEnd = ObjCObjArg,
@@ -644,6 +647,9 @@
 bool ParsePrintfString(FormatStringHandler &H,
                        const char *beg, const char *end, const LangOptions &LO,
                        const TargetInfo &Target);
+  
+bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO,
+                              const TargetInfo &Target);
 
 bool ParseScanfString(FormatStringHandler &H,
                       const char *beg, const char *end, const LangOptions &LO,
diff --git a/include/clang/Analysis/Analyses/LiveVariables.h b/include/clang/Analysis/Analyses/LiveVariables.h
index 7842271..c29dd40 100644
--- a/include/clang/Analysis/Analyses/LiveVariables.h
+++ b/include/clang/Analysis/Analyses/LiveVariables.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_LIVEVARIABLES_H
-#define LLVM_CLANG_LIVEVARIABLES_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIVEVARIABLES_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_LIVEVARIABLES_H
 
 #include "clang/AST/Decl.h"
 #include "clang/Analysis/AnalysisContext.h"
diff --git a/include/clang/Analysis/Analyses/PostOrderCFGView.h b/include/clang/Analysis/Analyses/PostOrderCFGView.h
index 91bf51c..a1c6504 100644
--- a/include/clang/Analysis/Analyses/PostOrderCFGView.h
+++ b/include/clang/Analysis/Analyses/PostOrderCFGView.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_POSTORDER_CFGVIEW
-#define LLVM_CLANG_POSTORDER_CFGVIEW
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_POSTORDERCFGVIEW_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_POSTORDERCFGVIEW_H
 
 #include <vector>
 //#include <algorithm>
@@ -47,17 +47,17 @@
 
     /// \brief Set the bit associated with a particular CFGBlock.
     /// This is the important method for the SetType template parameter.
-    bool insert(const CFGBlock *Block) {
+    std::pair<llvm::NoneType, bool> insert(const CFGBlock *Block) {
       // Note that insert() is called by po_iterator, which doesn't check to
       // make sure that Block is non-null.  Moreover, the CFGBlock iterator will
       // occasionally hand out null pointers for pruned edges, so we catch those
       // here.
       if (!Block)
-        return false;  // if an edge is trivially false.
+        return std::make_pair(None, false); // if an edge is trivially false.
       if (VisitedBlockIDs.test(Block->getBlockID()))
-        return false;
+        return std::make_pair(None, false);
       VisitedBlockIDs.set(Block->getBlockID());
-      return true;
+      return std::make_pair(None, true);
     }
 
     /// \brief Check if the bit for a CFGBlock has been already set.
diff --git a/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h b/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h
index cb73850..c4ec2f2 100644
--- a/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h
+++ b/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h
@@ -13,8 +13,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_ANALYSIS_PSEUDOCONSTANTANALYSIS
-#define LLVM_CLANG_ANALYSIS_PSEUDOCONSTANTANALYSIS
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_PSEUDOCONSTANTANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_PSEUDOCONSTANTANALYSIS_H
 
 #include "clang/AST/Stmt.h"
 
diff --git a/include/clang/Analysis/Analyses/ReachableCode.h b/include/clang/Analysis/Analyses/ReachableCode.h
index 90a6d01..4c523bf 100644
--- a/include/clang/Analysis/Analyses/ReachableCode.h
+++ b/include/clang/Analysis/Analyses/ReachableCode.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_REACHABLECODE_H
-#define LLVM_CLANG_REACHABLECODE_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_REACHABLECODE_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_REACHABLECODE_H
 
 #include "clang/Basic/SourceLocation.h"
 
diff --git a/include/clang/Analysis/Analyses/ThreadSafety.h b/include/clang/Analysis/Analyses/ThreadSafety.h
index b533c1d..458bb57 100644
--- a/include/clang/Analysis/Analyses/ThreadSafety.h
+++ b/include/clang/Analysis/Analyses/ThreadSafety.h
@@ -16,31 +16,33 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_THREADSAFETY_H
-#define LLVM_CLANG_THREADSAFETY_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETY_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETY_H
 
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
-namespace thread_safety {
+namespace threadSafety {
 
 /// 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 {
   POK_VarDereference, ///< Dereferencing a variable (e.g. p in *p = 5;)
   POK_VarAccess, ///< Reading or writing a variable (e.g. x in x = 5;)
-  POK_FunctionCall ///< Making a function call (e.g. fool())
+  POK_FunctionCall, ///< Making a function call (e.g. fool())
+  POK_PassByRef, ///< Passing a guarded variable by reference.
+  POK_PtPassByRef,  ///< Passing a pt-guarded variable by reference.
 };
 
 /// This enum distinguishes between different kinds of lock actions. For
 /// example, it is an error to write a variable protected by shared version of a
 /// mutex.
 enum LockKind {
-  LK_Shared, ///< Shared/reader lock of a mutex.
+  LK_Shared,    ///< Shared/reader lock of a mutex.
   LK_Exclusive, ///< Exclusive/writer lock of a mutex.
-  LK_Generic  ///<  Can be either Shared or Exclusive
+  LK_Generic    ///< Can be either Shared or Exclusive
 };
 
 /// This enum distinguishes between different ways to access (read or write) a
@@ -161,6 +163,16 @@
                                   LockKind LK, SourceLocation Loc,
                                   Name *PossibleMatch = nullptr) {}
 
+  /// Warn when acquiring a lock that the negative capability is not held.
+  /// \param Kind -- the capability's name parameter (role, mutex, etc).
+  /// \param LockName -- The name for the lock expression, to be printed in the
+  /// diagnostic.
+  /// \param Neg -- The name of the negative capability to be printed in the
+  /// diagnostic.
+  /// \param Loc -- The location of the protected operation.
+  virtual void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
+                                     SourceLocation Loc) {}
+
   /// Warn when a function is called while an excluded mutex is locked. For
   /// example, the mutex may be locked inside the function.
   /// \param Kind -- the capability's name parameter (role, mutex, etc).
@@ -171,6 +183,13 @@
   virtual void handleFunExcludesLock(StringRef Kind, Name FunName,
                                      Name LockName, 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) {}
+
+  /// Called by the analysis when finishing analysis of a function.
+  virtual void leaveFunction(const FunctionDecl *FD) {}
+
   bool issueBetaWarnings() { return IssueBetaWarnings; }
   void setIssueBetaWarnings(bool b) { IssueBetaWarnings = b; }
 
@@ -190,5 +209,5 @@
 /// of access.
 LockKind getLockKindFromAccessKind(AccessKind AK);
 
-}} // end namespace clang::thread_safety
+}} // end namespace clang::threadSafety
 #endif
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyCommon.h b/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
index 09c614c..76d8389 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
@@ -19,21 +19,64 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_THREAD_SAFETY_COMMON_H
-#define LLVM_CLANG_THREAD_SAFETY_COMMON_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
 
 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
+#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Basic/OperatorKinds.h"
 
 #include <memory>
+#include <ostream>
+#include <sstream>
 #include <vector>
 
 
 namespace clang {
 namespace threadSafety {
 
+
+// Various helper functions on til::SExpr
+namespace sx {
+
+inline bool equals(const til::SExpr *E1, const til::SExpr *E2) {
+  return til::EqualsComparator::compareExprs(E1, E2);
+}
+
+inline bool matches(const til::SExpr *E1, const til::SExpr *E2) {
+  // We treat a top-level wildcard as the "univsersal" lock.
+  // It matches everything for the purpose of checking locks, but not
+  // for unlocking them.
+  if (isa<til::Wildcard>(E1))
+    return isa<til::Wildcard>(E2);
+  if (isa<til::Wildcard>(E2))
+    return isa<til::Wildcard>(E1);
+
+  return til::MatchComparator::compareExprs(E1, E2);
+}
+
+inline bool partiallyMatches(const til::SExpr *E1, const til::SExpr *E2) {
+  const auto *PE1 = dyn_cast_or_null<til::Project>(E1);
+  if (!PE1)
+    return false;
+  const auto *PE2 = dyn_cast_or_null<til::Project>(E2);
+  if (!PE2)
+    return false;
+  return PE1->clangDecl() == PE2->clangDecl();
+}
+
+inline std::string toString(const til::SExpr *E) {
+  std::stringstream ss;
+  til::StdPrinter::print(E, ss);
+  return ss.str();
+}
+
+}  // end namespace sx
+
+
+
 // This class defines the interface of a clang CFG Visitor.
 // CFGWalker will invoke the following methods.
 // Note that methods are not virtual; the visitor is templatized.
@@ -206,6 +249,59 @@
 };
 
 
+
+
+class CapabilityExpr {
+  // TODO: move this back into ThreadSafety.cpp
+  // This is specific to thread safety.  It is here because
+  // translateAttrExpr needs it, but that should be moved too.
+
+private:
+  const til::SExpr* CapExpr;   ///< The capability expression.
+  bool Negated;                ///< True if this is a negative capability
+
+public:
+  CapabilityExpr(const til::SExpr *E, bool Neg) : CapExpr(E), Negated(Neg) {}
+
+  const til::SExpr* sexpr()    const { return CapExpr; }
+  bool              negative() const { return Negated; }
+
+  CapabilityExpr operator!() const {
+    return CapabilityExpr(CapExpr, !Negated);
+  }
+
+  bool equals(const CapabilityExpr &other) const {
+    return (Negated == other.Negated) && sx::equals(CapExpr, other.CapExpr);
+  }
+
+  bool matches(const CapabilityExpr &other) const {
+    return (Negated == other.Negated) && sx::matches(CapExpr, other.CapExpr);
+  }
+
+  bool matchesUniv(const CapabilityExpr &CapE) const {
+    return isUniversal() || matches(CapE);
+  }
+
+  bool partiallyMatches(const CapabilityExpr &other) const {
+    return (Negated == other.Negated) &&
+            sx::partiallyMatches(CapExpr, other.CapExpr);
+  }
+
+  std::string toString() const {
+    if (Negated)
+      return "!" + sx::toString(CapExpr);
+    return sx::toString(CapExpr);
+  }
+
+  bool shouldIgnore() const { return CapExpr == nullptr; }
+
+  bool isInvalid() const { return sexpr() && isa<til::Undefined>(sexpr()); }
+
+  bool isUniversal() const { return sexpr() && isa<til::Wildcard>(sexpr()); }
+};
+
+
+
 // Translate clang::Expr to til::SExpr.
 class SExprBuilder {
 public:
@@ -219,18 +315,16 @@
   /// should be evaluated; multiple calling contexts can be chained together
   /// by the lock_returned attribute.
   struct CallingContext {
+    CallingContext  *Prev;      // The previous context; or 0 if none.
     const NamedDecl *AttrDecl;  // The decl to which the attr is attached.
     const Expr *SelfArg;        // Implicit object argument -- e.g. 'this'
     unsigned NumArgs;           // Number of funArgs
     const Expr *const *FunArgs; // Function arguments
-    CallingContext *Prev;       // The previous context; or 0 if none.
     bool SelfArrow;             // is Self referred to with -> or .?
 
-    CallingContext(const NamedDecl *D = nullptr, const Expr *S = nullptr,
-                   unsigned N = 0, const Expr *const *A = nullptr,
-                   CallingContext *P = nullptr)
-        : AttrDecl(D), SelfArg(S), NumArgs(N), FunArgs(A), Prev(P),
-          SelfArrow(false)
+    CallingContext(CallingContext *P, const NamedDecl *D = nullptr)
+        : Prev(P), AttrDecl(D), SelfArg(nullptr),
+          NumArgs(0), FunArgs(nullptr), SelfArrow(false)
     {}
   };
 
@@ -242,6 +336,13 @@
     SelfVar->setKind(til::Variable::VK_SFun);
   }
 
+  // Translate a clang expression in an attribute to a til::SExpr.
+  // Constructs the context from D, DeclExp, and SelfDecl.
+  CapabilityExpr translateAttrExpr(const Expr *AttrExp, const NamedDecl *D,
+                                   const Expr *DeclExp, VarDecl *SelfD=nullptr);
+
+  CapabilityExpr translateAttrExpr(const Expr *AttrExp, CallingContext *Ctx);
+
   // Translate a clang statement or expression to a TIL expression.
   // Also performs substitution of variables; Ctx provides the context.
   // Dispatches on the type of S.
@@ -262,7 +363,8 @@
                                    CallingContext *Ctx) ;
   til::SExpr *translateCXXThisExpr(const CXXThisExpr *TE, CallingContext *Ctx);
   til::SExpr *translateMemberExpr(const MemberExpr *ME, CallingContext *Ctx);
-  til::SExpr *translateCallExpr(const CallExpr *CE, CallingContext *Ctx);
+  til::SExpr *translateCallExpr(const CallExpr *CE, CallingContext *Ctx,
+                                const Expr *SelfE = nullptr);
   til::SExpr *translateCXXMemberCallExpr(const CXXMemberCallExpr *ME,
                                          CallingContext *Ctx);
   til::SExpr *translateCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE,
@@ -280,10 +382,8 @@
   til::SExpr *translateCastExpr(const CastExpr *CE, CallingContext *Ctx);
   til::SExpr *translateArraySubscriptExpr(const ArraySubscriptExpr *E,
                                           CallingContext *Ctx);
-  til::SExpr *translateConditionalOperator(const ConditionalOperator *C,
-                                           CallingContext *Ctx);
-  til::SExpr *translateBinaryConditionalOperator(
-      const BinaryConditionalOperator *C, CallingContext *Ctx);
+  til::SExpr *translateAbstractConditionalOperator(
+      const AbstractConditionalOperator *C, CallingContext *Ctx);
 
   til::SExpr *translateDeclStmt(const DeclStmt *S, CallingContext *Ctx);
 
@@ -362,21 +462,24 @@
   void mergePhiNodesBackEdge(const CFGBlock *Blk);
 
 private:
+  // Set to true when parsing capability expressions, which get translated
+  // inaccurately in order to hack around smart pointers etc.
+  static const bool CapabilityExprMode = true;
+
   til::MemRegionRef Arena;
   til::Variable *SelfVar;       // Variable to use for 'this'.  May be null.
-  til::SCFG *Scfg;
 
+  til::SCFG *Scfg;
   StatementMap SMap;                       // Map from Stmt to TIL Variables
   LVarIndexMap LVarIdxMap;                 // Indices of clang local vars.
   std::vector<til::BasicBlock *> BlockMap; // Map from clang to til BBs.
   std::vector<BlockInfo> BBInfo;           // Extra information per BB.
                                            // Indexed by clang BlockID.
-  std::unique_ptr<SExprBuilder::CallingContext> CallCtx; // Root calling context
 
   LVarDefinitionMap CurrentLVarMap;
-  std::vector<til::Variable*> CurrentArguments;
-  std::vector<til::Variable*> CurrentInstructions;
-  std::vector<til::Variable*> IncompleteArgs;
+  std::vector<til::Phi*>   CurrentArguments;
+  std::vector<til::SExpr*> CurrentInstructions;
+  std::vector<til::Phi*>   IncompleteArgs;
   til::BasicBlock *CurrentBB;
   BlockInfo *CurrentBlockInfo;
 };
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyLogical.h b/include/clang/Analysis/Analyses/ThreadSafetyLogical.h
index c4f4b21..bc78021 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyLogical.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyLogical.h
@@ -10,8 +10,8 @@
 // that are used as part of fact-checking capability expressions.
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_THREAD_SAFETY_LOGICAL_H
-#define LLVM_CLANG_THREAD_SAFETY_LOGICAL_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYLOGICAL_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYLOGICAL_H
 
 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
 
@@ -41,13 +41,13 @@
 };
 
 class Terminal : public LExpr {
-  til::SExprRef Expr;
+  til::SExpr *Expr;
 
 public:
   Terminal(til::SExpr *Expr) : LExpr(LExpr::Terminal), Expr(Expr) {}
 
-  const til::SExpr *expr() const { return Expr.get(); }
-  til::SExpr *expr() { return Expr.get(); }
+  const til::SExpr *expr() const { return Expr; }
+  til::SExpr *expr() { return Expr; }
 
   static bool classof(const LExpr *E) { return E->kind() == LExpr::Terminal; }
 };
@@ -104,5 +104,5 @@
 }
 }
 
-#endif // LLVM_CLANG_THREAD_SAFETY_LOGICAL_H
+#endif
 
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyOps.def b/include/clang/Analysis/Analyses/ThreadSafetyOps.def
index 6ebc95d..0d2458b 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyOps.def
+++ b/include/clang/Analysis/Analyses/ThreadSafetyOps.def
@@ -44,8 +44,11 @@
 TIL_OPCODE_DEF(SCFG)
 TIL_OPCODE_DEF(BasicBlock)
 TIL_OPCODE_DEF(Phi)
+
+// Terminator instructions
 TIL_OPCODE_DEF(Goto)
 TIL_OPCODE_DEF(Branch)
+TIL_OPCODE_DEF(Return)
 
 // pseudo-terms
 TIL_OPCODE_DEF(Identifier)
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyTIL.h b/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
index 8e4299e..e06593c 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
@@ -44,8 +44,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_THREAD_SAFETY_TIL_H
-#define LLVM_CLANG_THREAD_SAFETY_TIL_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTIL_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTIL_H
 
 // All clang include dependencies for this file must be put in
 // ThreadSafetyUtil.h.
@@ -63,24 +63,27 @@
 namespace til {
 
 
+/// Enum for the different distinct classes of SExpr
 enum TIL_Opcode {
 #define TIL_OPCODE_DEF(X) COP_##X,
 #include "ThreadSafetyOps.def"
 #undef TIL_OPCODE_DEF
 };
 
+/// Opcode for unary arithmetic operations.
 enum TIL_UnaryOpcode : unsigned char {
   UOP_Minus,        //  -
   UOP_BitNot,       //  ~
   UOP_LogicNot      //  !
 };
 
+/// Opcode for binary arithmetic operations.
 enum TIL_BinaryOpcode : unsigned char {
+  BOP_Add,          //  +
+  BOP_Sub,          //  -
   BOP_Mul,          //  *
   BOP_Div,          //  /
   BOP_Rem,          //  %
-  BOP_Add,          //  +
-  BOP_Sub,          //  -
   BOP_Shl,          //  <<
   BOP_Shr,          //  >>
   BOP_BitAnd,       //  &
@@ -90,37 +93,42 @@
   BOP_Neq,          //  !=
   BOP_Lt,           //  <
   BOP_Leq,          //  <=
-  BOP_LogicAnd,     //  &&
-  BOP_LogicOr       //  ||
+  BOP_LogicAnd,     //  &&  (no short-circuit)
+  BOP_LogicOr       //  ||  (no short-circuit)
 };
 
+/// Opcode for cast operations.
 enum TIL_CastOpcode : unsigned char {
   CAST_none = 0,
   CAST_extendNum,   // extend precision of numeric type
   CAST_truncNum,    // truncate precision of numeric type
   CAST_toFloat,     // convert to floating point type
   CAST_toInt,       // convert to integer type
+  CAST_objToPtr     // convert smart pointer to pointer  (C++ only)
 };
 
 const TIL_Opcode       COP_Min  = COP_Future;
 const TIL_Opcode       COP_Max  = COP_Branch;
 const TIL_UnaryOpcode  UOP_Min  = UOP_Minus;
 const TIL_UnaryOpcode  UOP_Max  = UOP_LogicNot;
-const TIL_BinaryOpcode BOP_Min  = BOP_Mul;
+const TIL_BinaryOpcode BOP_Min  = BOP_Add;
 const TIL_BinaryOpcode BOP_Max  = BOP_LogicOr;
 const TIL_CastOpcode   CAST_Min = CAST_none;
 const TIL_CastOpcode   CAST_Max = CAST_toInt;
 
+/// Return the name of a unary opcode.
 StringRef getUnaryOpcodeString(TIL_UnaryOpcode Op);
+
+/// Return the name of a binary opcode.
 StringRef getBinaryOpcodeString(TIL_BinaryOpcode Op);
 
 
-// ValueTypes are data types that can actually be held in registers.
-// All variables and expressions must have a vBNF_Nonealue type.
-// Pointer types are further subdivided into the various heap-allocated
-// types, such as functions, records, etc.
-// Structured types that are passed by value (e.g. complex numbers)
-// require special handling; they use BT_ValueRef, and size ST_0.
+/// ValueTypes are data types that can actually be held in registers.
+/// All variables and expressions must have a value type.
+/// Pointer types are further subdivided into the various heap-allocated
+/// types, such as functions, records, etc.
+/// Structured types that are passed by value (e.g. complex numbers)
+/// require special handling; they use BT_ValueRef, and size ST_0.
 struct ValueType {
   enum BaseType : unsigned char {
     BT_Void = 0,
@@ -246,8 +254,10 @@
 }
 
 
+class BasicBlock;
 
-// Base class for AST nodes in the typed intermediate language.
+
+/// Base class for AST nodes in the typed intermediate language.
 class SExpr {
 public:
   TIL_Opcode opcode() const { return static_cast<TIL_Opcode>(Opcode); }
@@ -266,71 +276,47 @@
   // template <class C> typename C::CType compare(CType* E, C& Cmp) {
   //   compare all subexpressions, following the comparator interface
   // }
-
   void *operator new(size_t S, MemRegionRef &R) {
     return ::operator new(S, R);
   }
 
-  // SExpr objects cannot be deleted.
+  /// 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;
 
+  /// Returns the instruction ID for this expression.
+  /// All basic block instructions have a unique ID (i.e. virtual register).
+  unsigned id() const { return SExprID; }
+
+  /// Returns the block, if this is an instruction in a basic block,
+  /// otherwise returns null.
+  BasicBlock* block() const { return Block; }
+
+  /// Set the basic block and instruction ID for this expression.
+  void setID(BasicBlock *B, unsigned id) { Block = B; SExprID = id; }
+
 protected:
-  SExpr(TIL_Opcode Op) : Opcode(Op), Reserved(0), Flags(0) {}
-  SExpr(const SExpr &E) : Opcode(E.Opcode), Reserved(0), Flags(E.Flags) {}
+  SExpr(TIL_Opcode Op)
+    : Opcode(Op), Reserved(0), Flags(0), SExprID(0), Block(nullptr) {}
+  SExpr(const SExpr &E)
+    : Opcode(E.Opcode), Reserved(0), Flags(E.Flags), SExprID(0),
+      Block(nullptr) {}
 
   const unsigned char Opcode;
   unsigned char Reserved;
   unsigned short Flags;
+  unsigned SExprID;
+  BasicBlock* Block;
 
 private:
   SExpr() LLVM_DELETED_FUNCTION;
 
-  // SExpr objects must be created in an arena.
+  /// SExpr objects must be created in an arena.
   void *operator new(size_t) LLVM_DELETED_FUNCTION;
 };
 
 
-// Class for owning references to SExprs.
-// Includes attach/detach logic for counting variable references and lazy
-// rewriting strategies.
-class SExprRef {
-public:
-  SExprRef() : Ptr(nullptr) { }
-  SExprRef(std::nullptr_t P) : Ptr(nullptr) { }
-  SExprRef(SExprRef &&R) : Ptr(R.Ptr) { R.Ptr = nullptr; }
-
-  // Defined after Variable and Future, below.
-  inline SExprRef(SExpr *P);
-  inline ~SExprRef();
-
-  SExpr       *get()       { return Ptr; }
-  const SExpr *get() const { return Ptr; }
-
-  SExpr       *operator->()       { return get(); }
-  const SExpr *operator->() const { return get(); }
-
-  SExpr       &operator*()        { return *Ptr; }
-  const SExpr &operator*() const  { return *Ptr; }
-
-  bool operator==(const SExprRef &R) const { return Ptr == R.Ptr; }
-  bool operator!=(const SExprRef &R) const { return !operator==(R); }
-  bool operator==(const SExpr *P)    const { return Ptr == P; }
-  bool operator!=(const SExpr *P)    const { return !operator==(P); }
-  bool operator==(std::nullptr_t)    const { return Ptr == nullptr; }
-  bool operator!=(std::nullptr_t)    const { return Ptr != nullptr; }
-
-  inline void reset(SExpr *E);
-
-private:
-  inline void attach();
-  inline void detach();
-
-  SExpr *Ptr;
-};
-
-
 // Contains various helper functions for SExprs.
 namespace ThreadSafetyTIL {
   inline bool isTrivial(const SExpr *E) {
@@ -342,62 +328,64 @@
 // Nodes which declare variables
 class Function;
 class SFunction;
-class BasicBlock;
 class Let;
 
 
-// A named variable, e.g. "x".
-//
-// There are two distinct places in which a Variable can appear in the AST.
-// A variable declaration introduces a new variable, and can occur in 3 places:
-//   Let-expressions:           (Let (x = t) u)
-//   Functions:                 (Function (x : t) u)
-//   Self-applicable functions  (SFunction (x) t)
-//
-// If a variable occurs in any other location, it is a reference to an existing
-// variable declaration -- e.g. 'x' in (x * y + z). To save space, we don't
-// allocate a separate AST node for variable references; a reference is just a
-// pointer to the original declaration.
+/// A named variable, e.g. "x".
+///
+/// There are two distinct places in which a Variable can appear in the AST.
+/// A variable declaration introduces a new variable, and can occur in 3 places:
+///   Let-expressions:           (Let (x = t) u)
+///   Functions:                 (Function (x : t) u)
+///   Self-applicable functions  (SFunction (x) t)
+///
+/// If a variable occurs in any other location, it is a reference to an existing
+/// variable declaration -- e.g. 'x' in (x * y + z). To save space, we don't
+/// allocate a separate AST node for variable references; a reference is just a
+/// pointer to the original declaration.
 class Variable : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Variable; }
 
-  // Let-variable, function parameter, or self-variable
   enum VariableKind {
-    VK_Let,
-    VK_LetBB,
-    VK_Fun,
-    VK_SFun
+    VK_Let,  ///< Let-variable
+    VK_Fun,  ///< Function parameter
+    VK_SFun  ///< SFunction (self) parameter
   };
 
-  // These are defined after SExprRef contructor, below
-  inline Variable(SExpr *D, const clang::ValueDecl *Cvd = nullptr);
-  inline Variable(StringRef s, SExpr *D = nullptr);
-  inline Variable(const Variable &Vd, SExpr *D);
+  Variable(StringRef s, SExpr *D = nullptr)
+      : SExpr(COP_Variable), Name(s), Definition(D), Cvdecl(nullptr) {
+    Flags = VK_Let;
+  }
+  Variable(SExpr *D, const clang::ValueDecl *Cvd = nullptr)
+      : SExpr(COP_Variable), Name(Cvd ? Cvd->getName() : "_x"),
+        Definition(D), Cvdecl(Cvd) {
+    Flags = VK_Let;
+  }
+  Variable(const Variable &Vd, SExpr *D)  // rewrite constructor
+      : SExpr(Vd), Name(Vd.Name), Definition(D), Cvdecl(Vd.Cvdecl) {
+    Flags = Vd.kind();
+  }
 
+  /// Return the kind of variable (let, function param, or self)
   VariableKind kind() const { return static_cast<VariableKind>(Flags); }
 
-  const StringRef name() const { return Name; }
+  /// Return the name of the variable, if any.
+  StringRef name() const { return Name; }
+
+  /// Return the clang declaration for this variable, if any.
   const clang::ValueDecl *clangDecl() const { return Cvdecl; }
 
-  // Returns the definition (for let vars) or type (for parameter & self vars)
-  SExpr *definition() { return Definition.get(); }
-  const SExpr *definition() const { return Definition.get(); }
+  /// Return the definition of the variable.
+  /// For let-vars, this is the setting expression.
+  /// For function and self parameters, it is the type of the variable.
+  SExpr *definition() { return Definition; }
+  const SExpr *definition() const { return Definition; }
 
-  void attachVar() const { ++NumUses; }
-  void detachVar() const { assert(NumUses > 0); --NumUses; }
-
-  unsigned getID() const { return Id; }
-  unsigned getBlockID() const { return BlockID; }
-
-  void setName(StringRef S) { Name = S; }
-  void setID(unsigned Bid, unsigned I) {
-    BlockID = static_cast<unsigned short>(Bid);
-    Id = static_cast<unsigned short>(I);
-  }
-  void setClangDecl(const clang::ValueDecl *VD) { Cvdecl = VD; }
-  void setDefinition(SExpr *E);
+  void setName(StringRef S)    { Name = S;  }
   void setKind(VariableKind K) { Flags = K; }
+  void setDefinition(SExpr *E) { Definition = E; }
+  void setClangDecl(const clang::ValueDecl *VD) { Cvdecl = VD; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -405,7 +393,8 @@
     return Vs.reduceVariableRef(this);
   }
 
-  template <class C> typename C::CType compare(Variable* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Variable* E, C& Cmp) const {
     return Cmp.compareVariableRefs(this, E);
   }
 
@@ -416,17 +405,13 @@
   friend class Let;
 
   StringRef Name;                  // The name of the variable.
-  SExprRef  Definition;            // The TIL type or definition
+  SExpr*    Definition;            // The TIL type or definition
   const clang::ValueDecl *Cvdecl;  // The clang declaration for this variable.
-
-  unsigned short BlockID;
-  unsigned short Id;
-  mutable unsigned NumUses;
 };
 
 
-// Placeholder for an expression that has not yet been created.
-// Used to implement lazy copy and rewriting strategies.
+/// Placeholder for an expression that has not yet been created.
+/// Used to implement lazy copy and rewriting strategies.
 class Future : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Future; }
@@ -437,25 +422,17 @@
     FS_done
   };
 
-  Future() :
-    SExpr(COP_Future), Status(FS_pending), Result(nullptr), Location(nullptr)
-  {}
+  Future() : SExpr(COP_Future), Status(FS_pending), Result(nullptr) {}
+
 private:
   virtual ~Future() LLVM_DELETED_FUNCTION;
+
 public:
-
-  // Registers the location in the AST where this future is stored.
-  // Forcing the future will automatically update the AST.
-  static inline void registerLocation(SExprRef *Member) {
-    if (Future *F = dyn_cast_or_null<Future>(Member->get()))
-      F->Location = Member;
-  }
-
   // A lazy rewriting strategy should subclass Future and override this method.
-  virtual SExpr *create() { return nullptr; }
+  virtual SExpr *compute() { return nullptr; }
 
   // Return the result of this future if it exists, otherwise return null.
-  SExpr *maybeGetResult() {
+  SExpr *maybeGetResult() const {
     return Result;
   }
 
@@ -463,8 +440,7 @@
   SExpr *result() {
     switch (Status) {
     case FS_pending:
-      force();
-      return Result;
+      return force();
     case FS_evaluating:
       return nullptr; // infinite loop; illegal recursion.
     case FS_done:
@@ -478,88 +454,22 @@
     return Vs.traverse(Result, Ctx);
   }
 
-  template <class C> typename C::CType compare(Future* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Future* E, C& Cmp) const {
     if (!Result || !E->Result)
       return Cmp.comparePointers(this, E);
     return Cmp.compare(Result, E->Result);
   }
 
 private:
-  // Force the future.
-  inline void force();
+  SExpr* force();
 
   FutureStatus Status;
   SExpr *Result;
-  SExprRef *Location;
 };
 
 
-inline void SExprRef::attach() {
-  if (!Ptr)
-    return;
-
-  TIL_Opcode Op = Ptr->opcode();
-  if (Op == COP_Variable) {
-    cast<Variable>(Ptr)->attachVar();
-  } else if (Op == COP_Future) {
-    cast<Future>(Ptr)->registerLocation(this);
-  }
-}
-
-inline void SExprRef::detach() {
-  if (Ptr && Ptr->opcode() == COP_Variable) {
-    cast<Variable>(Ptr)->detachVar();
-  }
-}
-
-inline SExprRef::SExprRef(SExpr *P) : Ptr(P) {
-  attach();
-}
-
-inline SExprRef::~SExprRef() {
-  detach();
-}
-
-inline void SExprRef::reset(SExpr *P) {
-  detach();
-  Ptr = P;
-  attach();
-}
-
-
-inline Variable::Variable(StringRef s, SExpr *D)
-    : SExpr(COP_Variable), Name(s), Definition(D), Cvdecl(nullptr),
-      BlockID(0), Id(0), NumUses(0) {
-  Flags = VK_Let;
-}
-
-inline Variable::Variable(SExpr *D, const clang::ValueDecl *Cvd)
-    : SExpr(COP_Variable), Name(Cvd ? Cvd->getName() : "_x"),
-      Definition(D), Cvdecl(Cvd), BlockID(0), Id(0), NumUses(0) {
-  Flags = VK_Let;
-}
-
-inline Variable::Variable(const Variable &Vd, SExpr *D) // rewrite constructor
-    : SExpr(Vd), Name(Vd.Name), Definition(D), Cvdecl(Vd.Cvdecl),
-      BlockID(0), Id(0), NumUses(0) {
-  Flags = Vd.kind();
-}
-
-inline void Variable::setDefinition(SExpr *E) {
-  Definition.reset(E);
-}
-
-void Future::force() {
-  Status = FS_evaluating;
-  SExpr *R = create();
-  Result = R;
-  if (Location)
-    Location->reset(R);
-  Status = FS_done;
-}
-
-
-// Placeholder for C++ expressions that cannot be represented in the TIL.
+/// Placeholder for expressions that cannot be represented in the TIL.
 class Undefined : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Undefined; }
@@ -572,8 +482,9 @@
     return Vs.reduceUndefined(*this);
   }
 
-  template <class C> typename C::CType compare(Undefined* E, C& Cmp) {
-    return Cmp.comparePointers(Cstmt, E->Cstmt);
+  template <class C>
+  typename C::CType compare(const Undefined* E, C& Cmp) const {
+    return Cmp.trueResult();
   }
 
 private:
@@ -581,7 +492,7 @@
 };
 
 
-// Placeholder for a wildcard that matches any other expression.
+/// Placeholder for a wildcard that matches any other expression.
 class Wildcard : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Wildcard; }
@@ -593,7 +504,8 @@
     return Vs.reduceWildcard(*this);
   }
 
-  template <class C> typename C::CType compare(Wildcard* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Wildcard* E, C& Cmp) const {
     return Cmp.trueResult();
   }
 };
@@ -626,9 +538,10 @@
 
   template <class V> typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx);
 
-  template <class C> typename C::CType compare(Literal* E, C& Cmp) {
-    // TODO -- use value, not pointer equality
-    return Cmp.comparePointers(Cexpr, E->Cexpr);
+  template <class C>
+  typename C::CType compare(const Literal* E, C& Cmp) const {
+    // TODO: defer actual comparison to LiteralT
+    return Cmp.trueResult();
   }
 
 private:
@@ -710,8 +623,8 @@
 }
 
 
-// Literal pointer to an object allocated in memory.
-// At compile time, pointer literals are represented by symbolic names.
+/// A Literal pointer to an object allocated in memory.
+/// At compile time, pointer literals are represented by symbolic names.
 class LiteralPtr : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_LiteralPtr; }
@@ -727,7 +640,8 @@
     return Vs.reduceLiteralPtr(*this);
   }
 
-  template <class C> typename C::CType compare(LiteralPtr* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const LiteralPtr* E, C& Cmp) const {
     return Cmp.comparePointers(Cvdecl, E->Cvdecl);
   }
 
@@ -736,9 +650,9 @@
 };
 
 
-// A function -- a.k.a. lambda abstraction.
-// Functions with multiple arguments are created by currying,
-// e.g. (function (x: Int) (function (y: Int) (add x y)))
+/// A function -- a.k.a. lambda abstraction.
+/// Functions with multiple arguments are created by currying,
+/// e.g. (Function (x: Int) (Function (y: Int) (Code { return x + y })))
 class Function : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Function; }
@@ -755,8 +669,8 @@
   Variable *variableDecl()  { return VarDecl; }
   const Variable *variableDecl() const { return VarDecl; }
 
-  SExpr *body() { return Body.get(); }
-  const SExpr *body() const { return Body.get(); }
+  SExpr *body() { return Body; }
+  const SExpr *body() const { return Body; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -769,7 +683,8 @@
     return Vs.reduceFunction(*this, Nvd, E1);
   }
 
-  template <class C> typename C::CType compare(Function* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Function* E, C& Cmp) const {
     typename C::CType Ct =
       Cmp.compare(VarDecl->definition(), E->VarDecl->definition());
     if (Cmp.notTrue(Ct))
@@ -782,13 +697,13 @@
 
 private:
   Variable *VarDecl;
-  SExprRef Body;
+  SExpr* Body;
 };
 
 
-// A self-applicable function.
-// A self-applicable function can be applied to itself.  It's useful for
-// implementing objects and late binding
+/// A self-applicable function.
+/// A self-applicable function can be applied to itself.  It's useful for
+/// implementing objects and late binding.
 class SFunction : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_SFunction; }
@@ -797,20 +712,20 @@
       : SExpr(COP_SFunction), VarDecl(Vd), Body(B) {
     assert(Vd->Definition == nullptr);
     Vd->setKind(Variable::VK_SFun);
-    Vd->Definition.reset(this);
+    Vd->Definition = this;
   }
   SFunction(const SFunction &F, Variable *Vd, SExpr *B) // rewrite constructor
       : SExpr(F), VarDecl(Vd), Body(B) {
     assert(Vd->Definition == nullptr);
     Vd->setKind(Variable::VK_SFun);
-    Vd->Definition.reset(this);
+    Vd->Definition = this;
   }
 
   Variable *variableDecl() { return VarDecl; }
   const Variable *variableDecl() const { return VarDecl; }
 
-  SExpr *body() { return Body.get(); }
-  const SExpr *body() const { return Body.get(); }
+  SExpr *body() { return Body; }
+  const SExpr *body() const { return Body; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -824,7 +739,8 @@
     return Vs.reduceSFunction(*this, Nvd, E1);
   }
 
-  template <class C> typename C::CType compare(SFunction* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const SFunction* E, C& Cmp) const {
     Cmp.enterScope(variableDecl(), E->variableDecl());
     typename C::CType Ct = Cmp.compare(body(), E->body());
     Cmp.leaveScope();
@@ -833,11 +749,11 @@
 
 private:
   Variable *VarDecl;
-  SExprRef Body;
+  SExpr* Body;
 };
 
 
-// A block of code -- e.g. the body of a function.
+/// A block of code -- e.g. the body of a function.
 class Code : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Code; }
@@ -846,11 +762,11 @@
   Code(const Code &C, SExpr *T, SExpr *B) // rewrite constructor
       : SExpr(C), ReturnType(T), Body(B) {}
 
-  SExpr *returnType() { return ReturnType.get(); }
-  const SExpr *returnType() const { return ReturnType.get(); }
+  SExpr *returnType() { return ReturnType; }
+  const SExpr *returnType() const { return ReturnType; }
 
-  SExpr *body() { return Body.get(); }
-  const SExpr *body() const { return Body.get(); }
+  SExpr *body() { return Body; }
+  const SExpr *body() const { return Body; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -859,7 +775,8 @@
     return Vs.reduceCode(*this, Nt, Nb);
   }
 
-  template <class C> typename C::CType compare(Code* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Code* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(returnType(), E->returnType());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -867,12 +784,12 @@
   }
 
 private:
-  SExprRef ReturnType;
-  SExprRef Body;
+  SExpr* ReturnType;
+  SExpr* Body;
 };
 
 
-// A typed, writable location in memory
+/// A typed, writable location in memory
 class Field : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Field; }
@@ -881,11 +798,11 @@
   Field(const Field &C, SExpr *R, SExpr *B) // rewrite constructor
       : SExpr(C), Range(R), Body(B) {}
 
-  SExpr *range() { return Range.get(); }
-  const SExpr *range() const { return Range.get(); }
+  SExpr *range() { return Range; }
+  const SExpr *range() const { return Range; }
 
-  SExpr *body() { return Body.get(); }
-  const SExpr *body() const { return Body.get(); }
+  SExpr *body() { return Body; }
+  const SExpr *body() const { return Body; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -894,7 +811,8 @@
     return Vs.reduceField(*this, Nr, Nb);
   }
 
-  template <class C> typename C::CType compare(Field* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Field* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(range(), E->range());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -902,12 +820,16 @@
   }
 
 private:
-  SExprRef Range;
-  SExprRef Body;
+  SExpr* Range;
+  SExpr* Body;
 };
 
 
-// Apply an argument to a function
+/// Apply an argument to a function.
+/// Note that this does not actually call the function.  Functions are curried,
+/// so this returns a closure in which the first parameter has been applied.
+/// Once all parameters have been applied, Call can be used to invoke the
+/// function.
 class Apply : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Apply; }
@@ -917,11 +839,11 @@
       : SExpr(A), Fun(F), Arg(Ar)
   {}
 
-  SExpr *fun() { return Fun.get(); }
-  const SExpr *fun() const { return Fun.get(); }
+  SExpr *fun() { return Fun; }
+  const SExpr *fun() const { return Fun; }
 
-  SExpr *arg() { return Arg.get(); }
-  const SExpr *arg() const { return Arg.get(); }
+  SExpr *arg() { return Arg; }
+  const SExpr *arg() const { return Arg; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -930,7 +852,8 @@
     return Vs.reduceApply(*this, Nf, Na);
   }
 
-  template <class C> typename C::CType compare(Apply* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Apply* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(fun(), E->fun());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -938,12 +861,12 @@
   }
 
 private:
-  SExprRef Fun;
-  SExprRef Arg;
+  SExpr* Fun;
+  SExpr* Arg;
 };
 
 
-// Apply a self-argument to a self-applicable function
+/// Apply a self-argument to a self-applicable function.
 class SApply : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_SApply; }
@@ -952,23 +875,24 @@
   SApply(SApply &A, SExpr *Sf, SExpr *Ar = nullptr) // rewrite constructor
       : SExpr(A), Sfun(Sf), Arg(Ar) {}
 
-  SExpr *sfun() { return Sfun.get(); }
-  const SExpr *sfun() const { return Sfun.get(); }
+  SExpr *sfun() { return Sfun; }
+  const SExpr *sfun() const { return Sfun; }
 
-  SExpr *arg() { return Arg.get() ? Arg.get() : Sfun.get(); }
-  const SExpr *arg() const { return Arg.get() ? Arg.get() : Sfun.get(); }
+  SExpr *arg() { return Arg ? Arg : Sfun; }
+  const SExpr *arg() const { return Arg ? Arg : Sfun; }
 
-  bool isDelegation() const { return Arg == nullptr; }
+  bool isDelegation() const { return Arg != nullptr; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
     auto Nf = Vs.traverse(Sfun, Vs.subExprCtx(Ctx));
-    typename V::R_SExpr Na = Arg.get() ? Vs.traverse(Arg, Vs.subExprCtx(Ctx))
+    typename V::R_SExpr Na = Arg ? Vs.traverse(Arg, Vs.subExprCtx(Ctx))
                                        : nullptr;
     return Vs.reduceSApply(*this, Nf, Na);
   }
 
-  template <class C> typename C::CType compare(SApply* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const SApply* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(sfun(), E->sfun());
     if (Cmp.notTrue(Ct) || (!arg() && !E->arg()))
       return Ct;
@@ -976,12 +900,12 @@
   }
 
 private:
-  SExprRef Sfun;
-  SExprRef Arg;
+  SExpr* Sfun;
+  SExpr* Arg;
 };
 
 
-// Project a named slot from a C++ struct or class.
+/// Project a named slot from a C++ struct or class.
 class Project : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Project; }
@@ -989,17 +913,23 @@
   Project(SExpr *R, StringRef SName)
       : SExpr(COP_Project), Rec(R), SlotName(SName), Cvdecl(nullptr)
   { }
-  Project(SExpr *R, clang::ValueDecl *Cvd)
+  Project(SExpr *R, const clang::ValueDecl *Cvd)
       : SExpr(COP_Project), Rec(R), SlotName(Cvd->getName()), Cvdecl(Cvd)
   { }
   Project(const Project &P, SExpr *R)
       : SExpr(P), Rec(R), SlotName(P.SlotName), Cvdecl(P.Cvdecl)
   { }
 
-  SExpr *record() { return Rec.get(); }
-  const SExpr *record() const { return Rec.get(); }
+  SExpr *record() { return Rec; }
+  const SExpr *record() const { return Rec; }
 
-  const clang::ValueDecl *clangValueDecl() const { return Cvdecl; }
+  const clang::ValueDecl *clangDecl() const { return Cvdecl; }
+
+  bool isArrow() const { return (Flags & 0x01) != 0; }
+  void setArrow(bool b) {
+    if (b) Flags |= 0x01;
+    else Flags &= 0xFFFE;
+  }
 
   StringRef slotName() const {
     if (Cvdecl)
@@ -1014,7 +944,8 @@
     return Vs.reduceProject(*this, Nr);
   }
 
-  template <class C> typename C::CType compare(Project* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Project* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(record(), E->record());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -1022,13 +953,13 @@
   }
 
 private:
-  SExprRef Rec;
+  SExpr* Rec;
   StringRef SlotName;
-  clang::ValueDecl *Cvdecl;
+  const clang::ValueDecl *Cvdecl;
 };
 
 
-// Call a function (after all arguments have been applied).
+/// Call a function (after all arguments have been applied).
 class Call : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Call; }
@@ -1037,8 +968,8 @@
       : SExpr(COP_Call), Target(T), Cexpr(Ce) {}
   Call(const Call &C, SExpr *T) : SExpr(C), Target(T), Cexpr(C.Cexpr) {}
 
-  SExpr *target() { return Target.get(); }
-  const SExpr *target() const { return Target.get(); }
+  SExpr *target() { return Target; }
+  const SExpr *target() const { return Target; }
 
   const clang::CallExpr *clangCallExpr() const { return Cexpr; }
 
@@ -1048,17 +979,18 @@
     return Vs.reduceCall(*this, Nt);
   }
 
-  template <class C> typename C::CType compare(Call* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Call* E, C& Cmp) const {
     return Cmp.compare(target(), E->target());
   }
 
 private:
-  SExprRef Target;
+  SExpr* Target;
   const clang::CallExpr *Cexpr;
 };
 
 
-// Allocate memory for a new value on the heap or stack.
+/// Allocate memory for a new value on the heap or stack.
 class Alloc : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Call; }
@@ -1073,8 +1005,8 @@
 
   AllocKind kind() const { return static_cast<AllocKind>(Flags); }
 
-  SExpr *dataType() { return Dtype.get(); }
-  const SExpr *dataType() const { return Dtype.get(); }
+  SExpr *dataType() { return Dtype; }
+  const SExpr *dataType() const { return Dtype; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1082,7 +1014,8 @@
     return Vs.reduceAlloc(*this, Nd);
   }
 
-  template <class C> typename C::CType compare(Alloc* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Alloc* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compareIntegers(kind(), E->kind());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -1090,11 +1023,11 @@
   }
 
 private:
-  SExprRef Dtype;
+  SExpr* Dtype;
 };
 
 
-// Load a value from memory.
+/// Load a value from memory.
 class Load : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Load; }
@@ -1102,8 +1035,8 @@
   Load(SExpr *P) : SExpr(COP_Load), Ptr(P) {}
   Load(const Load &L, SExpr *P) : SExpr(L), Ptr(P) {}
 
-  SExpr *pointer() { return Ptr.get(); }
-  const SExpr *pointer() const { return Ptr.get(); }
+  SExpr *pointer() { return Ptr; }
+  const SExpr *pointer() const { return Ptr; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1111,17 +1044,18 @@
     return Vs.reduceLoad(*this, Np);
   }
 
-  template <class C> typename C::CType compare(Load* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Load* E, C& Cmp) const {
     return Cmp.compare(pointer(), E->pointer());
   }
 
 private:
-  SExprRef Ptr;
+  SExpr* Ptr;
 };
 
 
-// Store a value to memory.
-// Source is a pointer, destination is the value to store.
+/// Store a value to memory.
+/// The destination is a pointer to a field, the source is the value to store.
 class Store : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Store; }
@@ -1129,11 +1063,11 @@
   Store(SExpr *P, SExpr *V) : SExpr(COP_Store), Dest(P), Source(V) {}
   Store(const Store &S, SExpr *P, SExpr *V) : SExpr(S), Dest(P), Source(V) {}
 
-  SExpr *destination() { return Dest.get(); }  // Address to store to
-  const SExpr *destination() const { return Dest.get(); }
+  SExpr *destination() { return Dest; }  // Address to store to
+  const SExpr *destination() const { return Dest; }
 
-  SExpr *source() { return Source.get(); }     // Value to store
-  const SExpr *source() const { return Source.get(); }
+  SExpr *source() { return Source; }     // Value to store
+  const SExpr *source() const { return Source; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1142,7 +1076,8 @@
     return Vs.reduceStore(*this, Np, Nv);
   }
 
-  template <class C> typename C::CType compare(Store* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Store* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(destination(), E->destination());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -1150,13 +1085,13 @@
   }
 
 private:
-  SExprRef Dest;
-  SExprRef Source;
+  SExpr* Dest;
+  SExpr* Source;
 };
 
 
-// If p is a reference to an array, then first(p) is a reference to the first
-// element.  The usual array notation p[i]  becomes first(p + i).
+/// If p is a reference to an array, then p[i] is a reference to the i'th
+/// element of the array.
 class ArrayIndex : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_ArrayIndex; }
@@ -1165,11 +1100,11 @@
   ArrayIndex(const ArrayIndex &E, SExpr *A, SExpr *N)
     : SExpr(E), Array(A), Index(N) {}
 
-  SExpr *array() { return Array.get(); }
-  const SExpr *array() const { return Array.get(); }
+  SExpr *array() { return Array; }
+  const SExpr *array() const { return Array; }
 
-  SExpr *index() { return Index.get(); }
-  const SExpr *index() const { return Index.get(); }
+  SExpr *index() { return Index; }
+  const SExpr *index() const { return Index; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1178,7 +1113,8 @@
     return Vs.reduceArrayIndex(*this, Na, Ni);
   }
 
-  template <class C> typename C::CType compare(ArrayIndex* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const ArrayIndex* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(array(), E->array());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -1186,14 +1122,14 @@
   }
 
 private:
-  SExprRef Array;
-  SExprRef Index;
+  SExpr* Array;
+  SExpr* Index;
 };
 
 
-// Pointer arithmetic, restricted to arrays only.
-// If p is a reference to an array, then p + n, where n is an integer, is
-// a reference to a subarray.
+/// Pointer arithmetic, restricted to arrays only.
+/// If p is a reference to an array, then p + n, where n is an integer, is
+/// a reference to a subarray.
 class ArrayAdd : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_ArrayAdd; }
@@ -1202,11 +1138,11 @@
   ArrayAdd(const ArrayAdd &E, SExpr *A, SExpr *N)
     : SExpr(E), Array(A), Index(N) {}
 
-  SExpr *array() { return Array.get(); }
-  const SExpr *array() const { return Array.get(); }
+  SExpr *array() { return Array; }
+  const SExpr *array() const { return Array; }
 
-  SExpr *index() { return Index.get(); }
-  const SExpr *index() const { return Index.get(); }
+  SExpr *index() { return Index; }
+  const SExpr *index() const { return Index; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1215,7 +1151,8 @@
     return Vs.reduceArrayAdd(*this, Na, Ni);
   }
 
-  template <class C> typename C::CType compare(ArrayAdd* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const ArrayAdd* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(array(), E->array());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -1223,12 +1160,13 @@
   }
 
 private:
-  SExprRef Array;
-  SExprRef Index;
+  SExpr* Array;
+  SExpr* Index;
 };
 
 
-// Simple unary operation -- e.g. !, ~, etc.
+/// Simple arithmetic unary operations, e.g. negate and not.
+/// These operations have no side-effects.
 class UnaryOp : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_UnaryOp; }
@@ -1242,8 +1180,8 @@
     return static_cast<TIL_UnaryOpcode>(Flags);
   }
 
-  SExpr *expr() { return Expr0.get(); }
-  const SExpr *expr() const { return Expr0.get(); }
+  SExpr *expr() { return Expr0; }
+  const SExpr *expr() const { return Expr0; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1251,7 +1189,8 @@
     return Vs.reduceUnaryOp(*this, Ne);
   }
 
-  template <class C> typename C::CType compare(UnaryOp* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const UnaryOp* E, C& Cmp) const {
     typename C::CType Ct =
       Cmp.compareIntegers(unaryOpcode(), E->unaryOpcode());
     if (Cmp.notTrue(Ct))
@@ -1260,11 +1199,12 @@
   }
 
 private:
-  SExprRef Expr0;
+  SExpr* Expr0;
 };
 
 
-// Simple binary operation -- e.g. +, -, etc.
+/// Simple arithmetic binary operations, e.g. +, -, etc.
+/// These operations have no side effects.
 class BinaryOp : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_BinaryOp; }
@@ -1282,11 +1222,11 @@
     return static_cast<TIL_BinaryOpcode>(Flags);
   }
 
-  SExpr *expr0() { return Expr0.get(); }
-  const SExpr *expr0() const { return Expr0.get(); }
+  SExpr *expr0() { return Expr0; }
+  const SExpr *expr0() const { return Expr0; }
 
-  SExpr *expr1() { return Expr1.get(); }
-  const SExpr *expr1() const { return Expr1.get(); }
+  SExpr *expr1() { return Expr1; }
+  const SExpr *expr1() const { return Expr1; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1295,7 +1235,8 @@
     return Vs.reduceBinaryOp(*this, Ne0, Ne1);
   }
 
-  template <class C> typename C::CType compare(BinaryOp* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const BinaryOp* E, C& Cmp) const {
     typename C::CType Ct =
       Cmp.compareIntegers(binaryOpcode(), E->binaryOpcode());
     if (Cmp.notTrue(Ct))
@@ -1307,12 +1248,14 @@
   }
 
 private:
-  SExprRef Expr0;
-  SExprRef Expr1;
+  SExpr* Expr0;
+  SExpr* Expr1;
 };
 
 
-// Cast expression
+/// Cast expressions.
+/// Cast expressions are essentially unary operations, but we treat them
+/// as a distinct AST node because they only change the type of the result.
 class Cast : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Cast; }
@@ -1324,8 +1267,8 @@
     return static_cast<TIL_CastOpcode>(Flags);
   }
 
-  SExpr *expr() { return Expr0.get(); }
-  const SExpr *expr() const { return Expr0.get(); }
+  SExpr *expr() { return Expr0; }
+  const SExpr *expr() const { return Expr0; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1333,7 +1276,8 @@
     return Vs.reduceCast(*this, Ne);
   }
 
-  template <class C> typename C::CType compare(Cast* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Cast* E, C& Cmp) const {
     typename C::CType Ct =
       Cmp.compareIntegers(castOpcode(), E->castOpcode());
     if (Cmp.notTrue(Ct))
@@ -1342,16 +1286,18 @@
   }
 
 private:
-  SExprRef Expr0;
+  SExpr* Expr0;
 };
 
 
 class SCFG;
 
 
+/// Phi Node, for code in SSA form.
+/// Each Phi node has an array of possible values that it can take,
+/// depending on where control flow comes from.
 class Phi : public SExpr {
 public:
-  // TODO: change to SExprRef
   typedef SimpleArray<SExpr *> ValArray;
 
   // In minimal SSA form, all Phi nodes are MultiVal.
@@ -1365,9 +1311,12 @@
 
   static bool classof(const SExpr *E) { return E->opcode() == COP_Phi; }
 
-  Phi() : SExpr(COP_Phi) {}
-  Phi(MemRegionRef A, unsigned Nvals) : SExpr(COP_Phi), Values(A, Nvals) {}
-  Phi(const Phi &P, ValArray &&Vs)    : SExpr(P), Values(std::move(Vs)) {}
+  Phi()
+    : SExpr(COP_Phi), Cvdecl(nullptr) {}
+  Phi(MemRegionRef A, unsigned Nvals)
+    : SExpr(COP_Phi), Values(A, Nvals), Cvdecl(nullptr)  {}
+  Phi(const Phi &P, ValArray &&Vs)
+    : SExpr(P), Values(std::move(Vs)), Cvdecl(nullptr) {}
 
   const ValArray &values() const { return Values; }
   ValArray &values() { return Values; }
@@ -1375,6 +1324,12 @@
   Status status() const { return static_cast<Status>(Flags); }
   void setStatus(Status s) { Flags = s; }
 
+  /// Return the clang declaration of the variable for this Phi node, if any.
+  const clang::ValueDecl *clangDecl() const { return Cvdecl; }
+
+  /// Set the clang variable associated with this Phi node.
+  void setClangDecl(const clang::ValueDecl *Cvd) { Cvdecl = Cvd; }
+
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
     typename V::template Container<typename V::R_SExpr>
@@ -1386,72 +1341,268 @@
     return Vs.reducePhi(*this, Nvs);
   }
 
-  template <class C> typename C::CType compare(Phi *E, C &Cmp) {
+  template <class C>
+  typename C::CType compare(const Phi *E, C &Cmp) const {
     // TODO: implement CFG comparisons
     return Cmp.comparePointers(this, E);
   }
 
 private:
   ValArray Values;
+  const clang::ValueDecl* Cvdecl;
 };
 
 
-// A basic block is part of an SCFG, and can be treated as a function in
-// continuation passing style.  It consists of a sequence of phi nodes, which
-// are "arguments" to the function, followed by a sequence of instructions.
-// Both arguments and instructions define new variables.  It ends with a
-// branch or goto to another basic block in the same SCFG.
+/// Base class for basic block terminators:  Branch, Goto, and Return.
+class Terminator : public SExpr {
+public:
+  static bool classof(const SExpr *E) {
+    return E->opcode() >= COP_Goto && E->opcode() <= COP_Return;
+  }
+
+protected:
+  Terminator(TIL_Opcode Op)  : SExpr(Op) {}
+  Terminator(const SExpr &E) : SExpr(E)  {}
+
+public:
+  /// Return the list of basic blocks that this terminator can branch to.
+  ArrayRef<BasicBlock*> successors();
+
+  ArrayRef<BasicBlock*> successors() const {
+    return const_cast<const Terminator*>(this)->successors();
+  }
+};
+
+
+/// Jump to another basic block.
+/// A goto instruction is essentially a tail-recursive call into another
+/// block.  In addition to the block pointer, it specifies an index into the
+/// phi nodes of that block.  The index can be used to retrieve the "arguments"
+/// of the call.
+class Goto : public Terminator {
+public:
+  static bool classof(const SExpr *E) { return E->opcode() == COP_Goto; }
+
+  Goto(BasicBlock *B, unsigned I)
+      : Terminator(COP_Goto), TargetBlock(B), Index(I) {}
+  Goto(const Goto &G, BasicBlock *B, unsigned I)
+      : Terminator(COP_Goto), TargetBlock(B), Index(I) {}
+
+  const BasicBlock *targetBlock() const { return TargetBlock; }
+  BasicBlock *targetBlock() { return TargetBlock; }
+
+  /// Returns the index into the
+  unsigned index() const { return Index; }
+
+  /// Return the list of basic blocks that this terminator can branch to.
+  ArrayRef<BasicBlock*> successors() {
+    return ArrayRef<BasicBlock*>(&TargetBlock, 1);
+  }
+
+  template <class V>
+  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
+    BasicBlock *Ntb = Vs.reduceBasicBlockRef(TargetBlock);
+    return Vs.reduceGoto(*this, Ntb);
+  }
+
+  template <class C>
+  typename C::CType compare(const Goto *E, C &Cmp) const {
+    // TODO: implement CFG comparisons
+    return Cmp.comparePointers(this, E);
+  }
+
+private:
+  BasicBlock *TargetBlock;
+  unsigned Index;
+};
+
+
+/// A conditional branch to two other blocks.
+/// Note that unlike Goto, Branch does not have an index.  The target blocks
+/// must be child-blocks, and cannot have Phi nodes.
+class Branch : public Terminator {
+public:
+  static bool classof(const SExpr *E) { return E->opcode() == COP_Branch; }
+
+  Branch(SExpr *C, BasicBlock *T, BasicBlock *E)
+      : Terminator(COP_Branch), Condition(C) {
+    Branches[0] = T;
+    Branches[1] = E;
+  }
+  Branch(const Branch &Br, SExpr *C, BasicBlock *T, BasicBlock *E)
+      : Terminator(Br), Condition(C) {
+    Branches[0] = T;
+    Branches[1] = E;
+  }
+
+  const SExpr *condition() const { return Condition; }
+  SExpr *condition() { return Condition; }
+
+  const BasicBlock *thenBlock() const { return Branches[0]; }
+  BasicBlock *thenBlock() { return Branches[0]; }
+
+  const BasicBlock *elseBlock() const { return Branches[1]; }
+  BasicBlock *elseBlock() { return Branches[1]; }
+
+  /// Return the list of basic blocks that this terminator can branch to.
+  ArrayRef<BasicBlock*> successors() {
+    return ArrayRef<BasicBlock*>(Branches, 2);
+  }
+
+  template <class V>
+  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
+    auto Nc = Vs.traverse(Condition, Vs.subExprCtx(Ctx));
+    BasicBlock *Ntb = Vs.reduceBasicBlockRef(Branches[0]);
+    BasicBlock *Nte = Vs.reduceBasicBlockRef(Branches[1]);
+    return Vs.reduceBranch(*this, Nc, Ntb, Nte);
+  }
+
+  template <class C>
+  typename C::CType compare(const Branch *E, C &Cmp) const {
+    // TODO: implement CFG comparisons
+    return Cmp.comparePointers(this, E);
+  }
+
+private:
+  SExpr*     Condition;
+  BasicBlock *Branches[2];
+};
+
+
+/// Return from the enclosing function, passing the return value to the caller.
+/// Only the exit block should end with a return statement.
+class Return : public Terminator {
+public:
+  static bool classof(const SExpr *E) { return E->opcode() == COP_Return; }
+
+  Return(SExpr* Rval) : Terminator(COP_Return), Retval(Rval) {}
+  Return(const Return &R, SExpr* Rval) : Terminator(R), Retval(Rval) {}
+
+  /// Return an empty list.
+  ArrayRef<BasicBlock*> successors() {
+    return ArrayRef<BasicBlock*>();
+  }
+
+  SExpr *returnValue() { return Retval; }
+  const SExpr *returnValue() const { return Retval; }
+
+  template <class V>
+  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
+    auto Ne = Vs.traverse(Retval, Vs.subExprCtx(Ctx));
+    return Vs.reduceReturn(*this, Ne);
+  }
+
+  template <class C>
+  typename C::CType compare(const Return *E, C &Cmp) const {
+    return Cmp.compare(Retval, E->Retval);
+  }
+
+private:
+  SExpr* Retval;
+};
+
+
+inline ArrayRef<BasicBlock*> Terminator::successors() {
+  switch (opcode()) {
+    case COP_Goto:   return cast<Goto>(this)->successors();
+    case COP_Branch: return cast<Branch>(this)->successors();
+    case COP_Return: return cast<Return>(this)->successors();
+    default:
+      return ArrayRef<BasicBlock*>();
+  }
+}
+
+
+/// A basic block is part of an SCFG.  It can be treated as a function in
+/// continuation passing style.  A block consists of a sequence of phi nodes,
+/// which are "arguments" to the function, followed by a sequence of
+/// instructions.  It ends with a Terminator, which is a Branch or Goto to
+/// another basic block in the same SCFG.
 class BasicBlock : public SExpr {
 public:
-  typedef SimpleArray<Variable*>   VarArray;
+  typedef SimpleArray<SExpr*>      InstrArray;
   typedef SimpleArray<BasicBlock*> BlockArray;
 
+  // TopologyNodes are used to overlay tree structures on top of the CFG,
+  // such as dominator and postdominator trees.  Each block is assigned an
+  // ID in the tree according to a depth-first search.  Tree traversals are
+  // always up, towards the parents.
+  struct TopologyNode {
+    TopologyNode() : NodeID(0), SizeOfSubTree(0), Parent(nullptr) {}
+
+    bool isParentOf(const TopologyNode& OtherNode) {
+      return OtherNode.NodeID > NodeID &&
+             OtherNode.NodeID < NodeID + SizeOfSubTree;
+    }
+
+    bool isParentOfOrEqual(const TopologyNode& OtherNode) {
+      return OtherNode.NodeID >= NodeID &&
+             OtherNode.NodeID < NodeID + SizeOfSubTree;
+    }
+
+    int NodeID;
+    int SizeOfSubTree;    // Includes this node, so must be > 1.
+    BasicBlock *Parent;   // Pointer to parent.
+  };
+
   static bool classof(const SExpr *E) { return E->opcode() == COP_BasicBlock; }
 
-  explicit BasicBlock(MemRegionRef A, BasicBlock* P = nullptr)
+  explicit BasicBlock(MemRegionRef A)
       : SExpr(COP_BasicBlock), Arena(A), CFGPtr(nullptr), BlockID(0),
-        Parent(P), Terminator(nullptr)
-  { }
-  BasicBlock(BasicBlock &B, VarArray &&As, VarArray &&Is, SExpr *T)
-      : SExpr(COP_BasicBlock), Arena(B.Arena), CFGPtr(nullptr), BlockID(0),
-        Parent(nullptr), Args(std::move(As)), Instrs(std::move(Is)),
-        Terminator(T)
-  { }
+        Visited(0), TermInstr(nullptr) {}
+  BasicBlock(BasicBlock &B, MemRegionRef A, InstrArray &&As, InstrArray &&Is,
+             Terminator *T)
+      : SExpr(COP_BasicBlock), Arena(A), CFGPtr(nullptr), BlockID(0),Visited(0),
+        Args(std::move(As)), Instrs(std::move(Is)), TermInstr(T) {}
 
-  unsigned blockID() const { return BlockID; }
-  unsigned numPredecessors() const { return Predecessors.size(); }
+  /// Returns the block ID.  Every block has a unique ID in the CFG.
+  int blockID() const { return BlockID; }
+
+  /// Returns the number of predecessors.
+  size_t numPredecessors() const { return Predecessors.size(); }
+  size_t numSuccessors() const { return successors().size(); }
 
   const SCFG* cfg() const { return CFGPtr; }
   SCFG* cfg() { return CFGPtr; }
 
-  const BasicBlock *parent() const { return Parent; }
-  BasicBlock *parent() { return Parent; }
+  const BasicBlock *parent() const { return DominatorNode.Parent; }
+  BasicBlock *parent() { return DominatorNode.Parent; }
 
-  const VarArray &arguments() const { return Args; }
-  VarArray &arguments() { return Args; }
+  const InstrArray &arguments() const { return Args; }
+  InstrArray &arguments() { return Args; }
 
-  const VarArray &instructions() const { return Instrs; }
-  VarArray &instructions() { return Instrs; }
+  InstrArray &instructions() { return Instrs; }
+  const InstrArray &instructions() const { return Instrs; }
 
-  const BlockArray &predecessors() const { return Predecessors; }
+  /// Returns a list of predecessors.
+  /// The order of predecessors in the list is important; each phi node has
+  /// exactly one argument for each precessor, in the same order.
   BlockArray &predecessors() { return Predecessors; }
+  const BlockArray &predecessors() const { return Predecessors; }
 
-  const SExpr *terminator() const { return Terminator.get(); }
-  SExpr *terminator() { return Terminator.get(); }
+  ArrayRef<BasicBlock*> successors() { return TermInstr->successors(); }
+  ArrayRef<BasicBlock*> successors() const { return TermInstr->successors(); }
 
-  void setBlockID(unsigned i)   { BlockID = i; }
-  void setParent(BasicBlock *P) { Parent = P;  }
-  void setTerminator(SExpr *E)  { Terminator.reset(E); }
+  const Terminator *terminator() const { return TermInstr; }
+  Terminator *terminator() { return TermInstr; }
 
-  // Add a new argument.  V must define a phi-node.
-  void addArgument(Variable *V) {
-    V->setKind(Variable::VK_LetBB);
+  void setTerminator(Terminator *E) { TermInstr = E; }
+
+  bool Dominates(const BasicBlock &Other) {
+    return DominatorNode.isParentOfOrEqual(Other.DominatorNode);
+  }
+
+  bool PostDominates(const BasicBlock &Other) {
+    return PostDominatorNode.isParentOfOrEqual(Other.PostDominatorNode);
+  }
+
+  /// Add a new argument.
+  void addArgument(Phi *V) {
     Args.reserveCheck(1, Arena);
     Args.push_back(V);
   }
-  // Add a new instruction.
-  void addInstruction(Variable *V) {
-    V->setKind(Variable::VK_LetBB);
+  /// Add a new instruction.
+  void addInstruction(SExpr *V) {
     Instrs.reserveCheck(1, Arena);
     Instrs.push_back(V);
   }
@@ -1468,34 +1619,29 @@
   // Reserve space for NumPreds predecessors, including space in phi nodes.
   void reservePredecessors(unsigned NumPreds);
 
-  // Return the index of BB, or Predecessors.size if BB is not a predecessor.
+  /// Return the index of BB, or Predecessors.size if BB is not a predecessor.
   unsigned findPredecessorIndex(const BasicBlock *BB) const {
     auto I = std::find(Predecessors.cbegin(), Predecessors.cend(), BB);
     return std::distance(Predecessors.cbegin(), I);
   }
 
-  // Set id numbers for variables.
-  void renumberVars();
-
   template <class V>
   typename V::R_BasicBlock traverse(V &Vs, typename V::R_Ctx Ctx) {
-    typename V::template Container<Variable*> Nas(Vs, Args.size());
-    typename V::template Container<Variable*> Nis(Vs, Instrs.size());
+    typename V::template Container<SExpr*> Nas(Vs, Args.size());
+    typename V::template Container<SExpr*> Nis(Vs, Instrs.size());
 
     // Entering the basic block should do any scope initialization.
     Vs.enterBasicBlock(*this);
 
-    for (auto *A : Args) {
-      auto Ne = Vs.traverse(A->Definition, Vs.subExprCtx(Ctx));
-      Variable *Nvd = Vs.enterScope(*A, Ne);
-      Nas.push_back(Nvd);
+    for (auto *E : Args) {
+      auto Ne = Vs.traverse(E, Vs.subExprCtx(Ctx));
+      Nas.push_back(Ne);
     }
-    for (auto *I : Instrs) {
-      auto Ne = Vs.traverse(I->Definition, Vs.subExprCtx(Ctx));
-      Variable *Nvd = Vs.enterScope(*I, Ne);
-      Nis.push_back(Nvd);
+    for (auto *E : Instrs) {
+      auto Ne = Vs.traverse(E, Vs.subExprCtx(Ctx));
+      Nis.push_back(Ne);
     }
-    auto Nt = Vs.traverse(Terminator, Ctx);
+    auto Nt = Vs.traverse(TermInstr, Ctx);
 
     // Exiting the basic block should handle any scope cleanup.
     Vs.exitBasicBlock(*this);
@@ -1503,7 +1649,8 @@
     return Vs.reduceBasicBlock(*this, Nas, Nis, Nt);
   }
 
-  template <class C> typename C::CType compare(BasicBlock *E, C &Cmp) {
+  template <class C>
+  typename C::CType compare(const BasicBlock *E, C &Cmp) const {
     // TODO: implement CFG comparisons
     return Cmp.comparePointers(this, E);
   }
@@ -1511,22 +1658,32 @@
 private:
   friend class SCFG;
 
-  MemRegionRef Arena;
+  int  renumberInstrs(int id);  // assign unique ids to all instructions
+  int  topologicalSort(SimpleArray<BasicBlock*>& Blocks, int ID);
+  int  topologicalFinalSort(SimpleArray<BasicBlock*>& Blocks, int ID);
+  void computeDominator();
+  void computePostDominator();
 
-  SCFG       *CFGPtr;       // The CFG that contains this block.
-  unsigned   BlockID;       // unique id for this BB in the containing CFG
-  BasicBlock *Parent;       // The parent block is the enclosing lexical scope.
-                            // The parent dominates this block.
-  BlockArray Predecessors;  // Predecessor blocks in the CFG.
-  VarArray   Args;          // Phi nodes.  One argument per predecessor.
-  VarArray   Instrs;        // Instructions.
-  SExprRef   Terminator;    // Branch or Goto
+private:
+  MemRegionRef Arena;        // The arena used to allocate this block.
+  SCFG         *CFGPtr;      // The CFG that contains this block.
+  int          BlockID : 31; // unique id for this BB in the containing CFG.
+                             // IDs are in topological order.
+  bool         Visited : 1;  // Bit to determine if a block has been visited
+                             // during a traversal.
+  BlockArray  Predecessors;  // Predecessor blocks in the CFG.
+  InstrArray  Args;          // Phi nodes.  One argument per predecessor.
+  InstrArray  Instrs;        // Instructions.
+  Terminator* TermInstr;     // Terminating instruction
+
+  TopologyNode DominatorNode;       // The dominator tree
+  TopologyNode PostDominatorNode;   // The post-dominator tree
 };
 
 
-// An SCFG is a control-flow graph.  It consists of a set of basic blocks, each
-// of which terminates in a branch to another basic block.  There is one
-// entry point, and one exit point.
+/// An SCFG is a control-flow graph.  It consists of a set of basic blocks,
+/// each of which terminates in a branch to another basic block.  There is one
+/// entry point, and one exit point.
 class SCFG : public SExpr {
 public:
   typedef SimpleArray<BasicBlock *> BlockArray;
@@ -1537,20 +1694,29 @@
 
   SCFG(MemRegionRef A, unsigned Nblocks)
     : SExpr(COP_SCFG), Arena(A), Blocks(A, Nblocks),
-      Entry(nullptr), Exit(nullptr) {
-    Entry = new (A) BasicBlock(A, nullptr);
-    Exit  = new (A) BasicBlock(A, Entry);
-    auto *V = new (A) Variable(new (A) Phi());
+      Entry(nullptr), Exit(nullptr), NumInstructions(0), Normal(false) {
+    Entry = new (A) BasicBlock(A);
+    Exit  = new (A) BasicBlock(A);
+    auto *V = new (A) Phi();
     Exit->addArgument(V);
+    Exit->setTerminator(new (A) Return(V));
     add(Entry);
     add(Exit);
   }
   SCFG(const SCFG &Cfg, BlockArray &&Ba) // steals memory from Ba
       : SExpr(COP_SCFG), Arena(Cfg.Arena), Blocks(std::move(Ba)),
-        Entry(nullptr), Exit(nullptr) {
+        Entry(nullptr), Exit(nullptr), NumInstructions(0), Normal(false) {
     // TODO: set entry and exit!
   }
 
+  /// Return true if this CFG is valid.
+  bool valid() const { return Entry && Exit && Blocks.size() > 0; }
+
+  /// Return true if this CFG has been normalized.
+  /// After normalization, blocks are in topological order, and block and
+  /// instruction IDs have been assigned.
+  bool normal() const { return Normal; }
+
   iterator begin() { return Blocks.begin(); }
   iterator end() { return Blocks.end(); }
 
@@ -1565,9 +1731,17 @@
   const BasicBlock *exit() const { return Exit; }
   BasicBlock *exit() { return Exit; }
 
+  /// Return the number of blocks in the CFG.
+  /// Block::blockID() will return a number less than numBlocks();
+  size_t numBlocks() const { return Blocks.size(); }
+
+  /// Return the total number of instructions in the CFG.
+  /// This is useful for building instruction side-tables;
+  /// A call to SExpr::id() will return a number less than numInstructions().
+  unsigned numInstructions() { return NumInstructions; }
+
   inline void add(BasicBlock *BB) {
-    assert(BB->CFGPtr == nullptr || BB->CFGPtr == this);
-    BB->setBlockID(Blocks.size());
+    assert(BB->CFGPtr == nullptr);
     BB->CFGPtr = this;
     Blocks.reserveCheck(1, Arena);
     Blocks.push_back(BB);
@@ -1576,13 +1750,13 @@
   void setEntry(BasicBlock *BB) { Entry = BB; }
   void setExit(BasicBlock *BB)  { Exit = BB;  }
 
-  // Set varable ids in all blocks.
-  void renumberVars();
+  void computeNormalForm();
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
     Vs.enterCFG(*this);
     typename V::template Container<BasicBlock *> Bbs(Vs, Blocks.size());
+
     for (auto *B : Blocks) {
       Bbs.push_back( B->traverse(Vs, Vs.subExprCtx(Ctx)) );
     }
@@ -1590,100 +1764,28 @@
     return Vs.reduceSCFG(*this, Bbs);
   }
 
-  template <class C> typename C::CType compare(SCFG *E, C &Cmp) {
-    // TODO -- implement CFG comparisons
+  template <class C>
+  typename C::CType compare(const SCFG *E, C &Cmp) const {
+    // TODO: implement CFG comparisons
     return Cmp.comparePointers(this, E);
   }
 
 private:
+  void renumberInstrs();       // assign unique ids to all instructions
+
+private:
   MemRegionRef Arena;
   BlockArray   Blocks;
   BasicBlock   *Entry;
   BasicBlock   *Exit;
+  unsigned     NumInstructions;
+  bool         Normal;
 };
 
 
-class Goto : public SExpr {
-public:
-  static bool classof(const SExpr *E) { return E->opcode() == COP_Goto; }
 
-  Goto(BasicBlock *B, unsigned I)
-      : SExpr(COP_Goto), TargetBlock(B), Index(I) {}
-  Goto(const Goto &G, BasicBlock *B, unsigned I)
-      : SExpr(COP_Goto), TargetBlock(B), Index(I) {}
-
-  const BasicBlock *targetBlock() const { return TargetBlock; }
-  BasicBlock *targetBlock() { return TargetBlock; }
-
-  unsigned index() const { return Index; }
-
-  template <class V>
-  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
-    BasicBlock *Ntb = Vs.reduceBasicBlockRef(TargetBlock);
-    return Vs.reduceGoto(*this, Ntb);
-  }
-
-  template <class C> typename C::CType compare(Goto *E, C &Cmp) {
-    // TODO -- implement CFG comparisons
-    return Cmp.comparePointers(this, E);
-  }
-
-private:
-  BasicBlock *TargetBlock;
-  unsigned Index;   // Index into Phi nodes of target block.
-};
-
-
-class Branch : public SExpr {
-public:
-  static bool classof(const SExpr *E) { return E->opcode() == COP_Branch; }
-
-  Branch(SExpr *C, BasicBlock *T, BasicBlock *E, unsigned TI, unsigned EI)
-      : SExpr(COP_Branch), Condition(C), ThenBlock(T), ElseBlock(E),
-        ThenIndex(TI), ElseIndex(EI)
-  {}
-  Branch(const Branch &Br, SExpr *C, BasicBlock *T, BasicBlock *E,
-         unsigned TI, unsigned EI)
-      : SExpr(COP_Branch), Condition(C), ThenBlock(T), ElseBlock(E),
-        ThenIndex(TI), ElseIndex(EI)
-  {}
-
-  const SExpr *condition() const { return Condition; }
-  SExpr *condition() { return Condition; }
-
-  const BasicBlock *thenBlock() const { return ThenBlock; }
-  BasicBlock *thenBlock() { return ThenBlock; }
-
-  const BasicBlock *elseBlock() const { return ElseBlock; }
-  BasicBlock *elseBlock() { return ElseBlock; }
-
-  unsigned thenIndex() const { return ThenIndex; }
-  unsigned elseIndex() const { return ElseIndex; }
-
-  template <class V>
-  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
-    auto Nc = Vs.traverse(Condition, Vs.subExprCtx(Ctx));
-    BasicBlock *Ntb = Vs.reduceBasicBlockRef(ThenBlock);
-    BasicBlock *Nte = Vs.reduceBasicBlockRef(ElseBlock);
-    return Vs.reduceBranch(*this, Nc, Ntb, Nte);
-  }
-
-  template <class C> typename C::CType compare(Branch *E, C &Cmp) {
-    // TODO -- implement CFG comparisons
-    return Cmp.comparePointers(this, E);
-  }
-
-private:
-  SExpr *Condition;
-  BasicBlock *ThenBlock;
-  BasicBlock *ElseBlock;
-  unsigned ThenIndex;
-  unsigned ElseIndex;
-};
-
-
-// An identifier, e.g. 'foo' or 'x'.
-// This is a pseduo-term; it will be lowered to a variable or projection.
+/// An identifier, e.g. 'foo' or 'x'.
+/// This is a pseduo-term; it will be lowered to a variable or projection.
 class Identifier : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Identifier; }
@@ -1698,7 +1800,8 @@
     return Vs.reduceIdentifier(*this);
   }
 
-  template <class C> typename C::CType compare(Identifier* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Identifier* E, C& Cmp) const {
     return Cmp.compareStrings(name(), E->name());
   }
 
@@ -1707,8 +1810,8 @@
 };
 
 
-// An if-then-else expression.
-// This is a pseduo-term; it will be lowered to a branch in a CFG.
+/// An if-then-else expression.
+/// This is a pseduo-term; it will be lowered to a branch in a CFG.
 class IfThenElse : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_IfThenElse; }
@@ -1720,14 +1823,14 @@
     : SExpr(I), Condition(C), ThenExpr(T), ElseExpr(E)
   { }
 
-  SExpr *condition() { return Condition.get(); }   // Address to store to
-  const SExpr *condition() const { return Condition.get(); }
+  SExpr *condition() { return Condition; }   // Address to store to
+  const SExpr *condition() const { return Condition; }
 
-  SExpr *thenExpr() { return ThenExpr.get(); }     // Value to store
-  const SExpr *thenExpr() const { return ThenExpr.get(); }
+  SExpr *thenExpr() { return ThenExpr; }     // Value to store
+  const SExpr *thenExpr() const { return ThenExpr; }
 
-  SExpr *elseExpr() { return ElseExpr.get(); }     // Value to store
-  const SExpr *elseExpr() const { return ElseExpr.get(); }
+  SExpr *elseExpr() { return ElseExpr; }     // Value to store
+  const SExpr *elseExpr() const { return ElseExpr; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1737,7 +1840,8 @@
     return Vs.reduceIfThenElse(*this, Nc, Nt, Ne);
   }
 
-  template <class C> typename C::CType compare(IfThenElse* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const IfThenElse* E, C& Cmp) const {
     typename C::CType Ct = Cmp.compare(condition(), E->condition());
     if (Cmp.notTrue(Ct))
       return Ct;
@@ -1748,14 +1852,14 @@
   }
 
 private:
-  SExprRef Condition;
-  SExprRef ThenExpr;
-  SExprRef ElseExpr;
+  SExpr* Condition;
+  SExpr* ThenExpr;
+  SExpr* ElseExpr;
 };
 
 
-// A let-expression,  e.g.  let x=t; u.
-// This is a pseduo-term; it will be lowered to instructions in a CFG.
+/// A let-expression,  e.g.  let x=t; u.
+/// This is a pseduo-term; it will be lowered to instructions in a CFG.
 class Let : public SExpr {
 public:
   static bool classof(const SExpr *E) { return E->opcode() == COP_Let; }
@@ -1770,8 +1874,8 @@
   Variable *variableDecl()  { return VarDecl; }
   const Variable *variableDecl() const { return VarDecl; }
 
-  SExpr *body() { return Body.get(); }
-  const SExpr *body() const { return Body.get(); }
+  SExpr *body() { return Body; }
+  const SExpr *body() const { return Body; }
 
   template <class V>
   typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
@@ -1784,7 +1888,8 @@
     return Vs.reduceLet(*this, Nvd, E1);
   }
 
-  template <class C> typename C::CType compare(Let* E, C& Cmp) {
+  template <class C>
+  typename C::CType compare(const Let* E, C& Cmp) const {
     typename C::CType Ct =
       Cmp.compare(VarDecl->definition(), E->VarDecl->definition());
     if (Cmp.notTrue(Ct))
@@ -1797,17 +1902,18 @@
 
 private:
   Variable *VarDecl;
-  SExprRef Body;
+  SExpr* Body;
 };
 
 
 
-SExpr *getCanonicalVal(SExpr *E);
-void simplifyIncompleteArg(Variable *V, til::Phi *Ph);
+const SExpr *getCanonicalVal(const SExpr *E);
+SExpr* simplifyToCanonicalVal(SExpr *E);
+void simplifyIncompleteArg(til::Phi *Ph);
 
 
 } // end namespace til
 } // end namespace threadSafety
 } // end namespace clang
 
-#endif // LLVM_CLANG_THREAD_SAFETY_TIL_H
+#endif
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h b/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
index bc1490b..541f0bf 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
@@ -14,11 +14,13 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_THREAD_SAFETY_TRAVERSE_H
-#define LLVM_CLANG_THREAD_SAFETY_TRAVERSE_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTRAVERSE_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTRAVERSE_H
 
 #include "ThreadSafetyTIL.h"
 
+#include <ostream>
+
 namespace clang {
 namespace threadSafety {
 namespace til {
@@ -56,11 +58,16 @@
   // Traverse an expression -- returning a result of type R_SExpr.
   // Override this method to do something for every expression, regardless
   // of which kind it is.
-  typename R::R_SExpr traverse(SExprRef &E, typename R::R_Ctx Ctx) {
-    return traverse(E.get(), Ctx);
+  // E is a reference, so this can be use for in-place updates.
+  // The type T must be a subclass of SExpr.
+  template <class T>
+  typename R::R_SExpr traverse(T* &E, typename R::R_Ctx Ctx) {
+    return traverseSExpr(E, Ctx);
   }
 
-  typename R::R_SExpr traverse(SExpr *E, typename R::R_Ctx Ctx) {
+  // Override this method to do something for every expression.
+  // Does not allow in-place updates.
+  typename R::R_SExpr traverseSExpr(SExpr *E, typename R::R_Ctx Ctx) {
     return traverseByCase(E, Ctx);
   }
 
@@ -73,6 +80,7 @@
 #include "ThreadSafetyOps.def"
 #undef TIL_OPCODE_DEF
     }
+    return self()->reduceNull();
   }
 
 // Traverse e, by static dispatch on the type "X" of e.
@@ -90,10 +98,10 @@
 class SimpleReducerBase {
 public:
   enum TraversalKind {
-    TRV_Normal,
-    TRV_Decl,
-    TRV_Lazy,
-    TRV_Type
+    TRV_Normal,   // ordinary subexpressions
+    TRV_Decl,     // declarations (e.g. function bodies)
+    TRV_Lazy,     // expressions that require lazy evaluation
+    TRV_Type      // type expressions
   };
 
   // R_Ctx defines a "context" for the traversal, which encodes information
@@ -145,153 +153,6 @@
 };
 
 
-// Implements a traversal that makes a deep copy of an SExpr.
-// The default behavior of reduce##X(...) is to create a copy of the original.
-// Subclasses can override reduce##X to implement non-destructive rewriting
-// passes.
-template<class Self>
-class CopyReducer : public Traversal<Self, CopyReducerBase>,
-                    public CopyReducerBase {
-public:
-  CopyReducer(MemRegionRef A) : CopyReducerBase(A) {}
-
-public:
-  R_SExpr reduceNull() {
-    return nullptr;
-  }
-  // R_SExpr reduceFuture(...)  is never used.
-
-  R_SExpr reduceUndefined(Undefined &Orig) {
-    return new (Arena) Undefined(Orig);
-  }
-  R_SExpr reduceWildcard(Wildcard &Orig) {
-    return new (Arena) Wildcard(Orig);
-  }
-
-  R_SExpr reduceLiteral(Literal &Orig) {
-    return new (Arena) Literal(Orig);
-  }
-  template<class T>
-  R_SExpr reduceLiteralT(LiteralT<T> &Orig) {
-    return new (Arena) LiteralT<T>(Orig);
-  }
-  R_SExpr reduceLiteralPtr(LiteralPtr &Orig) {
-    return new (Arena) LiteralPtr(Orig);
-  }
-
-  R_SExpr reduceFunction(Function &Orig, Variable *Nvd, R_SExpr E0) {
-    return new (Arena) Function(Orig, Nvd, E0);
-  }
-  R_SExpr reduceSFunction(SFunction &Orig, Variable *Nvd, R_SExpr E0) {
-    return new (Arena) SFunction(Orig, Nvd, E0);
-  }
-  R_SExpr reduceCode(Code &Orig, R_SExpr E0, R_SExpr E1) {
-    return new (Arena) Code(Orig, E0, E1);
-  }
-  R_SExpr reduceField(Field &Orig, R_SExpr E0, R_SExpr E1) {
-    return new (Arena) Field(Orig, E0, E1);
-  }
-
-  R_SExpr reduceApply(Apply &Orig, R_SExpr E0, R_SExpr E1) {
-    return new (Arena) Apply(Orig, E0, E1);
-  }
-  R_SExpr reduceSApply(SApply &Orig, R_SExpr E0, R_SExpr E1) {
-    return new (Arena) SApply(Orig, E0, E1);
-  }
-  R_SExpr reduceProject(Project &Orig, R_SExpr E0) {
-    return new (Arena) Project(Orig, E0);
-  }
-  R_SExpr reduceCall(Call &Orig, R_SExpr E0) {
-    return new (Arena) Call(Orig, E0);
-  }
-
-  R_SExpr reduceAlloc(Alloc &Orig, R_SExpr E0) {
-    return new (Arena) Alloc(Orig, E0);
-  }
-  R_SExpr reduceLoad(Load &Orig, R_SExpr E0) {
-    return new (Arena) Load(Orig, E0);
-  }
-  R_SExpr reduceStore(Store &Orig, R_SExpr E0, R_SExpr E1) {
-    return new (Arena) Store(Orig, E0, E1);
-  }
-  R_SExpr reduceArrayIndex(ArrayIndex &Orig, R_SExpr E0, R_SExpr E1) {
-    return new (Arena) ArrayIndex(Orig, E0, E1);
-  }
-  R_SExpr reduceArrayAdd(ArrayAdd &Orig, R_SExpr E0, R_SExpr E1) {
-    return new (Arena) ArrayAdd(Orig, E0, E1);
-  }
-  R_SExpr reduceUnaryOp(UnaryOp &Orig, R_SExpr E0) {
-    return new (Arena) UnaryOp(Orig, E0);
-  }
-  R_SExpr reduceBinaryOp(BinaryOp &Orig, R_SExpr E0, R_SExpr E1) {
-    return new (Arena) BinaryOp(Orig, E0, E1);
-  }
-  R_SExpr reduceCast(Cast &Orig, R_SExpr E0) {
-    return new (Arena) Cast(Orig, E0);
-  }
-
-  R_SExpr reduceSCFG(SCFG &Orig, Container<BasicBlock *> &Bbs) {
-    return nullptr;  // FIXME: implement CFG rewriting
-  }
-  R_BasicBlock reduceBasicBlock(BasicBlock &Orig, Container<Variable *> &As,
-                                Container<Variable *> &Is, R_SExpr T) {
-    return nullptr;  // FIXME: implement CFG rewriting
-  }
-  R_SExpr reducePhi(Phi &Orig, Container<R_SExpr> &As) {
-    return new (Arena) Phi(Orig, std::move(As.Elems));
-  }
-  R_SExpr reduceGoto(Goto &Orig, BasicBlock *B) {
-    return new (Arena) Goto(Orig, B, 0);  // FIXME: set index
-  }
-  R_SExpr reduceBranch(Branch &O, R_SExpr C, BasicBlock *B0, BasicBlock *B1) {
-    return new (Arena) Branch(O, C, B0, B1, 0, 0);  // FIXME: set indices
-  }
-
-  R_SExpr reduceIdentifier(Identifier &Orig) {
-    return new (Arena) Identifier(Orig);
-  }
-  R_SExpr reduceIfThenElse(IfThenElse &Orig, R_SExpr C, R_SExpr T, R_SExpr E) {
-    return new (Arena) IfThenElse(Orig, C, T, E);
-  }
-  R_SExpr reduceLet(Let &Orig, Variable *Nvd, R_SExpr B) {
-    return new (Arena) Let(Orig, Nvd, B);
-  }
-
-  // Create a new variable from orig, and push it onto the lexical scope.
-  Variable *enterScope(Variable &Orig, R_SExpr E0) {
-    return new (Arena) Variable(Orig, E0);
-  }
-  // Exit the lexical scope of orig.
-  void exitScope(const Variable &Orig) {}
-
-  void enterCFG(SCFG &Cfg) {}
-  void exitCFG(SCFG &Cfg) {}
-  void enterBasicBlock(BasicBlock &BB) {}
-  void exitBasicBlock(BasicBlock &BB) {}
-
-  // Map Variable references to their rewritten definitions.
-  Variable *reduceVariableRef(Variable *Ovd) { return Ovd; }
-
-  // Map BasicBlock references to their rewritten definitions.
-  BasicBlock *reduceBasicBlockRef(BasicBlock *Obb) { return Obb; }
-};
-
-
-class SExprCopier : public CopyReducer<SExprCopier> {
-public:
-  typedef SExpr *R_SExpr;
-
-  SExprCopier(MemRegionRef A) : CopyReducer(A) { }
-
-  // Create a copy of e in region a.
-  static SExpr *copy(SExpr *E, MemRegionRef A) {
-    SExprCopier Copier(A);
-    return Copier.traverse(E, TRV_Normal);
-  }
-};
-
-
-
 // Base class for visit traversals.
 class VisitReducerBase : public SimpleReducerBase {
 public:
@@ -366,8 +227,8 @@
   R_SExpr reduceSCFG(SCFG &Orig, Container<BasicBlock *> Bbs) {
     return Bbs.Success;
   }
-  R_BasicBlock reduceBasicBlock(BasicBlock &Orig, Container<Variable *> &As,
-                                Container<Variable *> &Is, R_SExpr T) {
+  R_BasicBlock reduceBasicBlock(BasicBlock &Orig, Container<R_SExpr> &As,
+                                Container<R_SExpr> &Is, R_SExpr T) {
     return (As.Success && Is.Success && T);
   }
   R_SExpr reducePhi(Phi &Orig, Container<R_SExpr> &As) {
@@ -379,6 +240,9 @@
   R_SExpr reduceBranch(Branch &O, R_SExpr C, BasicBlock *B0, BasicBlock *B1) {
     return C;
   }
+  R_SExpr reduceReturn(Return &O, R_SExpr E) {
+    return E;
+  }
 
   R_SExpr reduceIdentifier(Identifier &Orig) {
     return true;
@@ -423,7 +287,7 @@
   Self *self() { return reinterpret_cast<Self *>(this); }
 
 public:
-  bool compareByCase(SExpr *E1, SExpr* E2) {
+  bool compareByCase(const SExpr *E1, const SExpr* E2) {
     switch (E1->opcode()) {
 #define TIL_OPCODE_DEF(X)                                                     \
     case COP_##X:                                                             \
@@ -431,6 +295,7 @@
 #include "ThreadSafetyOps.def"
 #undef TIL_OPCODE_DEF
     }
+    return false;
   }
 };
 
@@ -449,38 +314,86 @@
   bool compareStrings (StringRef s, StringRef r)     { return s == r; }
   bool comparePointers(const void* P, const void* Q) { return P == Q; }
 
-  bool compare(SExpr *E1, SExpr* E2) {
+  bool compare(const SExpr *E1, const SExpr* E2) {
     if (E1->opcode() != E2->opcode())
       return false;
     return compareByCase(E1, E2);
   }
 
   // TODO -- handle alpha-renaming of variables
-  void enterScope(Variable* V1, Variable* V2) { }
+  void enterScope(const Variable* V1, const Variable* V2) { }
   void leaveScope() { }
 
-  bool compareVariableRefs(Variable* V1, Variable* V2) {
+  bool compareVariableRefs(const Variable* V1, const Variable* V2) {
     return V1 == V2;
   }
 
-  static bool compareExprs(SExpr *E1, SExpr* E2) {
+  static bool compareExprs(const SExpr *E1, const SExpr* E2) {
     EqualsComparator Eq;
     return Eq.compare(E1, E2);
   }
 };
 
 
+
+class MatchComparator : public Comparator<MatchComparator> {
+public:
+  // Result type for the comparison, e.g. bool for simple equality,
+  // or int for lexigraphic comparison (-1, 0, 1).  Must have one value which
+  // denotes "true".
+  typedef bool CType;
+
+  CType trueResult() { return true; }
+  bool notTrue(CType ct) { return !ct; }
+
+  bool compareIntegers(unsigned i, unsigned j)       { return i == j; }
+  bool compareStrings (StringRef s, StringRef r)     { return s == r; }
+  bool comparePointers(const void* P, const void* Q) { return P == Q; }
+
+  bool compare(const SExpr *E1, const SExpr* E2) {
+    // Wildcards match anything.
+    if (E1->opcode() == COP_Wildcard || E2->opcode() == COP_Wildcard)
+      return true;
+    // otherwise normal equality.
+    if (E1->opcode() != E2->opcode())
+      return false;
+    return compareByCase(E1, E2);
+  }
+
+  // TODO -- handle alpha-renaming of variables
+  void enterScope(const Variable* V1, const Variable* V2) { }
+  void leaveScope() { }
+
+  bool compareVariableRefs(const Variable* V1, const Variable* V2) {
+    return V1 == V2;
+  }
+
+  static bool compareExprs(const SExpr *E1, const SExpr* E2) {
+    MatchComparator Matcher;
+    return Matcher.compare(E1, E2);
+  }
+};
+
+
+
+// inline std::ostream& operator<<(std::ostream& SS, StringRef R) {
+//   return SS.write(R.data(), R.size());
+// }
+
 // Pretty printer for TIL expressions
 template <typename Self, typename StreamType>
 class PrettyPrinter {
 private:
   bool Verbose;  // Print out additional information
   bool Cleanup;  // Omit redundant decls.
+  bool CStyle;   // Print exprs in C-like syntax.
 
 public:
-  PrettyPrinter(bool V = false, bool C = true) : Verbose(V), Cleanup(C) { }
+  PrettyPrinter(bool V = false, bool C = true, bool CS = true)
+     : Verbose(V), Cleanup(C), CStyle(CS)
+  {}
 
-  static void print(SExpr *E, StreamType &SS) {
+  static void print(const SExpr *E, StreamType &SS) {
     Self printer;
     printer.printSExpr(E, SS, Prec_MAX);
   }
@@ -502,7 +415,7 @@
   static const unsigned Prec_MAX = 6;
 
   // Return the precedence of a given node, for use in pretty printing.
-  unsigned precedence(SExpr *E) {
+  unsigned precedence(const SExpr *E) {
     switch (E->opcode()) {
       case COP_Future:     return Prec_Atom;
       case COP_Undefined:  return Prec_Atom;
@@ -529,13 +442,14 @@
 
       case COP_UnaryOp:    return Prec_Unary;
       case COP_BinaryOp:   return Prec_Binary;
-      case COP_Cast:       return Prec_Unary;
+      case COP_Cast:       return Prec_Atom;
 
       case COP_SCFG:       return Prec_Decl;
       case COP_BasicBlock: return Prec_MAX;
       case COP_Phi:        return Prec_Atom;
       case COP_Goto:       return Prec_Atom;
       case COP_Branch:     return Prec_Atom;
+      case COP_Return:     return Prec_Other;
 
       case COP_Identifier: return Prec_Atom;
       case COP_IfThenElse: return Prec_Other;
@@ -544,22 +458,29 @@
     return Prec_MAX;
   }
 
-  void printBlockLabel(StreamType & SS, BasicBlock *BB, unsigned index) {
+  void printBlockLabel(StreamType & SS, const BasicBlock *BB, int index) {
     if (!BB) {
       SS << "BB_null";
       return;
     }
     SS << "BB_";
     SS << BB->blockID();
-    SS << ":";
-    SS << index;
+    if (index >= 0) {
+      SS << ":";
+      SS << index;
+    }
   }
 
-  void printSExpr(SExpr *E, StreamType &SS, unsigned P) {
+
+  void printSExpr(const SExpr *E, StreamType &SS, unsigned P, bool Sub=true) {
     if (!E) {
       self()->printNull(SS);
       return;
     }
+    if (Sub && E->block() && E->opcode() != COP_Variable) {
+      SS << "_x" << E->id();
+      return;
+    }
     if (self()->precedence(E) > P) {
       // Wrap expr in () if necessary.
       SS << "(";
@@ -582,28 +503,28 @@
     SS << "#null";
   }
 
-  void printFuture(Future *E, StreamType &SS) {
+  void printFuture(const Future *E, StreamType &SS) {
     self()->printSExpr(E->maybeGetResult(), SS, Prec_Atom);
   }
 
-  void printUndefined(Undefined *E, StreamType &SS) {
+  void printUndefined(const Undefined *E, StreamType &SS) {
     SS << "#undefined";
   }
 
-  void printWildcard(Wildcard *E, StreamType &SS) {
-    SS << "_";
+  void printWildcard(const Wildcard *E, StreamType &SS) {
+    SS << "*";
   }
 
   template<class T>
-  void printLiteralT(LiteralT<T> *E, StreamType &SS) {
+  void printLiteralT(const LiteralT<T> *E, StreamType &SS) {
     SS << E->value();
   }
 
-  void printLiteralT(LiteralT<uint8_t> *E, StreamType &SS) {
+  void printLiteralT(const LiteralT<uint8_t> *E, StreamType &SS) {
     SS << "'" << E->value() << "'";
   }
 
-  void printLiteral(Literal *E, StreamType &SS) {
+  void printLiteral(const Literal *E, StreamType &SS) {
     if (E->clangExpr()) {
       SS << getSourceLiteralString(E->clangExpr());
       return;
@@ -685,25 +606,18 @@
     SS << "#lit";
   }
 
-  void printLiteralPtr(LiteralPtr *E, StreamType &SS) {
+  void printLiteralPtr(const LiteralPtr *E, StreamType &SS) {
     SS << E->clangDecl()->getNameAsString();
   }
 
-  void printVariable(Variable *V, StreamType &SS, bool IsVarDecl = false) {
-    if (!IsVarDecl && Cleanup) {
-      SExpr* E = getCanonicalVal(V);
-      if (E != V) {
-        printSExpr(E, SS, Prec_Atom);
-        return;
-      }
-    }
-    if (V->kind() == Variable::VK_LetBB)
-      SS << V->name() << V->getBlockID() << "_" << V->getID();
+  void printVariable(const Variable *V, StreamType &SS, bool IsVarDecl=false) {
+    if (CStyle && V->kind() == Variable::VK_SFun)
+      SS << "this";
     else
-      SS << V->name() << V->getID();
+      SS << V->name() << V->id();
   }
 
-  void printFunction(Function *E, StreamType &SS, unsigned sugared = 0) {
+  void printFunction(const Function *E, StreamType &SS, unsigned sugared = 0) {
     switch (sugared) {
       default:
         SS << "\\(";   // Lambda
@@ -719,7 +633,7 @@
     SS << ": ";
     self()->printSExpr(E->variableDecl()->definition(), SS, Prec_MAX);
 
-    SExpr *B = E->body();
+    const SExpr *B = E->body();
     if (B && B->opcode() == COP_Function)
       self()->printFunction(cast<Function>(B), SS, 2);
     else {
@@ -728,29 +642,29 @@
     }
   }
 
-  void printSFunction(SFunction *E, StreamType &SS) {
+  void printSFunction(const SFunction *E, StreamType &SS) {
     SS << "@";
     self()->printVariable(E->variableDecl(), SS, true);
     SS << " ";
     self()->printSExpr(E->body(), SS, Prec_Decl);
   }
 
-  void printCode(Code *E, StreamType &SS) {
+  void printCode(const Code *E, StreamType &SS) {
     SS << ": ";
     self()->printSExpr(E->returnType(), SS, Prec_Decl-1);
     SS << " -> ";
     self()->printSExpr(E->body(), SS, Prec_Decl);
   }
 
-  void printField(Field *E, StreamType &SS) {
+  void printField(const Field *E, StreamType &SS) {
     SS << ": ";
     self()->printSExpr(E->range(), SS, Prec_Decl-1);
     SS << " = ";
     self()->printSExpr(E->body(), SS, Prec_Decl);
   }
 
-  void printApply(Apply *E, StreamType &SS, bool sugared = false) {
-    SExpr *F = E->fun();
+  void printApply(const Apply *E, StreamType &SS, bool sugared = false) {
+    const SExpr *F = E->fun();
     if (F->opcode() == COP_Apply) {
       printApply(cast<Apply>(F), SS, true);
       SS << ", ";
@@ -763,7 +677,7 @@
       SS << ")$";
   }
 
-  void printSApply(SApply *E, StreamType &SS) {
+  void printSApply(const SApply *E, StreamType &SS) {
     self()->printSExpr(E->sfun(), SS, Prec_Postfix);
     if (E->isDelegation()) {
       SS << "@(";
@@ -772,14 +686,36 @@
     }
   }
 
-  void printProject(Project *E, StreamType &SS) {
+  void printProject(const Project *E, StreamType &SS) {
+    if (CStyle) {
+      // Omit the  this->
+      if (const SApply *SAP = dyn_cast<SApply>(E->record())) {
+        if (const Variable *V = dyn_cast<Variable>(SAP->sfun())) {
+          if (!SAP->isDelegation() && V->kind() == Variable::VK_SFun) {
+            SS << E->slotName();
+            return;
+          }
+        }
+      }
+      if (isa<Wildcard>(E->record())) {
+        // handle existentials
+        SS << "&";
+        SS << E->clangDecl()->getQualifiedNameAsString();
+        return;
+      }
+    }
     self()->printSExpr(E->record(), SS, Prec_Postfix);
-    SS << ".";
+    if (CStyle && E->isArrow()) {
+      SS << "->";
+    }
+    else {
+      SS << ".";
+    }
     SS << E->slotName();
   }
 
-  void printCall(Call *E, StreamType &SS) {
-    SExpr *T = E->target();
+  void printCall(const Call *E, StreamType &SS) {
+    const SExpr *T = E->target();
     if (T->opcode() == COP_Apply) {
       self()->printApply(cast<Apply>(T), SS, true);
       SS << ")";
@@ -790,52 +726,60 @@
     }
   }
 
-  void printAlloc(Alloc *E, StreamType &SS) {
+  void printAlloc(const Alloc *E, StreamType &SS) {
     SS << "new ";
     self()->printSExpr(E->dataType(), SS, Prec_Other-1);
   }
 
-  void printLoad(Load *E, StreamType &SS) {
+  void printLoad(const Load *E, StreamType &SS) {
     self()->printSExpr(E->pointer(), SS, Prec_Postfix);
-    SS << "^";
+    if (!CStyle)
+      SS << "^";
   }
 
-  void printStore(Store *E, StreamType &SS) {
+  void printStore(const Store *E, StreamType &SS) {
     self()->printSExpr(E->destination(), SS, Prec_Other-1);
     SS << " := ";
     self()->printSExpr(E->source(), SS, Prec_Other-1);
   }
 
-  void printArrayIndex(ArrayIndex *E, StreamType &SS) {
+  void printArrayIndex(const ArrayIndex *E, StreamType &SS) {
     self()->printSExpr(E->array(), SS, Prec_Postfix);
     SS << "[";
     self()->printSExpr(E->index(), SS, Prec_MAX);
     SS << "]";
   }
 
-  void printArrayAdd(ArrayAdd *E, StreamType &SS) {
+  void printArrayAdd(const ArrayAdd *E, StreamType &SS) {
     self()->printSExpr(E->array(), SS, Prec_Postfix);
     SS << " + ";
     self()->printSExpr(E->index(), SS, Prec_Atom);
   }
 
-  void printUnaryOp(UnaryOp *E, StreamType &SS) {
+  void printUnaryOp(const UnaryOp *E, StreamType &SS) {
     SS << getUnaryOpcodeString(E->unaryOpcode());
     self()->printSExpr(E->expr(), SS, Prec_Unary);
   }
 
-  void printBinaryOp(BinaryOp *E, StreamType &SS) {
+  void printBinaryOp(const BinaryOp *E, StreamType &SS) {
     self()->printSExpr(E->expr0(), SS, Prec_Binary-1);
     SS << " " << getBinaryOpcodeString(E->binaryOpcode()) << " ";
     self()->printSExpr(E->expr1(), SS, Prec_Binary-1);
   }
 
-  void printCast(Cast *E, StreamType &SS) {
-    SS << "%";
+  void printCast(const Cast *E, StreamType &SS) {
+    if (!CStyle) {
+      SS << "cast[";
+      SS << E->castOpcode();
+      SS << "](";
+      self()->printSExpr(E->expr(), SS, Prec_Unary);
+      SS << ")";
+      return;
+    }
     self()->printSExpr(E->expr(), SS, Prec_Unary);
   }
 
-  void printSCFG(SCFG *E, StreamType &SS) {
+  void printSCFG(const SCFG *E, StreamType &SS) {
     SS << "CFG {\n";
     for (auto BBI : *E) {
       printBasicBlock(BBI, SS);
@@ -844,39 +788,45 @@
     newline(SS);
   }
 
-  void printBasicBlock(BasicBlock *E, StreamType &SS) {
+
+  void printBBInstr(const SExpr *E, StreamType &SS) {
+    bool Sub = false;
+    if (E->opcode() == COP_Variable) {
+      auto *V = cast<Variable>(E);
+      SS << "let " << V->name() << V->id() << " = ";
+      E = V->definition();
+      Sub = true;
+    }
+    else if (E->opcode() != COP_Store) {
+      SS << "let _x" << E->id() << " = ";
+    }
+    self()->printSExpr(E, SS, Prec_MAX, Sub);
+    SS << ";";
+    newline(SS);
+  }
+
+  void printBasicBlock(const BasicBlock *E, StreamType &SS) {
     SS << "BB_" << E->blockID() << ":";
     if (E->parent())
       SS << " BB_" << E->parent()->blockID();
     newline(SS);
-    for (auto *A : E->arguments()) {
-      SS << "let ";
-      self()->printVariable(A, SS, true);
-      SS << " = ";
-      self()->printSExpr(A->definition(), SS, Prec_MAX);
-      SS << ";";
-      newline(SS);
-    }
-    for (auto *I : E->instructions()) {
-      if (I->definition()->opcode() != COP_Store) {
-        SS << "let ";
-        self()->printVariable(I, SS, true);
-        SS << " = ";
-      }
-      self()->printSExpr(I->definition(), SS, Prec_MAX);
-      SS << ";";
-      newline(SS);
-    }
-    SExpr *T = E->terminator();
+
+    for (auto *A : E->arguments())
+      printBBInstr(A, SS);
+
+    for (auto *I : E->instructions())
+      printBBInstr(I, SS);
+
+    const SExpr *T = E->terminator();
     if (T) {
-      self()->printSExpr(T, SS, Prec_MAX);
+      self()->printSExpr(T, SS, Prec_MAX, false);
       SS << ";";
       newline(SS);
     }
     newline(SS);
   }
 
-  void printPhi(Phi *E, StreamType &SS) {
+  void printPhi(const Phi *E, StreamType &SS) {
     SS << "phi(";
     if (E->status() == Phi::PH_SingleVal)
       self()->printSExpr(E->values()[0], SS, Prec_MAX);
@@ -891,25 +841,38 @@
     SS << ")";
   }
 
-  void printGoto(Goto *E, StreamType &SS) {
+  void printGoto(const Goto *E, StreamType &SS) {
     SS << "goto ";
     printBlockLabel(SS, E->targetBlock(), E->index());
   }
 
-  void printBranch(Branch *E, StreamType &SS) {
+  void printBranch(const Branch *E, StreamType &SS) {
     SS << "branch (";
     self()->printSExpr(E->condition(), SS, Prec_MAX);
     SS << ") ";
-    printBlockLabel(SS, E->thenBlock(), E->thenIndex());
+    printBlockLabel(SS, E->thenBlock(), -1);
     SS << " ";
-    printBlockLabel(SS, E->elseBlock(), E->elseIndex());
+    printBlockLabel(SS, E->elseBlock(), -1);
   }
 
-  void printIdentifier(Identifier *E, StreamType &SS) {
+  void printReturn(const Return *E, StreamType &SS) {
+    SS << "return ";
+    self()->printSExpr(E->returnValue(), SS, Prec_Other);
+  }
+
+  void printIdentifier(const Identifier *E, StreamType &SS) {
     SS << E->name();
   }
 
-  void printIfThenElse(IfThenElse *E, StreamType &SS) {
+  void printIfThenElse(const IfThenElse *E, StreamType &SS) {
+    if (CStyle) {
+      printSExpr(E->condition(), SS, Prec_Unary);
+      SS << " ? ";
+      printSExpr(E->thenExpr(), SS, Prec_Unary);
+      SS << " : ";
+      printSExpr(E->elseExpr(), SS, Prec_Unary);
+      return;
+    }
     SS << "if (";
     printSExpr(E->condition(), SS, Prec_MAX);
     SS << ") then ";
@@ -918,7 +881,7 @@
     printSExpr(E->elseExpr(), SS, Prec_Other);
   }
 
-  void printLet(Let *E, StreamType &SS) {
+  void printLet(const Let *E, StreamType &SS) {
     SS << "let ";
     printVariable(E->variableDecl(), SS, true);
     SS << " = ";
@@ -929,6 +892,10 @@
 };
 
 
+class StdPrinter : public PrettyPrinter<StdPrinter, std::ostream> { };
+
+
+
 } // end namespace til
 } // end namespace threadSafety
 } // end namespace clang
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyUtil.h b/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
index 31200a3..5a75724 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
@@ -11,8 +11,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_THREAD_SAFETY_UTIL_H
-#define LLVM_CLANG_THREAD_SAFETY_UTIL_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYUTIL_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYUTIL_H
 
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/AlignOf.h"
@@ -24,6 +24,7 @@
 #include <cstddef>
 #include <vector>
 #include <utility>
+#include <ostream>
 
 namespace clang {
 namespace threadSafety {
@@ -142,18 +143,35 @@
     assert(i < Size && "Array index out of bounds.");
     return Data[i];
   }
+  T &back() {
+    assert(Size && "No elements in the array.");
+    return Data[Size - 1];
+  }
+  const T &back() const {
+    assert(Size && "No elements in the array.");
+    return Data[Size - 1];
+  }
 
   iterator begin() { return Data; }
-  iterator end() { return Data + Size; }
+  iterator end()   { return Data + Size; }
+
+  const_iterator begin() const { return Data; }
+  const_iterator end()   const { return Data + Size; }
 
   const_iterator cbegin() const { return Data; }
-  const_iterator cend() const { return Data + Size; }
+  const_iterator cend()   const { return Data + Size; }
 
   void push_back(const T &Elem) {
     assert(Size < Capacity);
     Data[Size++] = Elem;
   }
 
+  // drop last n elements from array
+  void drop(unsigned n = 0) {
+    assert(Size > n);
+    Size -= n;
+  }
+
   void setValues(unsigned Sz, const T& C) {
     assert(Sz <= Capacity);
     Size = Sz;
@@ -171,6 +189,37 @@
     return J - Osz;
   }
 
+  // An adaptor to reverse a simple array
+  class ReverseAdaptor {
+   public:
+    ReverseAdaptor(SimpleArray &Array) : Array(Array) {}
+    // A reverse iterator used by the reverse adaptor
+    class Iterator {
+     public:
+      Iterator(T *Data) : Data(Data) {}
+      T &operator*() { return *Data; }
+      const T &operator*() const { return *Data; }
+      Iterator &operator++() {
+        --Data;
+        return *this;
+      }
+      bool operator!=(Iterator Other) { return Data != Other.Data; }
+
+     private:
+      T *Data;
+    };
+    Iterator begin() { return Array.end() - 1; }
+    Iterator end() { return Array.begin() - 1; }
+    const Iterator begin() const { return Array.end() - 1; }
+    const Iterator end() const { return Array.begin() - 1; }
+
+   private:
+    SimpleArray &Array;
+  };
+
+  const ReverseAdaptor reverse() const { return ReverseAdaptor(*this); }
+  ReverseAdaptor reverse() { return ReverseAdaptor(*this); }
+
 private:
   // std::max is annoying here, because it requires a reference,
   // thus forcing InitialCapacity to be initialized outside the .h file.
@@ -185,6 +234,7 @@
   size_t Capacity;
 };
 
+
 }  // end namespace til
 
 
@@ -310,6 +360,11 @@
 };
 
 
+inline std::ostream& operator<<(std::ostream& ss, const StringRef str) {
+  return ss.write(str.data(), str.size());
+}
+
+
 } // end namespace threadSafety
 } // end namespace clang
 
diff --git a/include/clang/Analysis/Analyses/UninitializedValues.h b/include/clang/Analysis/Analyses/UninitializedValues.h
index 188722d..53ff20c 100644
--- a/include/clang/Analysis/Analyses/UninitializedValues.h
+++ b/include/clang/Analysis/Analyses/UninitializedValues.h
@@ -12,8 +12,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_UNINIT_VALS_H
-#define LLVM_CLANG_UNINIT_VALS_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_UNINITIALIZEDVALUES_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_UNINITIALIZEDVALUES_H
 
 #include "clang/AST/Stmt.h"
 #include "llvm/ADT/SmallVector.h"
diff --git a/include/clang/Analysis/AnalysisContext.h b/include/clang/Analysis/AnalysisContext.h
index 08e3354..0ebdf15 100644
--- a/include/clang/Analysis/AnalysisContext.h
+++ b/include/clang/Analysis/AnalysisContext.h
@@ -17,6 +17,7 @@
 
 #include "clang/AST/Decl.h"
 #include "clang/Analysis/CFG.h"
+#include "clang/Analysis/CodeInjector.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/Support/Allocator.h"
@@ -143,6 +144,14 @@
   /// \sa getBody
   bool isBodyAutosynthesized() const;
 
+  /// \brief Checks if the body of the Decl is generated by the BodyFarm from a
+  /// model file.
+  ///
+  /// Note, the lookup is not free. We are going to call getBody behind
+  /// the scenes.
+  /// \sa getBody
+  bool isBodyAutosynthesizedFromModelFile() const;
+
   CFG *getCFG();
 
   CFGStmtMap *getCFGStmtMap();
@@ -398,6 +407,10 @@
   ContextMap Contexts;
   LocationContextManager LocContexts;
   CFG::BuildOptions cfgBuildOptions;
+
+  /// Pointer to an interface that can provide function bodies for
+  /// declarations from external source.
+  std::unique_ptr<CodeInjector> Injector;
   
   /// Flag to indicate whether or not bodies should be synthesized
   /// for well-known functions.
@@ -410,7 +423,8 @@
                              bool addTemporaryDtors = false,
                              bool synthesizeBodies = false,
                              bool addStaticInitBranches = false,
-                             bool addCXXNewAllocator = true);
+                             bool addCXXNewAllocator = true,
+                             CodeInjector* injector = nullptr);
 
   ~AnalysisDeclContextManager();
 
diff --git a/include/clang/Analysis/AnalysisDiagnostic.h b/include/clang/Analysis/AnalysisDiagnostic.h
index 33c940e..8d28971 100644
--- a/include/clang/Analysis/AnalysisDiagnostic.h
+++ b/include/clang/Analysis/AnalysisDiagnostic.h
@@ -7,8 +7,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_DIAGNOSTICANALYSIS_H
-#define LLVM_CLANG_DIAGNOSTICANALYSIS_H
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSISDIAGNOSTIC_H
+#define LLVM_CLANG_ANALYSIS_ANALYSISDIAGNOSTIC_H
 
 #include "clang/Basic/Diagnostic.h"
 
diff --git a/include/clang/Analysis/CFG.h b/include/clang/Analysis/CFG.h
index 891fb90..beea867 100644
--- a/include/clang/Analysis/CFG.h
+++ b/include/clang/Analysis/CFG.h
@@ -12,8 +12,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_CFG_H
-#define LLVM_CLANG_CFG_H
+#ifndef LLVM_CLANG_ANALYSIS_CFG_H
+#define LLVM_CLANG_ANALYSIS_CFG_H
 
 #include "clang/AST/Stmt.h"
 #include "clang/Analysis/Support/BumpVector.h"
@@ -811,10 +811,9 @@
     ImplTy I;
   };
 
-  /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
-  ///   constructed CFG belongs to the caller.
-  static CFG* buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
-                       const BuildOptions &BO);
+  /// buildCFG - Builds a CFG from an AST.
+  static std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
+                                       const BuildOptions &BO);
 
   /// createBlock - Create a new block in the CFG.  The CFG owns the block;
   ///  the caller should not directly free it.
diff --git a/include/clang/Analysis/CFGStmtMap.h b/include/clang/Analysis/CFGStmtMap.h
index 6e8e140..4dfa91d 100644
--- a/include/clang/Analysis/CFGStmtMap.h
+++ b/include/clang/Analysis/CFGStmtMap.h
@@ -12,8 +12,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_CFGSTMTMAP_H
-#define LLVM_CLANG_CFGSTMTMAP_H
+#ifndef LLVM_CLANG_ANALYSIS_CFGSTMTMAP_H
+#define LLVM_CLANG_ANALYSIS_CFGSTMTMAP_H
 
 #include "clang/Analysis/CFG.h"
 
diff --git a/include/clang/Analysis/CallGraph.h b/include/clang/Analysis/CallGraph.h
index 593ba57..eda22a5 100644
--- a/include/clang/Analysis/CallGraph.h
+++ b/include/clang/Analysis/CallGraph.h
@@ -14,8 +14,8 @@
 //  edges to all externally available functions.
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_CLANG_ANALYSIS_CALLGRAPH
-#define LLVM_CLANG_ANALYSIS_CALLGRAPH
+#ifndef LLVM_CLANG_ANALYSIS_CALLGRAPH_H
+#define LLVM_CLANG_ANALYSIS_CALLGRAPH_H
 
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/RecursiveASTVisitor.h"
diff --git a/include/clang/Analysis/CodeInjector.h b/include/clang/Analysis/CodeInjector.h
new file mode 100644
index 0000000..413a55b
--- /dev/null
+++ b/include/clang/Analysis/CodeInjector.h
@@ -0,0 +1,46 @@
+//===-- CodeInjector.h ------------------------------------------*- C++ -*-===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief Defines the clang::CodeInjector interface which is responsible for
+/// injecting AST of function definitions that may not be available in the
+/// original source.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_ANALYSIS_CODEINJECTOR_H
+#define LLVM_CLANG_ANALYSIS_CODEINJECTOR_H
+
+namespace clang {
+
+class Stmt;
+class FunctionDecl;
+class ObjCMethodDecl;
+
+/// \brief CodeInjector is an interface which is responsible for injecting AST
+/// of function definitions that may not be available in the original source.
+///
+/// The getBody function will be called each time the static analyzer examines a
+/// function call that has no definition available in the current translation
+/// unit. If the returned statement is not a null pointer, it is assumed to be
+/// the body of a function which will be used for the analysis. The source of
+/// the body can be arbitrary, but it is advised to use memoization to avoid
+/// unnecessary reparsing of the external source that provides the body of the
+/// functions.
+class CodeInjector {
+public:
+  CodeInjector();
+  virtual ~CodeInjector();
+
+  virtual Stmt *getBody(const FunctionDecl *D) = 0;
+  virtual Stmt *getBody(const ObjCMethodDecl *D) = 0;
+};
+}
+
+#endif
diff --git a/include/clang/Analysis/DomainSpecific/CocoaConventions.h b/include/clang/Analysis/DomainSpecific/CocoaConventions.h
index e6a2f13..8b3fcff 100644
--- a/include/clang/