[clang] [CIR] Add binary operators (PR #132420)

Morris Hafner via cfe-commits cfe-commits at lists.llvm.org
Tue Mar 25 12:20:56 PDT 2025


https://github.com/mmha updated https://github.com/llvm/llvm-project/pull/132420

>From 706c944045b8f156942c1b08a8418498b4c12d78 Mon Sep 17 00:00:00 2001
From: Morris Hafner <mhafner at nvidia.com>
Date: Fri, 21 Mar 2025 17:55:00 +0100
Subject: [PATCH 01/11] [CIR] Add binary operators

This patch adds upstreams support for BinOp and BinOverflowOp including lvalue assignments and rudimentary support for pointer arithmetic. Note that this does not include ternary ops, ShiftOp and SelectOp which are required for logical binary operators.
---
 .../CIR/Dialect/Builder/CIRBaseBuilder.h      | 114 ++-
 clang/include/clang/CIR/Dialect/IR/CIROps.td  | 123 +++
 clang/include/clang/CIR/Dialect/IR/CIRTypes.h |   1 +
 clang/include/clang/CIR/MissingFeatures.h     |  13 +-
 clang/lib/CIR/CodeGen/CIRGenBuilder.h         | 116 ++-
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp          |  64 +-
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp    | 730 +++++++++++++++++-
 clang/lib/CIR/CodeGen/CIRGenFunction.cpp      |   2 +
 clang/lib/CIR/CodeGen/CIRGenFunction.h        |  30 +-
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp       |  41 +-
 clang/lib/CIR/Dialect/IR/CIRTypes.cpp         |  10 +
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 243 +++++-
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.h   |  33 +
 clang/test/CIR/CodeGen/binop.cpp              |  33 +
 clang/test/CIR/Lowering/binop-bool.cir        |  18 +
 clang/test/CIR/Lowering/binop-fp.cir          |  68 ++
 clang/test/CIR/Lowering/binop-overflow.cir    |  63 ++
 clang/test/CIR/Lowering/binop-signed-int.cir  |  60 ++
 .../test/CIR/Lowering/binop-unsigned-int.cir  |  73 ++
 19 files changed, 1794 insertions(+), 41 deletions(-)
 create mode 100644 clang/test/CIR/CodeGen/binop.cpp
 create mode 100644 clang/test/CIR/Lowering/binop-bool.cir
 create mode 100644 clang/test/CIR/Lowering/binop-fp.cir
 create mode 100644 clang/test/CIR/Lowering/binop-overflow.cir
 create mode 100644 clang/test/CIR/Lowering/binop-signed-int.cir
 create mode 100644 clang/test/CIR/Lowering/binop-unsigned-int.cir

diff --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index c6aea10d46b63..9fe80cde261a9 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -10,7 +10,6 @@
 #define LLVM_CLANG_CIR_DIALECT_BUILDER_CIRBASEBUILDER_H
 
 #include "clang/AST/CharUnits.h"
-#include "clang/AST/Type.h"
 #include "clang/CIR/Dialect/IR/CIRAttrs.h"
 #include "clang/CIR/Dialect/IR/CIRDialect.h"
 #include "clang/CIR/Dialect/IR/CIRTypes.h"
@@ -28,6 +27,11 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
   CIRBaseBuilderTy(mlir::MLIRContext &mlirContext)
       : mlir::OpBuilder(&mlirContext) {}
 
+  mlir::Value getConstAPInt(mlir::Location loc, mlir::Type typ,
+                            const llvm::APInt &val) {
+    return create<cir::ConstantOp>(loc, typ, getAttr<cir::IntAttr>(typ, val));
+  }
+
   cir::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr) {
     return create<cir::ConstantOp>(loc, attr.getType(), attr);
   }
@@ -143,6 +147,114 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
     return createCast(loc, cir::CastKind::bitcast, src, newTy);
   }
 
+  mlir::Value createBinop(mlir::Value lhs, cir::BinOpKind kind,
+                          const llvm::APInt &rhs) {
+    return create<cir::BinOp>(lhs.getLoc(), lhs.getType(), kind, lhs,
+                              getConstAPInt(lhs.getLoc(), lhs.getType(), rhs));
+  }
+
+  mlir::Value createBinop(mlir::Value lhs, cir::BinOpKind kind,
+                          mlir::Value rhs) {
+    return create<cir::BinOp>(lhs.getLoc(), lhs.getType(), kind, lhs, rhs);
+  }
+
+  mlir::Value createBinop(mlir::Location loc, mlir::Value lhs,
+                          cir::BinOpKind kind, mlir::Value rhs) {
+    return create<cir::BinOp>(loc, lhs.getType(), kind, lhs, rhs);
+  }
+
+  mlir::Value createLowBitsSet(mlir::Location loc, unsigned size,
+                               unsigned bits) {
+    llvm::APInt val = llvm::APInt::getLowBitsSet(size, bits);
+    auto type = cir::IntType::get(getContext(), size, false);
+    return getConstAPInt(loc, type, val);
+  }
+
+  mlir::Value createAnd(mlir::Value lhs, const llvm::APInt &rhs) {
+    mlir::Value val = getConstAPInt(lhs.getLoc(), lhs.getType(), rhs);
+    return createBinop(lhs, cir::BinOpKind::And, val);
+  }
+
+  mlir::Value createAnd(mlir::Value lhs, mlir::Value rhs) {
+    return createBinop(lhs, cir::BinOpKind::And, rhs);
+  }
+
+  mlir::Value createAnd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
+    return createBinop(loc, lhs, cir::BinOpKind::And, rhs);
+  }
+
+  mlir::Value createOr(mlir::Value lhs, const llvm::APInt &rhs) {
+    mlir::Value val = getConstAPInt(lhs.getLoc(), lhs.getType(), rhs);
+    return createBinop(lhs, cir::BinOpKind::Or, val);
+  }
+
+  mlir::Value createOr(mlir::Value lhs, mlir::Value rhs) {
+    return createBinop(lhs, cir::BinOpKind::Or, rhs);
+  }
+
+  mlir::Value createMul(mlir::Value lhs, mlir::Value rhs, bool hasNUW = false,
+                        bool hasNSW = false) {
+    auto op = create<cir::BinOp>(lhs.getLoc(), lhs.getType(),
+                                 cir::BinOpKind::Mul, lhs, rhs);
+    if (hasNUW)
+      op.setNoUnsignedWrap(true);
+    if (hasNSW)
+      op.setNoSignedWrap(true);
+    return op;
+  }
+  mlir::Value createNSWMul(mlir::Value lhs, mlir::Value rhs) {
+    return createMul(lhs, rhs, false, true);
+  }
+  mlir::Value createNUWAMul(mlir::Value lhs, mlir::Value rhs) {
+    return createMul(lhs, rhs, true, false);
+  }
+
+  mlir::Value createMul(mlir::Value lhs, const llvm::APInt &rhs) {
+    mlir::Value val = getConstAPInt(lhs.getLoc(), lhs.getType(), rhs);
+    return createBinop(lhs, cir::BinOpKind::Mul, val);
+  }
+
+  mlir::Value createSub(mlir::Value lhs, mlir::Value rhs, bool hasNUW = false,
+                        bool hasNSW = false, bool saturated = false) {
+    auto op = create<cir::BinOp>(lhs.getLoc(), lhs.getType(),
+                                 cir::BinOpKind::Sub, lhs, rhs);
+    if (hasNUW)
+      op.setNoUnsignedWrap(true);
+    if (hasNSW)
+      op.setNoSignedWrap(true);
+    if (saturated)
+      op.setSaturated(true);
+    return op;
+  }
+
+  mlir::Value createNSWSub(mlir::Value lhs, mlir::Value rhs) {
+    return createSub(lhs, rhs, false, true);
+  }
+
+  mlir::Value createNUWSub(mlir::Value lhs, mlir::Value rhs) {
+    return createSub(lhs, rhs, true, false);
+  }
+
+  mlir::Value createAdd(mlir::Value lhs, mlir::Value rhs, bool hasNUW = false,
+                        bool hasNSW = false, bool saturated = false) {
+    auto op = create<cir::BinOp>(lhs.getLoc(), lhs.getType(),
+                                 cir::BinOpKind::Add, lhs, rhs);
+    if (hasNUW)
+      op.setNoUnsignedWrap(true);
+    if (hasNSW)
+      op.setNoSignedWrap(true);
+    if (saturated)
+      op.setSaturated(true);
+    return op;
+  }
+
+  mlir::Value createNSWAdd(mlir::Value lhs, mlir::Value rhs) {
+    return createAdd(lhs, rhs, false, true);
+  }
+  mlir::Value createNUWAdd(mlir::Value lhs, mlir::Value rhs) {
+    return createAdd(lhs, rhs, true, false);
+  }
+
   //
   // Block handling helpers
   // ----------------------
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index d7d63e040a2ba..dca17e6cd2d2d 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -826,6 +826,129 @@ def ForOp : CIR_Op<"for", [LoopOpInterface, NoRegionArguments]> {
   }];
 }
 
+//===----------------------------------------------------------------------===//
+// BinOp
+//===----------------------------------------------------------------------===//
+
+// FIXME: represent Commutative, Idempotent traits for appropriate binops
+def BinOpKind_Mul : I32EnumAttrCase<"Mul", 1, "mul">;
+def BinOpKind_Div : I32EnumAttrCase<"Div", 2, "div">;
+def BinOpKind_Rem : I32EnumAttrCase<"Rem", 3, "rem">;
+def BinOpKind_Add : I32EnumAttrCase<"Add", 4, "add">;
+def BinOpKind_Sub : I32EnumAttrCase<"Sub", 5, "sub">;
+def BinOpKind_And : I32EnumAttrCase<"And", 8, "and">;
+def BinOpKind_Xor : I32EnumAttrCase<"Xor", 9, "xor">;
+def BinOpKind_Or  : I32EnumAttrCase<"Or", 10, "or">;
+// TODO(cir): Do we need a min binop?
+def BinOpKind_Max : I32EnumAttrCase<"Max", 11, "max">;
+
+def BinOpKind : I32EnumAttr<
+    "BinOpKind",
+    "binary operation (arith and logic) kind",
+    [BinOpKind_Mul, BinOpKind_Div, BinOpKind_Rem,
+     BinOpKind_Add, BinOpKind_Sub,
+     BinOpKind_And, BinOpKind_Xor,
+     BinOpKind_Or, BinOpKind_Max]> {
+  let cppNamespace = "::cir";
+}
+
+// FIXME: Pure won't work when we add overloading.
+def BinOp : CIR_Op<"binop", [Pure,
+  SameTypeOperands, SameOperandsAndResultType]> {
+
+  let summary = "Binary operations (arith and logic)";
+  let description = [{
+    cir.binop performs the binary operation according to
+    the specified opcode kind: [mul, div, rem, add, sub,
+    and, xor, or, max].
+
+    It requires two input operands and has one result, all types
+    should be the same.
+
+    ```mlir
+    %7 = cir.binop(add, %1, %2) : !s32i
+    %7 = cir.binop(mul, %1, %2) : !u8i
+    ```
+  }];
+
+  // TODO: get more accurate than CIR_AnyType
+  let results = (outs CIR_AnyType:$result);
+  let arguments = (ins Arg<BinOpKind, "binop kind">:$kind,
+                       CIR_AnyType:$lhs, CIR_AnyType:$rhs,
+                       UnitAttr:$no_unsigned_wrap,
+                       UnitAttr:$no_signed_wrap,
+                       UnitAttr:$saturated);
+
+  let assemblyFormat = [{
+    `(` $kind `,` $lhs `,` $rhs  `)`
+    (`nsw` $no_signed_wrap^)?
+    (`nuw` $no_unsigned_wrap^)?
+    (`sat` $saturated^)?
+    `:` type($lhs) attr-dict
+  }];
+
+  let hasVerifier = 1;
+}
+
+
+//===----------------------------------------------------------------------===//
+// BinOpOverflowOp
+//===----------------------------------------------------------------------===//
+
+def BinOpOverflowKind : I32EnumAttr<
+    "BinOpOverflowKind",
+    "checked binary arithmetic operation kind",
+    [BinOpKind_Add, BinOpKind_Sub, BinOpKind_Mul]> {
+  let cppNamespace = "::cir";
+}
+
+def BinOpOverflowOp : CIR_Op<"binop.overflow", [Pure, SameTypeOperands]> {
+  let summary = "Perform binary integral arithmetic with overflow checking";
+  let description = [{
+    `cir.binop.overflow` performs binary arithmetic operations with overflow
+    checking on integral operands.
+
+    The `kind` argument specifies the kind of arithmetic operation to perform.
+    It can be either `add`, `sub`, or `mul`. The `lhs` and `rhs` arguments
+    specify the input operands of the arithmetic operation. The types of `lhs`
+    and `rhs` must be the same.
+
+    `cir.binop.overflow` produces two SSA values. `result` is the result of the
+    arithmetic operation truncated to its specified type. `overflow` is a
+    boolean value indicating whether overflow happens during the operation.
+
+    The exact semantic of this operation is as follows:
+
+      - `lhs` and `rhs` are promoted to an imaginary integral type that has
+        infinite precision.
+      - The arithmetic operation is performed on the promoted operands.
+      - The infinite-precision result is truncated to the type of `result`. The
+        truncated result is assigned to `result`.
+      - If the truncated result is equal to the un-truncated result, `overflow`
+        is assigned to false. Otherwise, `overflow` is assigned to true.
+  }];
+
+  let arguments = (ins Arg<BinOpOverflowKind, "arithmetic kind">:$kind,
+                       CIR_IntType:$lhs, CIR_IntType:$rhs);
+  let results = (outs CIR_IntType:$result, CIR_BoolType:$overflow);
+
+  let assemblyFormat = [{
+    `(` $kind `,` $lhs `,` $rhs `)` `:` type($lhs) `,`
+    `(` type($result) `,` type($overflow) `)`
+    attr-dict
+  }];
+
+  let builders = [
+    OpBuilder<(ins "cir::IntType":$resultTy,
+                   "cir::BinOpOverflowKind":$kind,
+                   "mlir::Value":$lhs,
+                   "mlir::Value":$rhs), [{
+      auto overflowTy = cir::BoolType::get($_builder.getContext());
+      build($_builder, $_state, resultTy, overflowTy, kind, lhs, rhs);
+    }]>
+  ];
+}
+
 //===----------------------------------------------------------------------===//
 // GlobalOp
 //===----------------------------------------------------------------------===//
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRTypes.h b/clang/include/clang/CIR/Dialect/IR/CIRTypes.h
index 5d1eb17e146d0..7b0fcbc7cc98f 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRTypes.h
+++ b/clang/include/clang/CIR/Dialect/IR/CIRTypes.h
@@ -21,6 +21,7 @@
 namespace cir {
 
 bool isAnyFloatingPointType(mlir::Type t);
+bool isFPOrFPVectorTy(mlir::Type);
 
 } // namespace cir
 
diff --git a/clang/include/clang/CIR/MissingFeatures.h b/clang/include/clang/CIR/MissingFeatures.h
index 3e33e5dc60194..3654038a51fbd 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -79,6 +79,9 @@ struct MissingFeatures {
   static bool opUnarySignedOverflow() { return false; }
   static bool opUnaryPromotionType() { return false; }
 
+  // Clang early optimizations or things defered to LLVM lowering.
+  static bool mayHaveIntegerOverflow() { return false; }
+
   // Misc
   static bool cxxABI() { return false; }
   static bool tryEmitAsConstant() { return false; }
@@ -93,16 +96,20 @@ struct MissingFeatures {
   static bool stackSaveOp() { return false; }
   static bool aggValueSlot() { return false; }
   static bool generateDebugInfo() { return false; }
+  static bool getFPFeaturesInEffect() { return false; }
+  static bool pointerOverflowSanitizer() { return false; }
   static bool fpConstraints() { return false; }
   static bool sanitizers() { return false; }
   static bool addHeapAllocSiteMetadata() { return false; }
   static bool targetCodeGenInfoGetNullPointer() { return false; }
-  static bool CGFPOptionsRAII() { return false; }
   static bool loopInfoStack() { return false; }
   static bool requiresCleanups() { return false; }
   static bool createProfileWeightsForLoop() { return false; }
   static bool emitCondLikelihoodViaExpectIntrinsic() { return false; }
   static bool pgoUse() { return false; }
+  static bool cgFPOptionsRAII() { return false; }
+  static bool metaDataNode() { return false; }
+  static bool foldBinOpFMF() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }
@@ -111,6 +118,8 @@ struct MissingFeatures {
   static bool scalableVectors() { return false; }
   static bool unsizedTypes() { return false; }
   static bool vectorType() { return false; }
+  static bool complexType() { return false; }
+  static bool fixedPointType() { return false; }
 
   // Future CIR operations
   static bool awaitOp() { return false; }
@@ -127,6 +136,8 @@ struct MissingFeatures {
   static bool ternaryOp() { return false; }
   static bool tryOp() { return false; }
   static bool zextOp() { return false; }
+  static bool opPtrStride() { return false; }
+  static bool opPtrDiff() { return false; }
 };
 
 } // namespace cir
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.h b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
index fef290612149a..dfffc2639b0d2 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuilder.h
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
@@ -14,11 +14,13 @@
 
 #include "clang/CIR/Dialect/Builder/CIRBaseBuilder.h"
 #include "clang/CIR/MissingFeatures.h"
+#include "llvm/ADT/STLExtras.h"
 
 namespace clang::CIRGen {
 
 class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
   const CIRGenTypeCache &typeCache;
+  bool isFPConstrained = false;
 
 public:
   CIRGenBuilderTy(mlir::MLIRContext &mlirContext, const CIRGenTypeCache &tc)
@@ -72,15 +74,72 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
     if (const auto arrayVal = mlir::dyn_cast<cir::ConstArrayAttr>(attr)) {
       if (mlir::isa<mlir::StringAttr>(arrayVal.getElts()))
         return false;
-      for (const auto elt : mlir::cast<mlir::ArrayAttr>(arrayVal.getElts())) {
-        if (!isNullValue(elt))
-          return false;
-      }
-      return true;
+
+      return llvm::all_of(
+          mlir::cast<mlir::ArrayAttr>(arrayVal.getElts()),
+          [&](const mlir::Attribute &elt) { return isNullValue(elt); });
     }
     return false;
   }
 
+  //
+  // Type helpers
+  // ------------
+  //
+  cir::IntType getUIntNTy(int n) {
+    switch (n) {
+    case 8:
+      return getUInt8Ty();
+    case 16:
+      return getUInt16Ty();
+    case 32:
+      return getUInt32Ty();
+    case 64:
+      return getUInt64Ty();
+    default:
+      return cir::IntType::get(getContext(), n, false);
+    }
+  }
+
+  cir::IntType getSIntNTy(int n) {
+    switch (n) {
+    case 8:
+      return getSInt8Ty();
+    case 16:
+      return getSInt16Ty();
+    case 32:
+      return getSInt32Ty();
+    case 64:
+      return getSInt64Ty();
+    default:
+      return cir::IntType::get(getContext(), n, true);
+    }
+  }
+
+  cir::VoidType getVoidTy() { return typeCache.VoidTy; }
+
+  cir::IntType getSInt8Ty() { return typeCache.SInt8Ty; }
+  cir::IntType getSInt16Ty() { return typeCache.SInt16Ty; }
+  cir::IntType getSInt32Ty() { return typeCache.SInt32Ty; }
+  cir::IntType getSInt64Ty() { return typeCache.SInt64Ty; }
+
+  cir::IntType getUInt8Ty() { return typeCache.UInt8Ty; }
+  cir::IntType getUInt16Ty() { return typeCache.UInt16Ty; }
+  cir::IntType getUInt32Ty() { return typeCache.UInt32Ty; }
+  cir::IntType getUInt64Ty() { return typeCache.UInt64Ty; }
+
+  bool isInt8Ty(mlir::Type i) {
+    return i == typeCache.UInt8Ty || i == typeCache.SInt8Ty;
+  }
+  bool isInt16Ty(mlir::Type i) {
+    return i == typeCache.UInt16Ty || i == typeCache.SInt16Ty;
+  }
+  bool isInt32Ty(mlir::Type i) {
+    return i == typeCache.UInt32Ty || i == typeCache.SInt32Ty;
+  }
+  bool isInt64Ty(mlir::Type i) {
+    return i == typeCache.UInt64Ty || i == typeCache.SInt64Ty;
+  }
   bool isInt(mlir::Type i) { return mlir::isa<cir::IntType>(i); }
 
   // Creates constant nullptr for pointer type ty.
@@ -88,6 +147,53 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
     assert(!cir::MissingFeatures::targetCodeGenInfoGetNullPointer());
     return create<cir::ConstantOp>(loc, ty, getConstPtrAttr(ty, 0));
   }
+
+  mlir::Value createNeg(mlir::Value value) {
+
+    if (auto intTy = mlir::dyn_cast<cir::IntType>(value.getType())) {
+      // Source is a unsigned integer: first cast it to signed.
+      if (intTy.isUnsigned())
+        value = createIntCast(value, getSIntNTy(intTy.getWidth()));
+      return create<cir::UnaryOp>(value.getLoc(), value.getType(),
+                                  cir::UnaryOpKind::Minus, value);
+    }
+
+    llvm_unreachable("negation for the given type is NYI");
+  }
+
+  mlir::Value createFSub(mlir::Value lhs, mlir::Value rhs) {
+    assert(!cir::MissingFeatures::metaDataNode());
+    if (isFPConstrained)
+      llvm_unreachable("Constrained FP NYI");
+
+    assert(!cir::MissingFeatures::foldBinOpFMF());
+    return create<cir::BinOp>(lhs.getLoc(), cir::BinOpKind::Sub, lhs, rhs);
+  }
+
+  mlir::Value createFAdd(mlir::Value lhs, mlir::Value rhs) {
+    assert(!cir::MissingFeatures::metaDataNode());
+    if (isFPConstrained)
+      llvm_unreachable("Constrained FP NYI");
+
+    assert(!cir::MissingFeatures::foldBinOpFMF());
+    return create<cir::BinOp>(lhs.getLoc(), cir::BinOpKind::Add, lhs, rhs);
+  }
+  mlir::Value createFMul(mlir::Value lhs, mlir::Value rhs) {
+    assert(!cir::MissingFeatures::metaDataNode());
+    if (isFPConstrained)
+      llvm_unreachable("Constrained FP NYI");
+
+    assert(!cir::MissingFeatures::foldBinOpFMF());
+    return create<cir::BinOp>(lhs.getLoc(), cir::BinOpKind::Mul, lhs, rhs);
+  }
+  mlir::Value createFDiv(mlir::Value lhs, mlir::Value rhs) {
+    assert(!cir::MissingFeatures::metaDataNode());
+    if (isFPConstrained)
+      llvm_unreachable("Constrained FP NYI");
+
+    assert(!cir::MissingFeatures::foldBinOpFMF());
+    return create<cir::BinOp>(lhs.getLoc(), cir::BinOpKind::Div, lhs, rhs);
+  }
 };
 
 } // namespace clang::CIRGen
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 306130b80d457..d3365cbcbbeed 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -149,8 +149,8 @@ LValue CIRGenFunction::emitDeclRefLValue(const DeclRefExpr *e) {
     Address addr = Address::invalid();
 
     // The variable should generally be present in the local decl map.
-    auto iter = LocalDeclMap.find(vd);
-    if (iter != LocalDeclMap.end()) {
+    auto iter = localDeclMap.find(vd);
+    if (iter != localDeclMap.end()) {
       addr = iter->second;
     } else {
       // Otherwise, it might be static local we haven't emitted yet for some
@@ -176,7 +176,7 @@ mlir::Value CIRGenFunction::evaluateExprAsBool(const Expr *e) {
     return createDummyValue(getLoc(loc), boolTy);
   }
 
-  assert(!cir::MissingFeatures::CGFPOptionsRAII());
+  assert(!cir::MissingFeatures::cgFPOptionsRAII());
   if (!e->getType()->isAnyComplexType())
     return emitScalarConversion(emitScalarExpr(e), e->getType(), boolTy, loc);
 
@@ -211,9 +211,8 @@ LValue CIRGenFunction::emitUnaryOpLValue(const UnaryOperator *e) {
     if (e->getType()->isAnyComplexType()) {
       cgm.errorNYI(e->getSourceRange(), "UnaryOp complex inc/dec");
       return LValue();
-    } else {
-      emitScalarPrePostIncDec(e, lv, isInc, /*isPre=*/true);
     }
+    emitScalarPrePostIncDec(e, lv, isInc, /*isPre=*/true);
 
     return lv;
   }
@@ -232,6 +231,61 @@ LValue CIRGenFunction::emitUnaryOpLValue(const UnaryOperator *e) {
   llvm_unreachable("Unknown unary operator kind!");
 }
 
+LValue CIRGenFunction::emitBinaryOperatorLValue(const BinaryOperator *e) {
+  // Comma expressions just emit their LHS then their RHS as an l-value.
+  if (e->getOpcode() == BO_Comma) {
+    emitIgnoredExpr(e->getLHS());
+    return emitLValue(e->getRHS());
+  }
+
+  if (e->getOpcode() == BO_PtrMemD || e->getOpcode() == BO_PtrMemI) {
+    cgm.errorNYI(e->getSourceRange(), "member pointers");
+    return {};
+  }
+
+  assert(e->getOpcode() == BO_Assign && "unexpected binary l-value");
+
+  // Note that in all of these cases, __block variables need the RHS
+  // evaluated first just in case the variable gets moved by the RHS.
+
+  switch (CIRGenFunction::getEvaluationKind(e->getType())) {
+  case cir::TEK_Scalar: {
+    if (e->getLHS()->getType().getObjCLifetime() !=
+        clang::Qualifiers::ObjCLifetime::OCL_None) {
+      cgm.errorNYI(e->getSourceRange(), "objc lifetimes");
+      return {};
+    }
+
+    RValue rv = emitAnyExpr(e->getRHS());
+    LValue lv = emitLValue(e->getLHS());
+
+    SourceLocRAIIObject loc{*this, getLoc(e->getSourceRange())};
+    if (lv.isBitField()) {
+      cgm.errorNYI(e->getSourceRange(), "bitfields");
+      return {};
+    }
+    emitStoreThroughLValue(rv, lv);
+
+    if (getLangOpts().OpenMP) {
+      cgm.errorNYI(e->getSourceRange(), "openmp");
+      return {};
+    }
+
+    return lv;
+  }
+
+  case cir::TEK_Complex: {
+    assert(!cir::MissingFeatures::complexType());
+    cgm.errorNYI(e->getSourceRange(), "complex l-values");
+    return {};
+  }
+  case cir::TEK_Aggregate:
+    cgm.errorNYI(e->getSourceRange(), "aggregate lvalues");
+    return {};
+  }
+  llvm_unreachable("bad evaluation kind");
+}
+
 /// Emit code to compute the specified expression which
 /// can have any type.  The result is returned as an RValue struct.
 RValue CIRGenFunction::emitAnyExpr(const Expr *e) {
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index ca0090f8d35b3..787a93c52b53e 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -26,6 +26,53 @@ using namespace clang::CIRGen;
 
 namespace {
 
+struct BinOpInfo {
+  mlir::Value lhs;
+  mlir::Value rhs;
+  SourceRange loc;
+  QualType fullType;             // Type of operands and result
+  QualType compType;             // Type used for computations. Element type
+                                 // for vectors, otherwise same as FullType.
+  BinaryOperator::Opcode opcode; // Opcode of BinOp to perform
+  FPOptions fpfeatures;
+  const Expr *e; // Entire expr, for error unsupported.  May not be binop.
+
+  /// Check if the binop computes a division or a remainder.
+  bool isDivremOp() const {
+    return opcode == BO_Div || opcode == BO_Rem || opcode == BO_DivAssign ||
+           opcode == BO_RemAssign;
+  }
+
+  /// Check if the binop can result in integer overflow.
+  bool mayHaveIntegerOverflow() const {
+    // Without constant input, we can't rule out overflow.
+    auto lhsci = dyn_cast<cir::ConstantOp>(lhs.getDefiningOp());
+    auto rhsci = dyn_cast<cir::ConstantOp>(rhs.getDefiningOp());
+    if (!lhsci || !rhsci)
+      return true;
+
+    assert(!cir::MissingFeatures::mayHaveIntegerOverflow());
+    // TODO(cir): For now we just assume that we might overflow
+    return true;
+  }
+
+  /// Check if at least one operand is a fixed point type. In such cases,
+  /// this operation did not follow usual arithmetic conversion and both
+  /// operands might not be of the same type.
+  bool isFixedPointOp() const {
+    // We cannot simply check the result type since comparison operations
+    // return an int.
+    if (const auto *binOp = llvm::dyn_cast<BinaryOperator>(e)) {
+      QualType lhstype = binOp->getLHS()->getType();
+      QualType rhstype = binOp->getRHS()->getType();
+      return lhstype->isFixedPointType() || rhstype->isFixedPointType();
+    }
+    if (const auto *unop = llvm::dyn_cast<UnaryOperator>(e))
+      return unop->getSubExpr()->getType()->isFixedPointType();
+    return false;
+  }
+};
+
 class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
   CIRGenFunction &cgf;
   CIRGenBuilderTy &builder;
@@ -35,6 +82,22 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
   ScalarExprEmitter(CIRGenFunction &cgf, CIRGenBuilderTy &builder)
       : cgf(cgf), builder(builder) {}
 
+  //===--------------------------------------------------------------------===//
+  //                               Utilities
+  //===--------------------------------------------------------------------===//
+
+  mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType) {
+    cgf.cgm.errorNYI(result.getLoc(), "floating cast for promoted value");
+    return nullptr;
+  }
+
+  mlir::Value emitUnPromotedValue(mlir::Value result, QualType exprType) {
+    cgf.cgm.errorNYI(result.getLoc(), "floating cast for unpromoted value");
+    return nullptr;
+  }
+
+  mlir::Value emitPromoted(const Expr *e, QualType promotionType);
+
   //===--------------------------------------------------------------------===//
   //                            Visitor Methods
   //===--------------------------------------------------------------------===//
@@ -60,6 +123,10 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
     return cgf.emitLoadOfLValue(lv, e->getExprLoc()).getScalarVal();
   }
 
+  mlir::Value emitLoadOfLValue(LValue lv, SourceLocation loc) {
+    return cgf.emitLoadOfLValue(lv, loc).getScalarVal();
+  }
+
   // l-values
   mlir::Value VisitDeclRefExpr(DeclRefExpr *e) {
     assert(!cir::MissingFeatures::tryEmitAsConstant());
@@ -308,14 +375,14 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
         // NOTE(CIR): clang calls CreateAdd but folds this to a unary op
         value = emitUnaryOp(e, kind, input);
       }
-    } else if (const PointerType *ptr = type->getAs<PointerType>()) {
+    } else if (isa<PointerType>(type)) {
       cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec pointer");
       return {};
     } else if (type->isVectorType()) {
       cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec vector");
       return {};
     } else if (type->isRealFloatingType()) {
-      assert(!cir::MissingFeatures::CGFPOptionsRAII());
+      assert(!cir::MissingFeatures::cgFPOptionsRAII());
 
       if (type->isHalfType() &&
           !cgf.getContext().getLangOpts().NativeHalfType) {
@@ -349,9 +416,8 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
     if (lv.isBitField()) {
       cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec bitfield");
       return {};
-    } else {
-      cgf.emitStoreThroughLValue(RValue::get(value), lv);
     }
+    cgf.emitStoreThroughLValue(RValue::get(value), lv);
 
     // If this is a postinc, return the value read from memory, otherwise use
     // the updated value.
@@ -558,8 +624,225 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
 
     return res;
   }
+
+  BinOpInfo emitBinOps(const BinaryOperator *e,
+                       QualType promotionType = QualType()) {
+    BinOpInfo result;
+    result.lhs = cgf.emitPromotedScalarExpr(e->getLHS(), promotionType);
+    result.rhs = cgf.emitPromotedScalarExpr(e->getRHS(), promotionType);
+    if (!promotionType.isNull())
+      result.fullType = promotionType;
+    else
+      result.fullType = e->getType();
+    result.compType = result.fullType;
+    if (const auto *vecType = dyn_cast_or_null<VectorType>(result.fullType)) {
+      result.compType = vecType->getElementType();
+    }
+    result.opcode = e->getOpcode();
+    result.loc = e->getSourceRange();
+    // TODO(cir): Result.FPFeatures
+    assert(!cir::MissingFeatures::getFPFeaturesInEffect());
+    result.e = e;
+    return result;
+  }
+
+  mlir::Value emitMul(const BinOpInfo &ops);
+  mlir::Value emitDiv(const BinOpInfo &ops);
+  mlir::Value emitRem(const BinOpInfo &ops);
+  mlir::Value emitAdd(const BinOpInfo &ops);
+  mlir::Value emitSub(const BinOpInfo &ops);
+  mlir::Value emitShl(const BinOpInfo &ops);
+  mlir::Value emitShr(const BinOpInfo &ops);
+  mlir::Value emitAnd(const BinOpInfo &ops);
+  mlir::Value emitXor(const BinOpInfo &ops);
+  mlir::Value emitOr(const BinOpInfo &ops);
+
+  LValue emitCompoundAssignLValue(
+      const CompoundAssignOperator *e,
+      mlir::Value (ScalarExprEmitter::*f)(const BinOpInfo &),
+      mlir::Value &result);
+  mlir::Value
+  emitCompoundAssign(const CompoundAssignOperator *e,
+                     mlir::Value (ScalarExprEmitter::*f)(const BinOpInfo &));
+
+  // TODO(cir): Candidate to be in a common AST helper between CIR and LLVM
+  // codegen.
+  QualType getPromotionType(QualType ty) {
+    if (ty->getAs<ComplexType>()) {
+      assert(!cir::MissingFeatures::complexType());
+      cgf.cgm.errorNYI("promotion to complex type");
+      return QualType();
+    }
+    if (ty.UseExcessPrecision(cgf.getContext())) {
+      if (ty->getAs<VectorType>()) {
+        assert(!cir::MissingFeatures::vectorType());
+        cgf.cgm.errorNYI("promotion to vector type");
+        return QualType();
+      }
+      return cgf.getContext().FloatTy;
+    }
+    return QualType();
+  }
+
+// Binary operators and binary compound assignment operators.
+#define HANDLEBINOP(OP)                                                        \
+  mlir::Value VisitBin##OP(const BinaryOperator *e) {                          \
+    QualType promotionTy = getPromotionType(e->getType());                     \
+    auto result = emit##OP(emitBinOps(e, promotionTy));                        \
+    if (result && !promotionTy.isNull())                                       \
+      result = emitUnPromotedValue(result, e->getType());                      \
+    return result;                                                             \
+  }                                                                            \
+  mlir::Value VisitBin##OP##Assign(const CompoundAssignOperator *e) {          \
+    return emitCompoundAssign(e, &ScalarExprEmitter::emit##OP);                \
+  }
+
+  HANDLEBINOP(Mul)
+  HANDLEBINOP(Div)
+  HANDLEBINOP(Rem)
+  HANDLEBINOP(Add)
+  HANDLEBINOP(Sub)
+  HANDLEBINOP(Shl)
+  HANDLEBINOP(Shr)
+  HANDLEBINOP(And)
+  HANDLEBINOP(Xor)
+  HANDLEBINOP(Or)
+#undef HANDLEBINOP
 };
 
+LValue ScalarExprEmitter::emitCompoundAssignLValue(
+    const CompoundAssignOperator *e,
+    mlir::Value (ScalarExprEmitter::*func)(const BinOpInfo &),
+    mlir::Value &result) {
+  QualType lhsTy = e->getLHS()->getType();
+  BinOpInfo opInfo;
+
+  if (e->getComputationResultType()->isAnyComplexType()) {
+    cgf.cgm.errorNYI(result.getLoc(), "complex lvalue assign");
+    return LValue();
+  }
+
+  // Emit the RHS first.  __block variables need to have the rhs evaluated
+  // first, plus this should improve codegen a little.
+
+  QualType promotionTypeCR = getPromotionType(e->getComputationResultType());
+  if (promotionTypeCR.isNull())
+    promotionTypeCR = e->getComputationResultType();
+
+  QualType promotionTypeLHS = getPromotionType(e->getComputationLHSType());
+  QualType promotionTypeRHS = getPromotionType(e->getRHS()->getType());
+
+  if (!promotionTypeRHS.isNull())
+    opInfo.rhs = cgf.emitPromotedScalarExpr(e->getRHS(), promotionTypeRHS);
+  else
+    opInfo.rhs = Visit(e->getRHS());
+
+  opInfo.fullType = promotionTypeCR;
+  opInfo.compType = opInfo.fullType;
+  if (const auto *vecType = dyn_cast_or_null<VectorType>(opInfo.fullType)) {
+    opInfo.compType = vecType->getElementType();
+  }
+  opInfo.opcode = e->getOpcode();
+  opInfo.fpfeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
+  opInfo.e = e;
+  opInfo.loc = e->getSourceRange();
+
+  // Load/convert the LHS
+  LValue lhsLV = cgf.emitLValue(e->getLHS());
+
+  if (lhsTy->getAs<AtomicType>()) {
+    cgf.cgm.errorNYI(result.getLoc(), "atomic lvalue assign");
+    return LValue();
+  }
+
+  opInfo.lhs = emitLoadOfLValue(lhsLV, e->getExprLoc());
+
+  CIRGenFunction::SourceLocRAIIObject sourceloc{
+      cgf, cgf.getLoc(e->getSourceRange())};
+  SourceLocation loc = e->getExprLoc();
+  if (!promotionTypeLHS.isNull())
+    opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy, promotionTypeLHS,
+                                      e->getExprLoc());
+  else
+    opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy,
+                                      e->getComputationLHSType(), loc);
+
+  // Expand the binary operator.
+  result = (this->*func)(opInfo);
+
+  // Convert the result back to the LHS type,
+  // potentially with Implicit Conversion sanitizer check.
+  result = emitScalarConversion(result, promotionTypeCR, lhsTy, loc);
+  //                              ScalarConversionOpts(cgf.sanOpts));
+
+  // Store the result value into the LHS lvalue. Bit-fields are handled
+  // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
+  // 'An assignment expression has the value of the left operand after the
+  // assignment...'.
+  if (lhsLV.isBitField())
+    cgf.cgm.errorNYI(e->getSourceRange(), "store through bitfield lvalue");
+  else
+    cgf.emitStoreThroughLValue(RValue::get(result), lhsLV);
+
+  if (cgf.getLangOpts().OpenMP)
+    cgf.cgm.errorNYI(e->getSourceRange(), "openmp");
+
+  return lhsLV;
+}
+
+mlir::Value ScalarExprEmitter::emitPromoted(const Expr *e,
+                                            QualType promotionType) {
+  e = e->IgnoreParens();
+  if (const auto *bo = dyn_cast<BinaryOperator>(e)) {
+    switch (bo->getOpcode()) {
+#define HANDLE_BINOP(OP)                                                       \
+  case BO_##OP:                                                                \
+    return emit##OP(emitBinOps(bo, promotionType));
+      HANDLE_BINOP(Add)
+      HANDLE_BINOP(Sub)
+      HANDLE_BINOP(Mul)
+      HANDLE_BINOP(Div)
+#undef HANDLE_BINOP
+    default:
+      break;
+    }
+  } else if (isa<UnaryOperator>(e)) {
+    cgf.cgm.errorNYI(e->getSourceRange(), "unary operators");
+    return {};
+  }
+  mlir::Value result = Visit(const_cast<Expr *>(e));
+  if (result) {
+    if (!promotionType.isNull())
+      return emitPromotedValue(result, promotionType);
+    return emitUnPromotedValue(result, e->getType());
+  }
+  return result;
+}
+
+mlir::Value ScalarExprEmitter::emitCompoundAssign(
+    const CompoundAssignOperator *e,
+    mlir::Value (ScalarExprEmitter::*func)(const BinOpInfo &)) {
+
+  bool ignore = std::exchange(ignoreResultAssign, false);
+  mlir::Value rhs;
+  LValue lhs = emitCompoundAssignLValue(e, func, rhs);
+
+  // If the result is clearly ignored, return now.
+  if (ignore)
+    return {};
+
+  // The result of an assignment in C is the assigned r-value.
+  if (!cgf.getLangOpts().CPlusPlus)
+    return rhs;
+
+  // If the lvalue is non-volatile, return the computed value of the assignment.
+  if (!lhs.isVolatile())
+    return rhs;
+
+  // Otherwise, reload the value.
+  return emitLoadOfLValue(lhs, e->getExprLoc());
+}
+
 } // namespace
 
 /// Emit the computation of the specified expression of scalar type.
@@ -570,13 +853,425 @@ mlir::Value CIRGenFunction::emitScalarExpr(const Expr *e) {
   return ScalarExprEmitter(*this, builder).Visit(const_cast<Expr *>(e));
 }
 
-[[maybe_unused]] static bool MustVisitNullValue(const Expr *e) {
+mlir::Value CIRGenFunction::emitPromotedScalarExpr(const Expr *e,
+                                                   QualType promotionType) {
+  if (!promotionType.isNull())
+    return ScalarExprEmitter(*this, builder).emitPromoted(e, promotionType);
+  return ScalarExprEmitter(*this, builder).Visit(const_cast<Expr *>(e));
+}
+
+[[maybe_unused]] static bool mustVisitNullValue(const Expr *e) {
   // If a null pointer expression's type is the C++0x nullptr_t, then
   // it's not necessarily a simple constant and it must be evaluated
   // for its potential side effects.
   return e->getType()->isNullPtrType();
 }
 
+/// If \p E is a widened promoted integer, get its base (unpromoted) type.
+static std::optional<QualType>
+getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e) {
+  const Expr *base = e->IgnoreImpCasts();
+  if (e == base)
+    return std::nullopt;
+
+  QualType baseTy = base->getType();
+  if (!astContext.isPromotableIntegerType(baseTy) ||
+      astContext.getTypeSize(baseTy) >= astContext.getTypeSize(e->getType()))
+    return std::nullopt;
+
+  return baseTy;
+}
+
+/// Check if \p E is a widened promoted integer.
+[[maybe_unused]] static bool isWidenedIntegerOp(const ASTContext &astContext,
+                                                const Expr *e) {
+  return getUnwidenedIntegerType(astContext, e).has_value();
+}
+
+/// Check if we can skip the overflow check for \p Op.
+[[maybe_unused]] static bool canElideOverflowCheck(const ASTContext &astContext,
+                                                   const BinOpInfo &op) {
+  assert((isa<UnaryOperator>(op.e) || isa<BinaryOperator>(op.e)) &&
+         "Expected a unary or binary operator");
+
+  // If the binop has constant inputs and we can prove there is no overflow,
+  // we can elide the overflow check.
+  if (!op.mayHaveIntegerOverflow())
+    return true;
+
+  // If a unary op has a widened operand, the op cannot overflow.
+  if (const auto *uo = dyn_cast<UnaryOperator>(op.e))
+    return !uo->canOverflow();
+
+  // We usually don't need overflow checks for binops with widened operands.
+  // Multiplication with promoted unsigned operands is a special case.
+  const auto *bo = cast<BinaryOperator>(op.e);
+  auto optionalLHSTy = getUnwidenedIntegerType(astContext, bo->getLHS());
+  if (!optionalLHSTy)
+    return false;
+
+  auto optionalRHSTy = getUnwidenedIntegerType(astContext, bo->getRHS());
+  if (!optionalRHSTy)
+    return false;
+
+  QualType lhsTy = *optionalLHSTy;
+  QualType rhsTy = *optionalRHSTy;
+
+  // This is the simple case: binops without unsigned multiplication, and with
+  // widened operands. No overflow check is needed here.
+  if ((op.opcode != BO_Mul && op.opcode != BO_MulAssign) ||
+      !lhsTy->isUnsignedIntegerType() || !rhsTy->isUnsignedIntegerType())
+    return true;
+
+  // For unsigned multiplication the overflow check can be elided if either one
+  // of the unpromoted types are less than half the size of the promoted type.
+  unsigned promotedSize = astContext.getTypeSize(op.e->getType());
+  return (2 * astContext.getTypeSize(lhsTy)) < promotedSize ||
+         (2 * astContext.getTypeSize(rhsTy)) < promotedSize;
+}
+
+/// Emit pointer + index arithmetic.
+static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf,
+                                         const BinOpInfo &op,
+                                         bool isSubtraction) {
+  // Must have binary (not unary) expr here.  Unary pointer
+  // increment/decrement doesn't use this path.
+  const BinaryOperator *expr = cast<BinaryOperator>(op.e);
+
+  mlir::Value pointer = op.lhs;
+  Expr *pointerOperand = expr->getLHS();
+  mlir::Value index = op.rhs;
+  Expr *indexOperand = expr->getRHS();
+
+  // In a subtraction, the LHS is always the pointer.
+  if (!isSubtraction && !mlir::isa<cir::PointerType>(pointer.getType())) {
+    std::swap(pointer, index);
+    std::swap(pointerOperand, indexOperand);
+  }
+
+  bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
+
+  // Some versions of glibc and gcc use idioms (particularly in their malloc
+  // routines) that add a pointer-sized integer (known to be a pointer value)
+  // to a null pointer in order to cast the value back to an integer or as
+  // part of a pointer alignment algorithm.  This is undefined behavior, but
+  // we'd like to be able to compile programs that use it.
+  //
+  // Normally, we'd generate a GEP with a null-pointer base here in response
+  // to that code, but it's also UB to dereference a pointer created that
+  // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
+  // generate a direct cast of the integer value to a pointer.
+  //
+  // The idiom (p = nullptr + N) is not met if any of the following are true:
+  //
+  //   The operation is subtraction.
+  //   The index is not pointer-sized.
+  //   The pointer type is not byte-sized.
+  //
+  if (BinaryOperator::isNullPointerArithmeticExtension(
+          cgf.getContext(), op.opcode, expr->getLHS(), expr->getRHS()))
+    return cgf.getBuilder().createIntToPtr(index, pointer.getType());
+
+  // Differently from LLVM codegen, ABI bits for index sizes is handled during
+  // LLVM lowering.
+
+  // If this is subtraction, negate the index.
+  if (isSubtraction)
+    index = cgf.getBuilder().createNeg(index);
+
+  if (cgf.sanOpts.has(SanitizerKind::ArrayBounds))
+    cgf.cgm.errorNYI("array bounds sanitizer");
+
+  const PointerType *pointerType =
+      pointerOperand->getType()->getAs<PointerType>();
+  if (!pointerType)
+    cgf.cgm.errorNYI("ObjC");
+
+  QualType elementType = pointerType->getPointeeType();
+  if (const VariableArrayType *vla =
+          cgf.getContext().getAsVariableArrayType(elementType)) {
+
+    // The element count here is the total number of non-VLA elements.
+    mlir::Value numElements = nullptr; // cgf.getVLASize(vla).NumElts;
+
+    // GEP indexes are signed, and scaling an index isn't permitted to
+    // signed-overflow, so we use the same semantics for our explicit
+    // multiply.  We suppress this if overflow is not undefined behavior.
+    mlir::Type elemTy = cgf.convertTypeForMem(vla->getElementType());
+
+    index = cgf.getBuilder().createCast(cir::CastKind::integral, index,
+                                        numElements.getType());
+    index = cgf.getBuilder().createMul(index, numElements);
+
+    if (cgf.getLangOpts().isSignedOverflowDefined()) {
+      assert(!cir::MissingFeatures::opPtrStride());
+      cgf.cgm.errorNYI("pointer stride");
+    } else {
+      pointer = cgf.emitCheckedInBoundsGEP(elemTy, pointer, index, isSigned,
+                                           isSubtraction, op.e->getExprLoc());
+    }
+
+    return pointer;
+  }
+  // Explicitly handle GNU void* and function pointer arithmetic extensions. The
+  // GNU void* casts amount to no-ops since our void* type is i8*, but this is
+  // future proof.
+  mlir::Type elemTy;
+  if (elementType->isVoidType() || elementType->isFunctionType())
+    elemTy = cgf.UInt8Ty;
+  else
+    elemTy = cgf.convertTypeForMem(elementType);
+
+  if (cgf.getLangOpts().isSignedOverflowDefined()) {
+    assert(!cir::MissingFeatures::opPtrStride());
+    cgf.cgm.errorNYI("pointer stride");
+    return pointer;
+  }
+
+  return cgf.emitCheckedInBoundsGEP(elemTy, pointer, index, isSigned,
+                                    isSubtraction, op.e->getExprLoc());
+}
+
+mlir::Value ScalarExprEmitter::emitMul(const BinOpInfo &ops) {
+  if (ops.compType->isSignedIntegerOrEnumerationType()) {
+    switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
+    case LangOptions::SOB_Defined:
+      if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
+        return builder.createMul(ops.lhs, ops.rhs);
+      [[fallthrough]];
+    case LangOptions::SOB_Undefined:
+      if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
+        return builder.createNSWMul(ops.lhs, ops.rhs);
+      [[fallthrough]];
+    case LangOptions::SOB_Trapping:
+      if (canElideOverflowCheck(cgf.getContext(), ops))
+        return builder.createNSWMul(ops.lhs, ops.rhs);
+      cgf.cgm.errorNYI("sanitizers");
+    }
+  }
+  if (ops.fullType->isConstantMatrixType()) {
+    assert(!cir::MissingFeatures::matrixType());
+    cgf.cgm.errorNYI("matrix types");
+    return nullptr;
+  }
+  if (ops.compType->isUnsignedIntegerType() &&
+      cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
+      !canElideOverflowCheck(cgf.getContext(), ops))
+    cgf.cgm.errorNYI("unsigned int overflow sanitizer");
+
+  if (cir::isFPOrFPVectorTy(ops.lhs.getType())) {
+    assert(!cir::MissingFeatures::cgFPOptionsRAII());
+    return builder.createFMul(ops.lhs, ops.rhs);
+  }
+
+  if (ops.isFixedPointOp()) {
+    assert(!cir::MissingFeatures::fixedPointType());
+    cgf.cgm.errorNYI("fixed point");
+    return nullptr;
+  }
+
+  return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
+                                    cgf.convertType(ops.fullType),
+                                    cir::BinOpKind::Mul, ops.lhs, ops.rhs);
+}
+mlir::Value ScalarExprEmitter::emitDiv(const BinOpInfo &ops) {
+  return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
+                                    cgf.convertType(ops.fullType),
+                                    cir::BinOpKind::Div, ops.lhs, ops.rhs);
+}
+mlir::Value ScalarExprEmitter::emitRem(const BinOpInfo &ops) {
+  return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
+                                    cgf.convertType(ops.fullType),
+                                    cir::BinOpKind::Rem, ops.lhs, ops.rhs);
+}
+
+mlir::Value ScalarExprEmitter::emitAdd(const BinOpInfo &ops) {
+  if (mlir::isa<cir::PointerType>(ops.lhs.getType()) ||
+      mlir::isa<cir::PointerType>(ops.rhs.getType()))
+    return emitPointerArithmetic(cgf, ops, /*isSubtraction=*/false);
+  if (ops.compType->isSignedIntegerOrEnumerationType()) {
+    switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
+    case LangOptions::SOB_Defined:
+      if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
+        return builder.createAdd(ops.lhs, ops.rhs);
+      [[fallthrough]];
+    case LangOptions::SOB_Undefined:
+      if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
+        return builder.createNSWAdd(ops.lhs, ops.rhs);
+      [[fallthrough]];
+    case LangOptions::SOB_Trapping:
+      if (canElideOverflowCheck(cgf.getContext(), ops))
+        return builder.createNSWAdd(ops.lhs, ops.rhs);
+      cgf.cgm.errorNYI("sanitizers");
+    }
+  }
+  if (ops.fullType->isConstantMatrixType()) {
+    assert(!cir::MissingFeatures::matrixType());
+    cgf.cgm.errorNYI("matrix types");
+    return nullptr;
+  }
+
+  if (ops.compType->isUnsignedIntegerType() &&
+      cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
+      !canElideOverflowCheck(cgf.getContext(), ops))
+    cgf.cgm.errorNYI("unsigned int overflow sanitizer");
+
+  if (cir::isFPOrFPVectorTy(ops.lhs.getType())) {
+    assert(!cir::MissingFeatures::cgFPOptionsRAII());
+    return builder.createFAdd(ops.lhs, ops.rhs);
+  }
+
+  if (ops.isFixedPointOp()) {
+    assert(!cir::MissingFeatures::fixedPointType());
+    cgf.cgm.errorNYI("fixed point");
+    return {};
+  }
+
+  return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
+                                    cgf.convertType(ops.fullType),
+                                    cir::BinOpKind::Add, ops.lhs, ops.rhs);
+}
+
+mlir::Value ScalarExprEmitter::emitSub(const BinOpInfo &ops) {
+  // The LHS is always a pointer if either side is.
+  if (!mlir::isa<cir::PointerType>(ops.lhs.getType())) {
+    if (ops.compType->isSignedIntegerOrEnumerationType()) {
+      switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
+      case LangOptions::SOB_Defined: {
+        if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
+          return builder.createSub(ops.lhs, ops.rhs);
+        [[fallthrough]];
+      }
+      case LangOptions::SOB_Undefined:
+        if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
+          return builder.createNSWSub(ops.lhs, ops.rhs);
+        [[fallthrough]];
+      case LangOptions::SOB_Trapping:
+        if (canElideOverflowCheck(cgf.getContext(), ops))
+          return builder.createNSWSub(ops.lhs, ops.rhs);
+        cgf.cgm.errorNYI("sanitizers");
+      }
+    }
+
+    if (ops.fullType->isConstantMatrixType()) {
+      assert(!cir::MissingFeatures::matrixType());
+      cgf.cgm.errorNYI("matrix types");
+      return nullptr;
+    }
+
+    if (ops.compType->isUnsignedIntegerType() &&
+        cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
+        !canElideOverflowCheck(cgf.getContext(), ops))
+      cgf.cgm.errorNYI("unsigned int overflow sanitizer");
+
+    if (cir::isFPOrFPVectorTy(ops.lhs.getType())) {
+      assert(!cir::MissingFeatures::cgFPOptionsRAII());
+      return builder.createFSub(ops.lhs, ops.rhs);
+    }
+
+    if (ops.isFixedPointOp()) {
+      assert(!cir::MissingFeatures::fixedPointType());
+      cgf.cgm.errorNYI("fixed point");
+      return {};
+    }
+
+    return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
+                                      cgf.convertType(ops.fullType),
+                                      cir::BinOpKind::Sub, ops.lhs, ops.rhs);
+  }
+
+  // If the RHS is not a pointer, then we have normal pointer
+  // arithmetic.
+  if (!mlir::isa<cir::PointerType>(ops.rhs.getType()))
+    return emitPointerArithmetic(cgf, ops, /*isSubtraction=*/true);
+
+  // Otherwise, this is a pointer subtraction
+
+  // Do the raw subtraction part.
+  //
+  // TODO(cir): note for LLVM lowering out of this; when expanding this into
+  // LLVM we shall take VLA's, division by element size, etc.
+  //
+  // See more in `EmitSub` in CGExprScalar.cpp.
+  assert(!cir::MissingFeatures::opPtrDiff());
+  cgf.cgm.errorNYI("ptrdiff");
+  return {};
+}
+
+mlir::Value ScalarExprEmitter::emitShl(const BinOpInfo &ops) {
+  // TODO: This misses out on the sanitizer check below.
+  if (ops.isFixedPointOp()) {
+    assert(cir::MissingFeatures::fixedPointType());
+    cgf.cgm.errorNYI("fixed point");
+    return {};
+  }
+
+  // CIR accepts shift between different types, meaning nothing special
+  // to be done here. OTOH, LLVM requires the LHS and RHS to be the same type:
+  // promote or truncate the RHS to the same size as the LHS.
+
+  bool sanitizeSignedBase = cgf.sanOpts.has(SanitizerKind::ShiftBase) &&
+                            ops.compType->hasSignedIntegerRepresentation() &&
+                            !cgf.getLangOpts().isSignedOverflowDefined() &&
+                            !cgf.getLangOpts().CPlusPlus20;
+  bool sanitizeUnsignedBase =
+      cgf.sanOpts.has(SanitizerKind::UnsignedShiftBase) &&
+      ops.compType->hasUnsignedIntegerRepresentation();
+  bool sanitizeBase = sanitizeSignedBase || sanitizeUnsignedBase;
+  bool sanitizeExponent = cgf.sanOpts.has(SanitizerKind::ShiftExponent);
+
+  // OpenCL 6.3j: shift values are effectively % word size of LHS.
+  if (cgf.getLangOpts().OpenCL)
+    cgf.cgm.errorNYI("opencl");
+  else if ((sanitizeBase || sanitizeExponent) &&
+           mlir::isa<cir::IntType>(ops.lhs.getType()))
+    cgf.cgm.errorNYI("sanitizers");
+
+  cgf.cgm.errorNYI("shift ops");
+  return {};
+}
+
+mlir::Value ScalarExprEmitter::emitShr(const BinOpInfo &ops) {
+  // TODO: This misses out on the sanitizer check below.
+  if (ops.isFixedPointOp()) {
+    assert(cir::MissingFeatures::fixedPointType());
+    cgf.cgm.errorNYI("fixed point");
+    return {};
+  }
+
+  // CIR accepts shift between different types, meaning nothing special
+  // to be done here. OTOH, LLVM requires the LHS and RHS to be the same type:
+  // promote or truncate the RHS to the same size as the LHS.
+
+  // OpenCL 6.3j: shift values are effectively % word size of LHS.
+  if (cgf.getLangOpts().OpenCL)
+    cgf.cgm.errorNYI("opencl");
+  else if (cgf.sanOpts.has(SanitizerKind::ShiftExponent) &&
+           mlir::isa<cir::IntType>(ops.lhs.getType()))
+    cgf.cgm.errorNYI("sanitizers");
+
+  // Note that we don't need to distinguish unsigned treatment at this
+  // point since it will be handled later by LLVM lowering.
+  cgf.cgm.errorNYI("shift ops");
+  return {};
+}
+
+mlir::Value ScalarExprEmitter::emitAnd(const BinOpInfo &ops) {
+  return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
+                                    cgf.convertType(ops.fullType),
+                                    cir::BinOpKind::And, ops.lhs, ops.rhs);
+}
+mlir::Value ScalarExprEmitter::emitXor(const BinOpInfo &ops) {
+  return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
+                                    cgf.convertType(ops.fullType),
+                                    cir::BinOpKind::Xor, ops.lhs, ops.rhs);
+}
+mlir::Value ScalarExprEmitter::emitOr(const BinOpInfo &ops) {
+  return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
+                                    cgf.convertType(ops.fullType),
+                                    cir::BinOpKind::Or, ops.lhs, ops.rhs);
+}
+
 // Emit code for an explicit or implicit cast.  Implicit
 // casts have to handle a more broad range of conversions than explicit
 // casts, as they handle things like function to ptr-to-function decay
@@ -661,7 +1356,7 @@ mlir::Value ScalarExprEmitter::VisitCastExpr(CastExpr *ce) {
   }
 
   case CK_NullToPointer: {
-    if (MustVisitNullValue(subExpr))
+    if (mustVisitNullValue(subExpr))
       cgf.emitIgnoredExpr(subExpr);
 
     // Note that DestTy is used as the MLIR type instead of a custom
@@ -790,9 +1485,26 @@ mlir::Value ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
                cgf.cgm.UInt64Ty, e->EvaluateKnownConstInt(cgf.getContext())));
 }
 
-mlir::Value CIRGenFunction::emitScalarPrePostIncDec(const UnaryOperator *E,
-                                                    LValue LV, bool isInc,
+mlir::Value CIRGenFunction::emitScalarPrePostIncDec(const UnaryOperator *e,
+                                                    LValue lv, bool isInc,
                                                     bool isPre) {
   return ScalarExprEmitter(*this, builder)
-      .emitScalarPrePostIncDec(E, LV, isInc, isPre);
+      .emitScalarPrePostIncDec(e, lv, isInc, isPre);
+}
+
+mlir::Value CIRGenFunction::emitCheckedInBoundsGEP(
+    mlir::Type elemTy, mlir::Value ptr, ArrayRef<mlir::Value> idxList,
+    bool signedIndices, bool isSubtraction, SourceLocation loc) {
+  assert(idxList.size() == 1 && "multi-index ptr arithmetic NYI");
+  assert(!cir::MissingFeatures::opPtrStride());
+  mlir::Value gepVal = nullptr;
+
+  // If the pointer overflow sanitizer isn't enabled, do nothing.
+  if (!sanOpts.has(SanitizerKind::PointerOverflow))
+    return gepVal;
+  return ptr;
+
+  assert(!cir::MissingFeatures::pointerOverflowSanitizer());
+  cgm.errorNYI("pointer overflow sanitizer");
+  return nullptr;
 }
diff --git a/clang/lib/CIR/CodeGen/CIRGenFunction.cpp b/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
index 16547f2401292..4ba3d416007f2 100644
--- a/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenFunction.cpp
@@ -444,6 +444,8 @@ LValue CIRGenFunction::emitLValue(const Expr *e) {
     return LValue();
   case Expr::UnaryOperatorClass:
     return emitUnaryOpLValue(cast<UnaryOperator>(e));
+  case Expr::BinaryOperatorClass:
+    return emitBinaryOperatorLValue(cast<BinaryOperator>(e));
   case Expr::DeclRefExprClass:
     return emitDeclRefLValue(cast<DeclRefExpr>(e));
   }
diff --git a/clang/lib/CIR/CodeGen/CIRGenFunction.h b/clang/lib/CIR/CodeGen/CIRGenFunction.h
index 631217cf67762..aaf70603f7782 100644
--- a/clang/lib/CIR/CodeGen/CIRGenFunction.h
+++ b/clang/lib/CIR/CodeGen/CIRGenFunction.h
@@ -29,8 +29,6 @@
 #include "clang/CIR/MissingFeatures.h"
 #include "clang/CIR/TypeEvaluationKind.h"
 
-#include "llvm/ADT/ScopedHashTable.h"
-
 namespace {
 class ScalarExprEmitter;
 } // namespace
@@ -62,7 +60,7 @@ class CIRGenFunction : public CIRGenTypeCache {
   using DeclMapTy = llvm::DenseMap<const clang::Decl *, Address>;
   /// This keeps track of the CIR allocas or globals for local C
   /// declarations.
-  DeclMapTy LocalDeclMap;
+  DeclMapTy localDeclMap;
 
   clang::ASTContext &getContext() const { return cgm.getASTContext(); }
 
@@ -80,11 +78,11 @@ class CIRGenFunction : public CIRGenTypeCache {
   /// this fuction. These can potentially set the return value.
   bool sawAsmBlock = false;
 
-  mlir::Type convertTypeForMem(QualType T);
+  mlir::Type convertTypeForMem(QualType t);
 
-  mlir::Type convertType(clang::QualType T);
-  mlir::Type convertType(const TypeDecl *T) {
-    return convertType(getContext().getTypeDeclType(T));
+  mlir::Type convertType(clang::QualType t);
+  mlir::Type convertType(const TypeDecl *t) {
+    return convertType(getContext().getTypeDeclType(t));
   }
 
   ///  Return the cir::TypeEvaluationKind of QualType \c type.
@@ -219,11 +217,22 @@ class CIRGenFunction : public CIRGenTypeCache {
 
   void emitDecl(const clang::Decl &d);
 
+  /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
+  /// detect undefined behavior when the pointer overflow sanitizer is enabled.
+  /// \p SignedIndices indicates whether any of the GEP indices are signed.
+  /// \p IsSubtraction indicates whether the expression used to form the GEP
+  /// is a subtraction.
+  mlir::Value emitCheckedInBoundsGEP(mlir::Type elemTy, mlir::Value ptr,
+                                     llvm::ArrayRef<mlir::Value> idxList,
+                                     bool signedIndices, bool isSubtraction,
+                                     SourceLocation loc);
+
   void emitScalarInit(const clang::Expr *init, mlir::Location loc,
                       LValue lvalue, bool capturedByInit = false);
 
   LValue emitDeclRefLValue(const clang::DeclRefExpr *e);
   LValue emitUnaryOpLValue(const clang::UnaryOperator *e);
+  LValue emitBinaryOperatorLValue(const BinaryOperator *e);
 
   /// Determine whether the given initializer is trivial in the sense
   /// that it requires no code to be generated.
@@ -322,8 +331,8 @@ class CIRGenFunction : public CIRGenTypeCache {
 
   /// Set the address of a local variable.
   void setAddrOfLocalVar(const clang::VarDecl *vd, Address addr) {
-    assert(!LocalDeclMap.count(vd) && "Decl already exists in LocalDeclMap!");
-    LocalDeclMap.insert({vd, addr});
+    assert(!localDeclMap.count(vd) && "Decl already exists in LocalDeclMap!");
+    localDeclMap.insert({vd, addr});
     // TODO: Add symbol table support
   }
 
@@ -332,6 +341,7 @@ class CIRGenFunction : public CIRGenTypeCache {
 
   /// Emit the computation of the specified expression of scalar type.
   mlir::Value emitScalarExpr(const clang::Expr *e);
+  mlir::Value emitPromotedScalarExpr(const Expr *e, QualType promotionType);
   cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn,
                            cir::FuncType funcType);
 
@@ -341,7 +351,7 @@ class CIRGenFunction : public CIRGenTypeCache {
   /// Emit code for the start of a function.
   /// \param loc       The location to be associated with the function.
   /// \param startLoc  The location of the function body.
-  void startFunction(clang::GlobalDecl gd, clang::QualType retTy,
+  void startFunction(clang::GlobalDecl gd, clang::QualType returnType,
                      cir::FuncOp fn, cir::FuncType funcType,
                      FunctionArgList args, clang::SourceLocation loc,
                      clang::SourceLocation startLoc);
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
index ae86fefcf3657..cdcfa77b66379 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
@@ -75,8 +75,8 @@ void cir::CIRDialect::initialize() {
 
 // Check if a region's termination omission is valid and, if so, creates and
 // inserts the omitted terminator into the region.
-LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region,
-                               SMLoc errLoc) {
+static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region,
+                                      SMLoc errLoc) {
   Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
   OpBuilder builder(parser.getBuilder().getContext());
 
@@ -102,7 +102,7 @@ LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region,
 }
 
 // True if the region's terminator should be omitted.
-bool omitRegionTerm(mlir::Region &r) {
+static bool omitRegionTerm(mlir::Region &r) {
   const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
   const auto yieldsNothing = [&r]() {
     auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
@@ -346,9 +346,9 @@ LogicalResult cir::CastOp::verify() {
       return emitOpError() << "requires two types differ in addrspace only";
     return success();
   }
+  default:
+    llvm_unreachable("Unknown CastOp kind?");
   }
-
-  llvm_unreachable("Unknown CastOp kind?");
 }
 
 static bool isIntOrBoolCast(cir::CastOp op) {
@@ -728,6 +728,37 @@ void cir::FuncOp::print(OpAsmPrinter &p) {
 // been implemented yet.
 mlir::LogicalResult cir::FuncOp::verify() { return success(); }
 
+LogicalResult cir::BinOp::verify() {
+  bool noWrap = getNoUnsignedWrap() || getNoSignedWrap();
+  bool saturated = getSaturated();
+
+  if (!isa<cir::IntType>(getType()) && noWrap)
+    return emitError()
+           << "only operations on integer values may have nsw/nuw flags";
+
+  bool noWrapOps = getKind() == cir::BinOpKind::Add ||
+                   getKind() == cir::BinOpKind::Sub ||
+                   getKind() == cir::BinOpKind::Mul;
+
+  bool saturatedOps =
+      getKind() == cir::BinOpKind::Add || getKind() == cir::BinOpKind::Sub;
+
+  if (noWrap && !noWrapOps)
+    return emitError() << "The nsw/nuw flags are applicable to opcodes: 'add', "
+                          "'sub' and 'mul'";
+  if (saturated && !saturatedOps)
+    return emitError() << "The saturated flag is applicable to opcodes: 'add' "
+                          "and 'sub'";
+  if (noWrap && saturated)
+    return emitError() << "The nsw/nuw flags and the saturated flag are "
+                          "mutually exclusive";
+
+  assert(!cir::MissingFeatures::complexType());
+  // TODO(cir): verify for complex binops
+
+  return mlir::success();
+}
+
 //===----------------------------------------------------------------------===//
 // UnaryOp
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/CIR/Dialect/IR/CIRTypes.cpp b/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
index 6291297492227..356f7f6244db8 100644
--- a/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRTypes.cpp
@@ -14,6 +14,7 @@
 
 #include "mlir/IR/DialectImplementation.h"
 #include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "clang/CIR/MissingFeatures.h"
 #include "llvm/ADT/TypeSwitch.h"
 
 //===----------------------------------------------------------------------===//
@@ -274,6 +275,15 @@ bool cir::isAnyFloatingPointType(mlir::Type t) {
              cir::FP80Type, cir::BF16Type, cir::FP16Type, cir::FP128Type>(t);
 }
 
+//===----------------------------------------------------------------------===//
+// Floating-point and Float-point Vector type helpers
+//===----------------------------------------------------------------------===//
+
+bool cir::isFPOrFPVectorTy(mlir::Type t) {
+  assert(!cir::MissingFeatures::vectorType());
+  return isAnyFloatingPointType(t);
+}
+
 //===----------------------------------------------------------------------===//
 // FuncType Definitions
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 30cbee48b4bdc..c0588ed906d95 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -32,7 +32,6 @@
 #include "clang/CIR/Passes.h"
 #include "llvm/ADT/TypeSwitch.h"
 #include "llvm/IR/Module.h"
-#include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TimeProfiler.h"
 
@@ -85,12 +84,11 @@ static mlir::Value createIntCast(mlir::OpBuilder &bld, mlir::Value src,
 
   if (dstWidth > srcWidth && isSigned)
     return bld.create<mlir::LLVM::SExtOp>(loc, dstTy, src);
-  else if (dstWidth > srcWidth)
+  if (dstWidth > srcWidth)
     return bld.create<mlir::LLVM::ZExtOp>(loc, dstTy, src);
-  else if (dstWidth < srcWidth)
+  if (dstWidth < srcWidth)
     return bld.create<mlir::LLVM::TruncOp>(loc, dstTy, src);
-  else
-    return bld.create<mlir::LLVM::BitcastOp>(loc, dstTy, src);
+  return bld.create<mlir::LLVM::BitcastOp>(loc, dstTy, src);
 }
 
 /// Emits the value from memory as expected by its users. Should be called when
@@ -994,6 +992,239 @@ mlir::LogicalResult CIRToLLVMUnaryOpLowering::matchAndRewrite(
                         << elementType;
 }
 
+mlir::LLVM::IntegerOverflowFlags
+CIRToLLVMBinOpLowering::getIntOverflowFlag(cir::BinOp op) const {
+  if (op.getNoUnsignedWrap())
+    return mlir::LLVM::IntegerOverflowFlags::nuw;
+
+  if (op.getNoSignedWrap())
+    return mlir::LLVM::IntegerOverflowFlags::nsw;
+
+  return mlir::LLVM::IntegerOverflowFlags::none;
+}
+
+static bool isIntTypeUnsigned(mlir::Type type) {
+  // TODO: Ideally, we should only need to check cir::IntType here.
+  return mlir::isa<cir::IntType>(type)
+             ? mlir::cast<cir::IntType>(type).isUnsigned()
+             : mlir::cast<mlir::IntegerType>(type).isUnsigned();
+}
+
+mlir::LogicalResult CIRToLLVMBinOpLowering::matchAndRewrite(
+    cir::BinOp op, OpAdaptor adaptor,
+    mlir::ConversionPatternRewriter &rewriter) const {
+  if (adaptor.getLhs().getType() != adaptor.getRhs().getType())
+    return op.emitError() << "inconsistent operands' types not supported yet";
+
+  mlir::Type type = op.getRhs().getType();
+  assert(!cir::MissingFeatures::vectorType());
+  if (!mlir::isa<cir::IntType, cir::BoolType, cir::CIRFPTypeInterface,
+                 mlir::IntegerType>(type))
+    return op.emitError() << "operand type not supported yet";
+
+  auto llvmTy = getTypeConverter()->convertType(op.getType());
+  mlir::Type llvmEltTy =
+      mlir::isa<mlir::VectorType>(llvmTy)
+          ? mlir::cast<mlir::VectorType>(llvmTy).getElementType()
+          : llvmTy;
+  auto rhs = adaptor.getRhs();
+  auto lhs = adaptor.getLhs();
+
+  type = elementTypeIfVector(type);
+
+  switch (op.getKind()) {
+  case cir::BinOpKind::Add:
+    if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
+      if (op.getSaturated()) {
+        if (isIntTypeUnsigned(type)) {
+          rewriter.replaceOpWithNewOp<mlir::LLVM::UAddSat>(op, lhs, rhs);
+          break;
+        }
+        rewriter.replaceOpWithNewOp<mlir::LLVM::SAddSat>(op, lhs, rhs);
+        break;
+      }
+      rewriter.replaceOpWithNewOp<mlir::LLVM::AddOp>(op, llvmTy, lhs, rhs,
+                                                     getIntOverflowFlag(op));
+    } else
+      rewriter.replaceOpWithNewOp<mlir::LLVM::FAddOp>(op, lhs, rhs);
+    break;
+  case cir::BinOpKind::Sub:
+    if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
+      if (op.getSaturated()) {
+        if (isIntTypeUnsigned(type)) {
+          rewriter.replaceOpWithNewOp<mlir::LLVM::USubSat>(op, lhs, rhs);
+          break;
+        }
+        rewriter.replaceOpWithNewOp<mlir::LLVM::SSubSat>(op, lhs, rhs);
+        break;
+      }
+      rewriter.replaceOpWithNewOp<mlir::LLVM::SubOp>(op, llvmTy, lhs, rhs,
+                                                     getIntOverflowFlag(op));
+    } else
+      rewriter.replaceOpWithNewOp<mlir::LLVM::FSubOp>(op, lhs, rhs);
+    break;
+  case cir::BinOpKind::Mul:
+    if (mlir::isa<mlir::IntegerType>(llvmEltTy))
+      rewriter.replaceOpWithNewOp<mlir::LLVM::MulOp>(op, llvmTy, lhs, rhs,
+                                                     getIntOverflowFlag(op));
+    else
+      rewriter.replaceOpWithNewOp<mlir::LLVM::FMulOp>(op, lhs, rhs);
+    break;
+  case cir::BinOpKind::Div:
+    if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
+      auto isUnsigned = isIntTypeUnsigned(type);
+      if (isUnsigned)
+        rewriter.replaceOpWithNewOp<mlir::LLVM::UDivOp>(op, lhs, rhs);
+      else
+        rewriter.replaceOpWithNewOp<mlir::LLVM::SDivOp>(op, lhs, rhs);
+    } else
+      rewriter.replaceOpWithNewOp<mlir::LLVM::FDivOp>(op, lhs, rhs);
+    break;
+  case cir::BinOpKind::Rem:
+    if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
+      auto isUnsigned = isIntTypeUnsigned(type);
+      if (isUnsigned)
+        rewriter.replaceOpWithNewOp<mlir::LLVM::URemOp>(op, lhs, rhs);
+      else
+        rewriter.replaceOpWithNewOp<mlir::LLVM::SRemOp>(op, lhs, rhs);
+    } else
+      rewriter.replaceOpWithNewOp<mlir::LLVM::FRemOp>(op, lhs, rhs);
+    break;
+  case cir::BinOpKind::And:
+    rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(op, lhs, rhs);
+    break;
+  case cir::BinOpKind::Or:
+    rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(op, lhs, rhs);
+    break;
+  case cir::BinOpKind::Xor:
+    rewriter.replaceOpWithNewOp<mlir::LLVM::XOrOp>(op, lhs, rhs);
+    break;
+  case cir::BinOpKind::Max:
+    if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
+      auto isUnsigned = isIntTypeUnsigned(type);
+      if (isUnsigned)
+        rewriter.replaceOpWithNewOp<mlir::LLVM::UMaxOp>(op, llvmTy, lhs, rhs);
+      else
+        rewriter.replaceOpWithNewOp<mlir::LLVM::SMaxOp>(op, llvmTy, lhs, rhs);
+    }
+    break;
+  }
+
+  return mlir::LogicalResult::success();
+}
+
+mlir::LogicalResult CIRToLLVMBinOpOverflowOpLowering::matchAndRewrite(
+    cir::BinOpOverflowOp op, OpAdaptor adaptor,
+    mlir::ConversionPatternRewriter &rewriter) const {
+  auto loc = op.getLoc();
+  auto arithKind = op.getKind();
+  auto operandTy = op.getLhs().getType();
+  auto resultTy = op.getResult().getType();
+
+  auto encompassedTyInfo = computeEncompassedTypeWidth(operandTy, resultTy);
+  auto encompassedLLVMTy = rewriter.getIntegerType(encompassedTyInfo.width);
+
+  auto lhs = adaptor.getLhs();
+  auto rhs = adaptor.getRhs();
+  if (operandTy.getWidth() < encompassedTyInfo.width) {
+    if (operandTy.isSigned()) {
+      lhs = rewriter.create<mlir::LLVM::SExtOp>(loc, encompassedLLVMTy, lhs);
+      rhs = rewriter.create<mlir::LLVM::SExtOp>(loc, encompassedLLVMTy, rhs);
+    } else {
+      lhs = rewriter.create<mlir::LLVM::ZExtOp>(loc, encompassedLLVMTy, lhs);
+      rhs = rewriter.create<mlir::LLVM::ZExtOp>(loc, encompassedLLVMTy, rhs);
+    }
+  }
+
+  auto intrinName = getLLVMIntrinName(arithKind, encompassedTyInfo.sign,
+                                      encompassedTyInfo.width);
+  auto intrinNameAttr = mlir::StringAttr::get(op.getContext(), intrinName);
+
+  auto overflowLLVMTy = rewriter.getI1Type();
+  auto intrinRetTy = mlir::LLVM::LLVMStructType::getLiteral(
+      rewriter.getContext(), {encompassedLLVMTy, overflowLLVMTy});
+
+  auto callLLVMIntrinOp = rewriter.create<mlir::LLVM::CallIntrinsicOp>(
+      loc, intrinRetTy, intrinNameAttr, mlir::ValueRange{lhs, rhs});
+  auto intrinRet = callLLVMIntrinOp.getResult(0);
+
+  auto result = rewriter
+                    .create<mlir::LLVM::ExtractValueOp>(loc, intrinRet,
+                                                        ArrayRef<int64_t>{0})
+                    .getResult();
+  auto overflow = rewriter
+                      .create<mlir::LLVM::ExtractValueOp>(loc, intrinRet,
+                                                          ArrayRef<int64_t>{1})
+                      .getResult();
+
+  if (resultTy.getWidth() < encompassedTyInfo.width) {
+    auto resultLLVMTy = getTypeConverter()->convertType(resultTy);
+    auto truncResult =
+        rewriter.create<mlir::LLVM::TruncOp>(loc, resultLLVMTy, result);
+
+    // Extend the truncated result back to the encompassing type to check for
+    // any overflows during the truncation.
+    mlir::Value truncResultExt;
+    if (resultTy.isSigned())
+      truncResultExt = rewriter.create<mlir::LLVM::SExtOp>(
+          loc, encompassedLLVMTy, truncResult);
+    else
+      truncResultExt = rewriter.create<mlir::LLVM::ZExtOp>(
+          loc, encompassedLLVMTy, truncResult);
+    auto truncOverflow = rewriter.create<mlir::LLVM::ICmpOp>(
+        loc, mlir::LLVM::ICmpPredicate::ne, truncResultExt, result);
+
+    result = truncResult;
+    overflow = rewriter.create<mlir::LLVM::OrOp>(loc, overflow, truncOverflow);
+  }
+
+  auto boolLLVMTy = getTypeConverter()->convertType(op.getOverflow().getType());
+  if (boolLLVMTy != rewriter.getI1Type())
+    overflow = rewriter.create<mlir::LLVM::ZExtOp>(loc, boolLLVMTy, overflow);
+
+  rewriter.replaceOp(op, mlir::ValueRange{result, overflow});
+
+  return mlir::success();
+}
+
+std::string CIRToLLVMBinOpOverflowOpLowering::getLLVMIntrinName(
+    cir::BinOpOverflowKind opKind, bool isSigned, unsigned width) {
+  // The intrinsic name is `@llvm.{s|u}{opKind}.with.overflow.i{width}`
+
+  std::string name = "llvm.";
+
+  if (isSigned)
+    name.push_back('s');
+  else
+    name.push_back('u');
+
+  switch (opKind) {
+  case cir::BinOpOverflowKind::Add:
+    name.append("add.");
+    break;
+  case cir::BinOpOverflowKind::Sub:
+    name.append("sub.");
+    break;
+  case cir::BinOpOverflowKind::Mul:
+    name.append("mul.");
+    break;
+  }
+
+  name.append("with.overflow.i");
+  name.append(std::to_string(width));
+
+  return name;
+}
+
+CIRToLLVMBinOpOverflowOpLowering::EncompassedTypeInfo
+CIRToLLVMBinOpOverflowOpLowering::computeEncompassedTypeWidth(
+    cir::IntType operandTy, cir::IntType resultTy) {
+  auto sign = operandTy.getIsSigned() || resultTy.getIsSigned();
+  auto width = std::max(operandTy.getWidth() + (sign && operandTy.isUnsigned()),
+                        resultTy.getWidth() + (sign && resultTy.isUnsigned()));
+  return {sign, width};
+}
+
 static void prepareTypeConverter(mlir::LLVMTypeConverter &converter,
                                  mlir::DataLayout &dataLayout) {
   converter.addConversion([&](cir::PointerType type) -> mlir::Type {
@@ -1133,6 +1364,8 @@ void ConvertCIRToLLVMPass::runOnOperation() {
   patterns.add<
       // clang-format off
                CIRToLLVMBrCondOpLowering,
+               CIRToLLVMBinOpLowering,
+               CIRToLLVMBinOpOverflowOpLowering,
                CIRToLLVMBrOpLowering,
                CIRToLLVMFuncOpLowering,
                CIRToLLVMTrapOpLowering,
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
index a01a9a5f4f076..9fb8babe3dd6c 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
@@ -178,6 +178,39 @@ class CIRToLLVMUnaryOpLowering
                   mlir::ConversionPatternRewriter &) const override;
 };
 
+class CIRToLLVMBinOpLowering : public mlir::OpConversionPattern<cir::BinOp> {
+  mlir::LLVM::IntegerOverflowFlags getIntOverflowFlag(cir::BinOp op) const;
+
+public:
+  using mlir::OpConversionPattern<cir::BinOp>::OpConversionPattern;
+
+  mlir::LogicalResult
+  matchAndRewrite(cir::BinOp op, OpAdaptor,
+                  mlir::ConversionPatternRewriter &) const override;
+};
+
+class CIRToLLVMBinOpOverflowOpLowering
+    : public mlir::OpConversionPattern<cir::BinOpOverflowOp> {
+public:
+  using mlir::OpConversionPattern<cir::BinOpOverflowOp>::OpConversionPattern;
+
+  mlir::LogicalResult
+  matchAndRewrite(cir::BinOpOverflowOp op, OpAdaptor,
+                  mlir::ConversionPatternRewriter &) const override;
+
+private:
+  static std::string getLLVMIntrinName(cir::BinOpOverflowKind opKind,
+                                       bool isSigned, unsigned width);
+
+  struct EncompassedTypeInfo {
+    bool sign;
+    unsigned width;
+  };
+
+  static EncompassedTypeInfo computeEncompassedTypeWidth(cir::IntType operandTy,
+                                                         cir::IntType resultTy);
+};
+
 class CIRToLLVMBrOpLowering : public mlir::OpConversionPattern<cir::BrOp> {
 public:
   using mlir::OpConversionPattern<cir::BrOp>::OpConversionPattern;
diff --git a/clang/test/CIR/CodeGen/binop.cpp b/clang/test/CIR/CodeGen/binop.cpp
new file mode 100644
index 0000000000000..4c20f79600fac
--- /dev/null
+++ b/clang/test/CIR/CodeGen/binop.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -O1 -Wno-unused-value -fclangir -emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s
+
+void b0(int a, int b) {
+  int x = a * b;
+  x = x / b;
+  x = x % b;
+  x = x + b;
+  x = x - b;
+  x = x & b;
+  x = x ^ b;
+  x = x | b;
+}
+
+// CHECK: %{{.+}} = cir.binop(mul, %{{.+}}, %{{.+}}) nsw : !s32i
+// CHECK: %{{.+}} = cir.binop(div, %{{.+}}, %{{.+}}) : !s32i
+// CHECK: %{{.+}} = cir.binop(rem, %{{.+}}, %{{.+}}) : !s32i
+// CHECK: %{{.+}} = cir.binop(add, %{{.+}}, %{{.+}}) nsw : !s32i
+// CHECK: %{{.+}} = cir.binop(sub, %{{.+}}, %{{.+}}) nsw : !s32i
+// CHECK: %{{.+}} = cir.binop(and, %{{.+}}, %{{.+}}) : !s32i
+// CHECK: %{{.+}} = cir.binop(xor, %{{.+}}, %{{.+}}) : !s32i
+// CHECK: %{{.+}} = cir.binop(or, %{{.+}}, %{{.+}}) : !s32i
+
+void testFloatingPointBinOps(float a, float b) {
+  a * b;
+  // CHECK: cir.binop(mul, %{{.+}}, %{{.+}}) : !cir.float
+  a / b;
+  // CHECK: cir.binop(div, %{{.+}}, %{{.+}}) : !cir.float
+  a + b;
+  // CHECK: cir.binop(add, %{{.+}}, %{{.+}}) : !cir.float
+  a - b;
+  // CHECK: cir.binop(sub, %{{.+}}, %{{.+}}) : !cir.float
+}
diff --git a/clang/test/CIR/Lowering/binop-bool.cir b/clang/test/CIR/Lowering/binop-bool.cir
new file mode 100644
index 0000000000000..7267c407cc0a7
--- /dev/null
+++ b/clang/test/CIR/Lowering/binop-bool.cir
@@ -0,0 +1,18 @@
+// RUN: cir-opt %s -cir-to-llvm -o %t.mlir
+// RUN: FileCheck --input-file=%t.mlir %s
+
+module {
+  cir.func @foo() {
+    %0 = cir.alloca !cir.bool, !cir.ptr<!cir.bool>, ["a", init] {alignment = 4 : i64}
+    %1 = cir.alloca !cir.bool, !cir.ptr<!cir.bool>, ["b", init] {alignment = 4 : i64}
+    %2 = cir.load %0 : !cir.ptr<!cir.bool>, !cir.bool
+    %3 = cir.load %1 : !cir.ptr<!cir.bool>, !cir.bool
+    %4 = cir.binop(or, %2, %3) : !cir.bool
+    // CHECK: = llvm.or {{.*}}, {{.*}} : i1
+    %5 = cir.binop(xor, %2, %3) : !cir.bool
+    // CHECK: = llvm.xor {{.*}}, {{.*}} : i1
+    %6 = cir.binop(and, %2, %3) : !cir.bool
+    // CHECK: = llvm.and {{.*}}, {{.*}} : i1
+    cir.return
+  }
+}
diff --git a/clang/test/CIR/Lowering/binop-fp.cir b/clang/test/CIR/Lowering/binop-fp.cir
new file mode 100644
index 0000000000000..e69a69e6b0991
--- /dev/null
+++ b/clang/test/CIR/Lowering/binop-fp.cir
@@ -0,0 +1,68 @@
+// RUN: cir-opt %s -cir-to-llvm -o - | FileCheck %s -check-prefix=MLIR
+// RUN: cir-translate %s -cir-to-llvmir --target x86_64-unknown-linux-gnu --disable-cc-lowering  | FileCheck %s -check-prefix=LLVM
+
+module {
+  cir.func @foo() {
+    %0 = cir.alloca !cir.float, !cir.ptr<!cir.float>, ["c"] {alignment = 4 : i64}
+    %1 = cir.alloca !cir.float, !cir.ptr<!cir.float>, ["d"] {alignment = 4 : i64}
+    %2 = cir.alloca !cir.float, !cir.ptr<!cir.float>, ["y", init] {alignment = 4 : i64}
+    %3 = cir.alloca !cir.double, !cir.ptr<!cir.double>, ["e"] {alignment = 8 : i64}
+    %4 = cir.alloca !cir.double, !cir.ptr<!cir.double>, ["f"] {alignment = 8 : i64}
+    %5 = cir.alloca !cir.double, !cir.ptr<!cir.double>, ["g", init] {alignment = 8 : i64}
+    %6 = cir.load %0 : !cir.ptr<!cir.float>, !cir.float
+    %7 = cir.load %1 : !cir.ptr<!cir.float>, !cir.float
+    %8 = cir.binop(mul, %6, %7) : !cir.float
+    cir.store %8, %2 : !cir.float, !cir.ptr<!cir.float>
+    %9 = cir.load %2 : !cir.ptr<!cir.float>, !cir.float
+    %10 = cir.load %1 : !cir.ptr<!cir.float>, !cir.float
+    %11 = cir.binop(div, %9, %10) : !cir.float
+    cir.store %11, %2 : !cir.float, !cir.ptr<!cir.float>
+    %12 = cir.load %2 : !cir.ptr<!cir.float>, !cir.float
+    %13 = cir.load %1 : !cir.ptr<!cir.float>, !cir.float
+    %14 = cir.binop(add, %12, %13) : !cir.float
+    cir.store %14, %2 : !cir.float, !cir.ptr<!cir.float>
+    %15 = cir.load %2 : !cir.ptr<!cir.float>, !cir.float
+    %16 = cir.load %1 : !cir.ptr<!cir.float>, !cir.float
+    %17 = cir.binop(sub, %15, %16) : !cir.float
+    cir.store %17, %2 : !cir.float, !cir.ptr<!cir.float>
+    %18 = cir.load %3 : !cir.ptr<!cir.double>, !cir.double
+    %19 = cir.load %4 : !cir.ptr<!cir.double>, !cir.double
+    %20 = cir.binop(add, %18, %19) : !cir.double
+    cir.store %20, %5 : !cir.double, !cir.ptr<!cir.double>
+    %21 = cir.load %3 : !cir.ptr<!cir.double>, !cir.double
+    %22 = cir.load %4 : !cir.ptr<!cir.double>, !cir.double
+    %23 = cir.binop(sub, %21, %22) : !cir.double
+    cir.store %23, %5 : !cir.double, !cir.ptr<!cir.double>
+    %24 = cir.load %3 : !cir.ptr<!cir.double>, !cir.double
+    %25 = cir.load %4 : !cir.ptr<!cir.double>, !cir.double
+    %26 = cir.binop(mul, %24, %25) : !cir.double
+    cir.store %26, %5 : !cir.double, !cir.ptr<!cir.double>
+    %27 = cir.load %3 : !cir.ptr<!cir.double>, !cir.double
+    %28 = cir.load %4 : !cir.ptr<!cir.double>, !cir.double
+    %29 = cir.binop(div, %27, %28) : !cir.double
+    cir.store %29, %5 : !cir.double, !cir.ptr<!cir.double>
+    cir.return
+  }
+}
+
+// MLIR: = llvm.alloca {{.*}} f32 {alignment = 4 : i64} : (i64) -> !llvm.ptr
+// MLIR: = llvm.alloca {{.*}} f64 {alignment = 8 : i64} : (i64) -> !llvm.ptr
+// MLIR: = llvm.fmul {{.*}} : f32
+// MLIR: = llvm.fdiv
+// MLIR: = llvm.fadd
+// MLIR: = llvm.fsub
+// MLIR: = llvm.fadd {{.*}} : f64
+// MLIR: = llvm.fsub
+// MLIR: = llvm.fmul
+// MLIR: = llvm.fdiv
+
+// LLVM: = alloca float, i64
+// LLVM: = alloca double, i64
+// LLVM: = fmul float
+// LLVM: = fdiv float
+// LLVM: = fadd float
+// LLVM: = fsub float
+// LLVM: = fadd double
+// LLVM: = fsub double
+// LLVM: = fmul double
+// LLVM: = fdiv double
diff --git a/clang/test/CIR/Lowering/binop-overflow.cir b/clang/test/CIR/Lowering/binop-overflow.cir
new file mode 100644
index 0000000000000..68af70aa6abb6
--- /dev/null
+++ b/clang/test/CIR/Lowering/binop-overflow.cir
@@ -0,0 +1,63 @@
+// RUN: cir-opt %s -cir-to-llvm -o - | FileCheck %s -check-prefix=MLIR
+// RUN: cir-translate %s -cir-to-llvmir --target x86_64-unknown-linux-gnu --disable-cc-lowering -o -  | FileCheck %s -check-prefix=LLVM
+
+!u32i = !cir.int<u, 32>
+!s32i = !cir.int<s, 32>
+
+module {
+  cir.func @test_add_u32_u32_u32(%lhs: !u32i, %rhs: !u32i, %res: !cir.ptr<!u32i>) -> !cir.bool {
+    %result, %overflow = cir.binop.overflow(add, %lhs, %rhs) : !u32i, (!u32i, !cir.bool)
+    cir.store %result, %res : !u32i, !cir.ptr<!u32i>
+    cir.return %overflow : !cir.bool
+  }
+
+  //      MLIR: llvm.func @test_add_u32_u32_u32(%[[LHS:.+]]: i32, %[[RHS:.+]]: i32, %[[RES_PTR:.+]]: !llvm.ptr) -> i1
+  // MLIR-NEXT:   %[[#INTRIN_RET:]] = llvm.call_intrinsic "llvm.uadd.with.overflow.i32"(%[[LHS]], %[[RHS]]) : (i32, i32) -> !llvm.struct<(i32, i1)>
+  // MLIR-NEXT:   %[[#RES:]] = llvm.extractvalue %[[#INTRIN_RET]][0] : !llvm.struct<(i32, i1)>
+  // MLIR-NEXT:   %[[#OVFL:]] = llvm.extractvalue %[[#INTRIN_RET]][1] : !llvm.struct<(i32, i1)>
+  // MLIR-NEXT:   llvm.store %[[#RES]], %[[RES_PTR]] {{.*}} : i32, !llvm.ptr
+  // MLIR-NEXT:   llvm.return %[[#OVFL]] : i1
+  // MLIR-NEXT: }
+
+  //      LLVM: define i1 @test_add_u32_u32_u32(i32 %[[#LHS:]], i32 %[[#RHS:]], ptr %[[#RES_PTR:]])
+  // LLVM-NEXT:   %[[#INTRIN_RET:]] = call { i32, i1 } @llvm.uadd.with.overflow.i32(i32 %[[#LHS]], i32 %[[#RHS]])
+  // LLVM-NEXT:   %[[#RES:]] = extractvalue { i32, i1 } %[[#INTRIN_RET]], 0
+  // LLVM-NEXT:   %[[#OVFL:]] = extractvalue { i32, i1 } %[[#INTRIN_RET]], 1
+  // LLVM-NEXT:   store i32 %[[#RES]], ptr %[[#RES_PTR]], align 4
+  // LLVM-NEXT:   ret i1 %[[#OVFL]]
+  // LLVM-NEXT: }
+
+  cir.func @test_add_u32_u32_i32(%lhs: !u32i, %rhs: !u32i, %res: !cir.ptr<!s32i>) -> !cir.bool {
+    %result, %overflow = cir.binop.overflow(add, %lhs, %rhs) : !u32i, (!s32i, !cir.bool)
+    cir.store %result, %res : !s32i, !cir.ptr<!s32i>
+    cir.return %overflow : !cir.bool
+  }
+
+  //      MLIR: llvm.func @test_add_u32_u32_i32(%[[LHS:.+]]: i32, %[[RHS:.+]]: i32, %[[RES_PTR:.+]]: !llvm.ptr) -> i1
+  // MLIR-NEXT:   %[[#LHS_EXT:]] = llvm.zext %[[LHS]] : i32 to i33
+  // MLIR-NEXT:   %[[#RHS_EXT:]] = llvm.zext %[[RHS]] : i32 to i33
+  // MLIR-NEXT:   %[[#INTRIN_RET:]] = llvm.call_intrinsic "llvm.sadd.with.overflow.i33"(%[[#LHS_EXT]], %[[#RHS_EXT]]) : (i33, i33) -> !llvm.struct<(i33, i1)>
+  // MLIR-NEXT:   %[[#RES_EXT:]] = llvm.extractvalue %[[#INTRIN_RET]][0] : !llvm.struct<(i33, i1)>
+  // MLIR-NEXT:   %[[#ARITH_OVFL:]] = llvm.extractvalue %[[#INTRIN_RET]][1] : !llvm.struct<(i33, i1)>
+  // MLIR-NEXT:   %[[#RES:]] = llvm.trunc %[[#RES_EXT]] : i33 to i32
+  // MLIR-NEXT:   %[[#RES_EXT_2:]] = llvm.sext %[[#RES]] : i32 to i33
+  // MLIR-NEXT:   %[[#TRUNC_OVFL:]] = llvm.icmp "ne" %[[#RES_EXT_2]], %[[#RES_EXT]] : i33
+  // MLIR-NEXT:   %[[#OVFL:]] = llvm.or %[[#ARITH_OVFL]], %[[#TRUNC_OVFL]]  : i1
+  // MLIR-NEXT:   llvm.store %[[#RES]], %[[RES_PTR]] {{.*}} : i32, !llvm.ptr
+  // MLIR-NEXT:   llvm.return %[[#OVFL]] : i1
+  // MLIR-NEXT: }
+
+  //      LLVM: define i1 @test_add_u32_u32_i32(i32 %[[#LHS:]], i32 %[[#RHS:]], ptr %[[#RES_PTR:]])
+  // LLVM-NEXT:   %[[#LHS_EXT:]] = zext i32 %[[#LHS]] to i33
+  // LLVM-NEXT:   %[[#RHS_EXT:]] = zext i32 %[[#RHS]] to i33
+  // LLVM-NEXT:   %[[#INTRIN_RET:]] = call { i33, i1 } @llvm.sadd.with.overflow.i33(i33 %[[#LHS_EXT]], i33 %[[#RHS_EXT]])
+  // LLVM-NEXT:   %[[#RES_EXT:]] = extractvalue { i33, i1 } %[[#INTRIN_RET]], 0
+  // LLVM-NEXT:   %[[#ARITH_OVFL:]] = extractvalue { i33, i1 } %[[#INTRIN_RET]], 1
+  // LLVM-NEXT:   %[[#RES:]] = trunc i33 %[[#RES_EXT]] to i32
+  // LLVM-NEXT:   %[[#RES_EXT_2:]] = sext i32 %[[#RES]] to i33
+  // LLVM-NEXT:   %[[#TRUNC_OVFL:]] = icmp ne i33 %[[#RES_EXT_2]], %[[#RES_EXT]]
+  // LLVM-NEXT:   %[[#OVFL:]] = or i1 %[[#ARITH_OVFL]], %[[#TRUNC_OVFL]]
+  // LLVM-NEXT:   store i32 %[[#RES]], ptr %[[#RES_PTR]], align 4
+  // LLVM-NEXT:   ret i1 %[[#OVFL]]
+  // LLVM-NEXT: }
+}
diff --git a/clang/test/CIR/Lowering/binop-signed-int.cir b/clang/test/CIR/Lowering/binop-signed-int.cir
new file mode 100644
index 0000000000000..17597f080cd44
--- /dev/null
+++ b/clang/test/CIR/Lowering/binop-signed-int.cir
@@ -0,0 +1,60 @@
+// RUN: cir-opt %s -cir-to-llvm -o %t.mlir
+// RUN: FileCheck --input-file=%t.mlir %s
+
+!s32i = !cir.int<s, 32>
+module {
+  cir.func @foo() {
+    %0 = cir.alloca !s32i, !cir.ptr<!s32i>, ["a", init] {alignment = 4 : i64}
+    %1 = cir.alloca !s32i, !cir.ptr<!s32i>, ["b", init] {alignment = 4 : i64}
+    %2 = cir.alloca !s32i, !cir.ptr<!s32i>, ["x", init] {alignment = 4 : i64}
+    %3 = cir.const #cir.int<2> : !s32i    cir.store %3, %0 : !s32i, !cir.ptr<!s32i>
+    %4 = cir.const #cir.int<1> : !s32i    cir.store %4, %1 : !s32i, !cir.ptr<!s32i>
+    %5 = cir.load %0 : !cir.ptr<!s32i>, !s32i
+    %6 = cir.load %1 : !cir.ptr<!s32i>, !s32i
+    %7 = cir.binop(mul, %5, %6) : !s32i
+    // CHECK: = llvm.mul
+    cir.store %7, %2 : !s32i, !cir.ptr<!s32i>
+    %8 = cir.load %2 : !cir.ptr<!s32i>, !s32i
+    %9 = cir.load %1 : !cir.ptr<!s32i>, !s32i
+    %10 = cir.binop(div, %8, %9) : !s32i
+      // CHECK: = llvm.sdiv
+    cir.store %10, %2 : !s32i, !cir.ptr<!s32i>
+    %11 = cir.load %2 : !cir.ptr<!s32i>, !s32i
+    %12 = cir.load %1 : !cir.ptr<!s32i>, !s32i
+    %13 = cir.binop(rem, %11, %12) : !s32i
+    // CHECK: = llvm.srem
+    cir.store %13, %2 : !s32i, !cir.ptr<!s32i>
+    %14 = cir.load %2 : !cir.ptr<!s32i>, !s32i
+    %15 = cir.load %1 : !cir.ptr<!s32i>, !s32i
+    %16 = cir.binop(add, %14, %15) : !s32i
+    // CHECK: = llvm.add
+    cir.store %16, %2 : !s32i, !cir.ptr<!s32i>
+    %17 = cir.load %2 : !cir.ptr<!s32i>, !s32i
+    %18 = cir.load %1 : !cir.ptr<!s32i>, !s32i
+    %19 = cir.binop(sub, %17, %18) : !s32i
+    // CHECK: = llvm.sub
+    cir.store %19, %2 : !s32i, !cir.ptr<!s32i>
+    %26 = cir.load %2 : !cir.ptr<!s32i>, !s32i
+    %27 = cir.load %1 : !cir.ptr<!s32i>, !s32i
+    %28 = cir.binop(and, %26, %27) : !s32i
+    // CHECK: = llvm.and
+    cir.store %28, %2 : !s32i, !cir.ptr<!s32i>
+    %29 = cir.load %2 : !cir.ptr<!s32i>, !s32i
+    %30 = cir.load %1 : !cir.ptr<!s32i>, !s32i
+    %31 = cir.binop(xor, %29, %30) : !s32i
+    // CHECK: = llvm.xor
+    cir.store %31, %2 : !s32i, !cir.ptr<!s32i>
+    %32 = cir.load %2 : !cir.ptr<!s32i>, !s32i
+    %33 = cir.load %1 : !cir.ptr<!s32i>, !s32i
+    %34 = cir.binop(or, %32, %33) : !s32i
+    // CHECK: = llvm.or
+    %35 = cir.binop(add, %32, %33) sat: !s32i
+    // CHECK: = llvm.intr.sadd.sat{{.*}}(i32, i32) -> i32
+    %36 = cir.binop(sub, %32, %33) sat: !s32i
+    // CHECK: = llvm.intr.ssub.sat{{.*}}(i32, i32) -> i32 
+    cir.store %34, %2 : !s32i, !cir.ptr<!s32i>
+    %37 = cir.binop(max, %32, %33) : !s32i
+    // CHECK: = llvm.intr.smax
+    cir.return
+  }
+}
diff --git a/clang/test/CIR/Lowering/binop-unsigned-int.cir b/clang/test/CIR/Lowering/binop-unsigned-int.cir
new file mode 100644
index 0000000000000..46c62b339f2ed
--- /dev/null
+++ b/clang/test/CIR/Lowering/binop-unsigned-int.cir
@@ -0,0 +1,73 @@
+// RUN: cir-opt %s -cir-to-llvm -o - | FileCheck %s -check-prefix=MLIR
+// RUN: cir-translate %s -cir-to-llvmir --target x86_64-unknown-linux-gnu --disable-cc-lowering  | FileCheck %s -check-prefix=LLVM
+!u32i = !cir.int<u, 32>
+
+module {
+  cir.func @foo() {
+    %0 = cir.alloca !u32i, !cir.ptr<!u32i>, ["a", init] {alignment = 4 : i64}
+    %1 = cir.alloca !u32i, !cir.ptr<!u32i>, ["b", init] {alignment = 4 : i64}
+    %2 = cir.alloca !u32i, !cir.ptr<!u32i>, ["x", init] {alignment = 4 : i64}
+    %3 = cir.const #cir.int<2> : !u32i    cir.store %3, %0 : !u32i, !cir.ptr<!u32i>
+    %4 = cir.const #cir.int<1> : !u32i    cir.store %4, %1 : !u32i, !cir.ptr<!u32i>
+    %5 = cir.load %0 : !cir.ptr<!u32i>, !u32i
+    %6 = cir.load %1 : !cir.ptr<!u32i>, !u32i
+    %7 = cir.binop(mul, %5, %6) : !u32i
+    cir.store %7, %2 : !u32i, !cir.ptr<!u32i>
+    %8 = cir.load %2 : !cir.ptr<!u32i>, !u32i
+    %9 = cir.load %1 : !cir.ptr<!u32i>, !u32i
+    %10 = cir.binop(div, %8, %9) : !u32i
+    cir.store %10, %2 : !u32i, !cir.ptr<!u32i>
+    %11 = cir.load %2 : !cir.ptr<!u32i>, !u32i
+    %12 = cir.load %1 : !cir.ptr<!u32i>, !u32i
+    %13 = cir.binop(rem, %11, %12) : !u32i
+    cir.store %13, %2 : !u32i, !cir.ptr<!u32i>
+    %14 = cir.load %2 : !cir.ptr<!u32i>, !u32i
+    %15 = cir.load %1 : !cir.ptr<!u32i>, !u32i
+    %16 = cir.binop(add, %14, %15) : !u32i
+    cir.store %16, %2 : !u32i, !cir.ptr<!u32i>
+    %17 = cir.load %2 : !cir.ptr<!u32i>, !u32i
+    %18 = cir.load %1 : !cir.ptr<!u32i>, !u32i
+    %19 = cir.binop(sub, %17, %18) : !u32i
+    cir.store %19, %2 : !u32i, !cir.ptr<!u32i>
+    %26 = cir.load %2 : !cir.ptr<!u32i>, !u32i
+    %27 = cir.load %1 : !cir.ptr<!u32i>, !u32i
+    %28 = cir.binop(and, %26, %27) : !u32i
+    cir.store %28, %2 : !u32i, !cir.ptr<!u32i>
+    %29 = cir.load %2 : !cir.ptr<!u32i>, !u32i
+    %30 = cir.load %1 : !cir.ptr<!u32i>, !u32i
+    %31 = cir.binop(xor, %29, %30) : !u32i
+    cir.store %31, %2 : !u32i, !cir.ptr<!u32i>
+    %32 = cir.load %2 : !cir.ptr<!u32i>, !u32i
+    %33 = cir.load %1 : !cir.ptr<!u32i>, !u32i
+    %34 = cir.binop(or, %32, %33) : !u32i
+    cir.store %34, %2 : !u32i, !cir.ptr<!u32i>
+    %35 = cir.binop(add, %32, %33) sat: !u32i
+    %36 = cir.binop(sub, %32, %33) sat: !u32i  
+    %37 = cir.binop(max, %32, %33) : !u32i
+    cir.return
+  }
+}
+
+// MLIR: = llvm.mul
+// MLIR: = llvm.udiv
+// MLIR: = llvm.urem
+// MLIR: = llvm.add
+// MLIR: = llvm.sub
+// MLIR: = llvm.and
+// MLIR: = llvm.xor
+// MLIR: = llvm.or
+// MLIR: = llvm.intr.uadd.sat{{.*}}(i32, i32) -> i32
+// MLIR: = llvm.intr.usub.sat{{.*}}(i32, i32) -> i32 
+// MLIR: = llvm.intr.umax
+
+// LLVM: = mul i32
+// LLVM: = udiv i32
+// LLVM: = urem i32
+// LLVM: = add i32
+// LLVM: = sub i32
+// LLVM: = and i32
+// LLVM: = xor i32
+// LLVM: = or i32
+// LLVM: = call i32 @llvm.uadd.sat.i32
+// LLVM: = call i32 @llvm.usub.sat.i32
+// LLVM: = call i32 @llvm.umax.i32

>From e2e0fa44f2427d7c2838da7c63b7f056cdf37b92 Mon Sep 17 00:00:00 2001
From: Morris Hafner <mmha at users.noreply.github.com>
Date: Mon, 24 Mar 2025 12:27:41 +0000
Subject: [PATCH 02/11] Update
 clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h

Co-authored-by: Andy Kaylor <akaylor at nvidia.com>
---
 clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index 9fe80cde261a9..df9b84434b015 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -147,7 +147,7 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
     return createCast(loc, cir::CastKind::bitcast, src, newTy);
   }
 
-  mlir::Value createBinop(mlir::Value lhs, cir::BinOpKind kind,
+  mlir::Value createBinOp(mlir::Value lhs, cir::BinOpKind kind,
                           const llvm::APInt &rhs) {
     return create<cir::BinOp>(lhs.getLoc(), lhs.getType(), kind, lhs,
                               getConstAPInt(lhs.getLoc(), lhs.getType(), rhs));

>From a77053b74dbeffabb4bb67c66d903e996adcc51c Mon Sep 17 00:00:00 2001
From: Morris Hafner <mmha at users.noreply.github.com>
Date: Mon, 24 Mar 2025 12:28:19 +0000
Subject: [PATCH 03/11] Update clang/include/clang/CIR/MissingFeatures.h

Co-authored-by: Andy Kaylor <akaylor at nvidia.com>
---
 clang/include/clang/CIR/MissingFeatures.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/CIR/MissingFeatures.h b/clang/include/clang/CIR/MissingFeatures.h
index 3654038a51fbd..7ddc7480630aa 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -136,7 +136,7 @@ struct MissingFeatures {
   static bool ternaryOp() { return false; }
   static bool tryOp() { return false; }
   static bool zextOp() { return false; }
-  static bool opPtrStride() { return false; }
+  static bool ptrStrideOp() { return false; }
   static bool opPtrDiff() { return false; }
 };
 

>From ad4b4c2623babad36c660d34073b785305d338af Mon Sep 17 00:00:00 2001
From: Morris Hafner <mmha at users.noreply.github.com>
Date: Mon, 24 Mar 2025 12:28:42 +0000
Subject: [PATCH 04/11] Update clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp

Co-authored-by: Andy Kaylor <akaylor at nvidia.com>
---
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index 787a93c52b53e..6bdc10627c904 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -882,7 +882,7 @@ getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e) {
   return baseTy;
 }
 
-/// Check if \p E is a widened promoted integer.
+/// Check if \p e is a widened promoted integer.
 [[maybe_unused]] static bool isWidenedIntegerOp(const ASTContext &astContext,
                                                 const Expr *e) {
   return getUnwidenedIntegerType(astContext, e).has_value();

>From a3c8c79496c49bac0a77652fee3fe2bd6a0f3e95 Mon Sep 17 00:00:00 2001
From: Morris Hafner <mmha at users.noreply.github.com>
Date: Mon, 24 Mar 2025 12:32:14 +0000
Subject: [PATCH 05/11] Update clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp

Co-authored-by: Andy Kaylor <akaylor at nvidia.com>
---
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index 6bdc10627c904..a62ac1300b98e 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -867,7 +867,7 @@ mlir::Value CIRGenFunction::emitPromotedScalarExpr(const Expr *e,
   return e->getType()->isNullPtrType();
 }
 
-/// If \p E is a widened promoted integer, get its base (unpromoted) type.
+/// If \p e is a widened promoted integer, get its base (unpromoted) type.
 static std::optional<QualType>
 getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e) {
   const Expr *base = e->IgnoreImpCasts();

>From c66dac4c552c47a17e41acad13b69520c278546b Mon Sep 17 00:00:00 2001
From: Morris Hafner <mmha at users.noreply.github.com>
Date: Mon, 24 Mar 2025 12:34:34 +0000
Subject: [PATCH 06/11] Update clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp

Co-authored-by: Andy Kaylor <akaylor at nvidia.com>
---
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index a62ac1300b98e..eebf2f622858a 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -762,7 +762,7 @@ LValue ScalarExprEmitter::emitCompoundAssignLValue(
   SourceLocation loc = e->getExprLoc();
   if (!promotionTypeLHS.isNull())
     opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy, promotionTypeLHS,
-                                      e->getExprLoc());
+                                      loc);
   else
     opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy,
                                       e->getComputationLHSType(), loc);

>From be5af08dbaecb001a9dc7c296d96e5b121a0ed1b Mon Sep 17 00:00:00 2001
From: Morris Hafner <mhafner at nvidia.com>
Date: Mon, 24 Mar 2025 17:35:52 +0000
Subject: [PATCH 07/11] Address review comments

---
 clang/include/clang/AST/ASTContext.h          |  317 ++-
 .../CIR/Dialect/Builder/CIRBaseBuilder.h      |  117 +-
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |    1 -
 clang/include/clang/CIR/MissingFeatures.h     |    3 +-
 clang/lib/AST/ASTContext.cpp                  | 2058 ++++++++---------
 clang/lib/CIR/CodeGen/CIRGenBuilder.h         |   38 +-
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp          |    6 +-
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp    |   86 +-
 clang/lib/CodeGen/CGExprScalar.cpp            |   21 +-
 9 files changed, 1276 insertions(+), 1371 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h
index af8c49e99a7ce..2c3170278d3d9 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -200,7 +200,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
       ConstantArrayTypes;
   mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
-  mutable std::vector<VariableArrayType*> VariableArrayTypes;
+  mutable std::vector<VariableArrayType *> VariableArrayTypes;
   mutable llvm::ContextualFoldingSet<DependentSizedArrayType, ASTContext &>
       DependentSizedArrayTypes;
   mutable llvm::ContextualFoldingSet<DependentSizedExtVectorType, ASTContext &>
@@ -214,8 +214,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable llvm::ContextualFoldingSet<DependentSizedMatrixType, ASTContext &>
       DependentSizedMatrixTypes;
   mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
-  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
-    FunctionProtoTypes;
+  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext &>
+      FunctionProtoTypes;
   mutable llvm::ContextualFoldingSet<DependentTypeOfExprType, ASTContext &>
       DependentTypeOfExprTypes;
   mutable llvm::ContextualFoldingSet<DependentDecltypeType, ASTContext &>
@@ -226,11 +226,11 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
   mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
   mutable llvm::FoldingSet<SubstTemplateTypeParmType>
-    SubstTemplateTypeParmTypes;
+      SubstTemplateTypeParmTypes;
   mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
-    SubstTemplateTypeParmPackTypes;
-  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
-    TemplateSpecializationTypes;
+      SubstTemplateTypeParmPackTypes;
+  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext &>
+      TemplateSpecializationTypes;
   mutable llvm::FoldingSet<ParenType> ParenTypes{GeneralTypesLog2InitSize};
   mutable llvm::FoldingSet<UsingType> UsingTypes;
   mutable llvm::FoldingSet<TypedefType> TypedefTypes;
@@ -238,20 +238,20 @@ class ASTContext : public RefCountedBase<ASTContext> {
       GeneralTypesLog2InitSize};
   mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
   mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
-                                     ASTContext&>
-    DependentTemplateSpecializationTypes;
+                                     ASTContext &>
+      DependentTemplateSpecializationTypes;
   mutable llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
   mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
   mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
   mutable llvm::FoldingSet<DependentUnaryTransformType>
-    DependentUnaryTransformTypes;
+      DependentUnaryTransformTypes;
   // An AutoType can have a dependency on another AutoType via its template
   // arguments. Since both dependent and dependency are on the same set,
   // we can end up in an infinite recursion when looking for a node if we used
   // a `FoldingSet`, since both could end up in the same bucket.
   mutable llvm::DenseMap<llvm::FoldingSetNodeID, AutoType *> AutoTypes;
   mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
-    DeducedTemplateSpecializationTypes;
+      DeducedTemplateSpecializationTypes;
   mutable llvm::FoldingSet<AtomicType> AtomicTypes;
   mutable llvm::FoldingSet<AttributedType> AttributedTypes;
   mutable llvm::FoldingSet<PipeType> PipeTypes;
@@ -266,10 +266,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
   mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
   mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
-    SubstTemplateTemplateParms;
+      SubstTemplateTemplateParms;
   mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
-                                     ASTContext&>
-    SubstTemplateTemplateParmPacks;
+                                     ASTContext &>
+      SubstTemplateTemplateParmPacks;
   mutable llvm::ContextualFoldingSet<DeducedTemplateStorage, ASTContext &>
       DeducedTemplates;
 
@@ -285,8 +285,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// A cache mapping from RecordDecls to ASTRecordLayouts.
   ///
   /// This is lazily created.  This is intentionally not serialized.
-  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
-    ASTRecordLayouts;
+  mutable llvm::DenseMap<const RecordDecl *, const ASTRecordLayout *>
+      ASTRecordLayouts;
   mutable llvm::DenseMap<const ObjCInterfaceDecl *, const ASTRecordLayout *>
       ObjCLayouts;
 
@@ -301,14 +301,15 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
 
   /// A cache mapping from CXXRecordDecls to key functions.
-  llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
+  llvm::DenseMap<const CXXRecordDecl *, LazyDeclPtr> KeyFunctions;
 
   /// Mapping from ObjCContainers to their ObjCImplementations.
-  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
+  llvm::DenseMap<ObjCContainerDecl *, ObjCImplDecl *> ObjCImpls;
 
   /// Mapping from ObjCMethod to its duplicate declaration in the same
   /// interface.
-  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
+  llvm::DenseMap<const ObjCMethodDecl *, const ObjCMethodDecl *>
+      ObjCMethodRedecls;
 
   /// Mapping from __block VarDecls to BlockVarCopyInit.
   llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
@@ -356,16 +357,15 @@ class ASTContext : public RefCountedBase<ASTContext> {
       Profile(ID, C, Parm);
     }
 
-    static void Profile(llvm::FoldingSetNodeID &ID,
-                        const ASTContext &C,
+    static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C,
                         TemplateTemplateParmDecl *Parm);
   };
   mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
-                                     const ASTContext&>
-    CanonTemplateTemplateParms;
+                                     const ASTContext &>
+      CanonTemplateTemplateParms;
 
   TemplateTemplateParmDecl *
-    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
+  getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
 
   /// The typedef for the __int128_t type.
   mutable TypedefDecl *Int128Decl = nullptr;
@@ -455,29 +455,29 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   /// Since so few decls have attrs, we keep them in a hash map instead of
   /// wasting space in the Decl class.
-  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
+  llvm::DenseMap<const Decl *, AttrVec *> DeclAttrs;
 
   /// A mapping from non-redeclarable declarations in modules that were
   /// merged with other declarations to the canonical declaration that they were
   /// merged into.
-  llvm::DenseMap<Decl*, Decl*> MergedDecls;
+  llvm::DenseMap<Decl *, Decl *> MergedDecls;
 
   /// A mapping from a defining declaration to a list of modules (other
   /// than the owning module of the declaration) that contain merged
   /// definitions of that entity.
-  llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
+  llvm::DenseMap<NamedDecl *, llvm::TinyPtrVector<Module *>> MergedDefModules;
 
   /// Initializers for a module, in order. Each Decl will be either
   /// something that has a semantic effect on startup (such as a variable with
   /// a non-constant initializer), or an ImportDecl (which recursively triggers
   /// initialization of another module).
   struct PerModuleInitializers {
-    llvm::SmallVector<Decl*, 4> Initializers;
+    llvm::SmallVector<Decl *, 4> Initializers;
     llvm::SmallVector<GlobalDeclID, 4> LazyInitializers;
 
     void resolve(ASTContext &Ctx);
   };
-  llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
+  llvm::DenseMap<Module *, PerModuleInitializers *> ModuleInitializers;
 
   /// This is the top-level (C++20) Named module we are building.
   Module *CurrentCXXNamedModule = nullptr;
@@ -545,7 +545,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
   /// class template X) and will be marked TSK_ImplicitInstantiation.
   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
-  TemplateOrInstantiation;
+      TemplateOrInstantiation;
 
   /// Keeps track of the declaration from which a using declaration was
   /// created during instantiation.
@@ -583,8 +583,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
       InstantiatedFromUsingEnumDecl;
 
   /// Simlarly maps instantiated UsingShadowDecls to their origin.
-  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
-    InstantiatedFromUsingShadowDecl;
+  llvm::DenseMap<UsingShadowDecl *, UsingShadowDecl *>
+      InstantiatedFromUsingShadowDecl;
 
   llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
 
@@ -738,8 +738,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
     PrintingPolicy = Policy;
   }
 
-  SourceManager& getSourceManager() { return SourceMgr; }
-  const SourceManager& getSourceManager() const { return SourceMgr; }
+  SourceManager &getSourceManager() { return SourceMgr; }
+  const SourceManager &getSourceManager() const { return SourceMgr; }
 
   // Cleans up some of the data structures. This allows us to do cleanup
   // normally done in the destructor earlier. Renders much of the ASTContext
@@ -747,9 +747,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   // longer need access to the AST.
   void cleanup();
 
-  llvm::BumpPtrAllocator &getAllocator() const {
-    return BumpAlloc;
-  }
+  llvm::BumpPtrAllocator &getAllocator() const { return BumpAlloc; }
 
   void *Allocate(size_t Size, unsigned Align = 8) const {
     return BumpAlloc.Allocate(Size, Align);
@@ -785,9 +783,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Return the total amount of physical memory allocated for representing
   /// AST nodes and type information.
-  size_t getASTAllocatedMemory() const {
-    return BumpAlloc.getTotalMemory();
-  }
+  size_t getASTAllocatedMemory() const { return BumpAlloc.getTotalMemory(); }
 
   /// Return the total memory used for various side tables.
   size_t getSideTableAllocatedMemory() const;
@@ -820,8 +816,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// sets integer QualTy according to specified details:
   /// bitwidth, signed/unsigned.
   /// Returns empty type if there is no appropriate target types.
-  QualType getIntTypeForBitwidth(unsigned DestWidth,
-                                 unsigned Signed) const;
+  QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const;
 
   /// getRealTypeForBitwidth -
   /// sets floating point QualTy according to specified bitwidth.
@@ -831,7 +826,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
 
-  const LangOptions& getLangOpts() const { return LangOpts; }
+  const LangOptions &getLangOpts() const { return LangOpts; }
 
   // If this condition is false, typo correction must be performed eagerly
   // rather than delayed in many places, as it makes use of dependent types.
@@ -846,16 +841,14 @@ class ASTContext : public RefCountedBase<ASTContext> {
   bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
                                 const QualType &Ty) const;
 
-  const XRayFunctionFilter &getXRayFilter() const {
-    return *XRayFilter;
-  }
+  const XRayFunctionFilter &getXRayFilter() const { return *XRayFilter; }
 
   const ProfileList &getProfileList() const { return *ProfList; }
 
   DiagnosticsEngine &getDiagnostics() const;
 
   FullSourceLoc getFullLoc(SourceLocation Loc) const {
-    return FullSourceLoc(Loc,SourceMgr);
+    return FullSourceLoc(Loc, SourceMgr);
   }
 
   /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden
@@ -952,7 +945,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
 
   comments::FullComment *cloneFullComment(comments::FullComment *FC,
-                                         const Decl *D) const;
+                                          const Decl *D) const;
 
 private:
   mutable comments::CommandTraits CommentCommandTraits;
@@ -1000,7 +993,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   }
 
   /// Retrieve the attributes for the given declaration.
-  AttrVec& getDeclAttrs(const Decl *D);
+  AttrVec &getDeclAttrs(const Decl *D);
 
   /// Erase the attributes corresponding to the given declaration.
   void eraseDeclAttrs(const Decl *D);
@@ -1009,14 +1002,14 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// class template specialization, returns the templated static data member
   /// from which it was instantiated.
   // FIXME: Remove ?
-  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
-                                                           const VarDecl *Var);
+  MemberSpecializationInfo *
+  getInstantiatedFromStaticDataMember(const VarDecl *Var);
 
   /// Note that the static data member \p Inst is an instantiation of
   /// the static data member template \p Tmpl of a class template.
-  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
-                                           TemplateSpecializationKind TSK,
-                        SourceLocation PointOfInstantiation = SourceLocation());
+  void setInstantiatedFromStaticDataMember(
+      VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK,
+      SourceLocation PointOfInstantiation = SourceLocation());
 
   TemplateOrSpecializationInfo
   getTemplateOrSpecializationInfo(const VarDecl *Var);
@@ -1076,9 +1069,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// the same selector and is of the same kind (class or instance).
   /// A method in an implementation is not considered as overriding the same
   /// method in the interface or its categories.
-  void getOverriddenMethods(
-                        const NamedDecl *Method,
-                        SmallVectorImpl<const NamedDecl *> &Overridden) const;
+  void
+  getOverriddenMethods(const NamedDecl *Method,
+                       SmallVectorImpl<const NamedDecl *> &Overridden) const;
 
   /// Notify the AST context that a new import declaration has been
   /// parsed or implicitly created within this translation unit.
@@ -1113,7 +1106,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Get the additional modules in which the definition \p Def has
   /// been merged.
-  ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
+  ArrayRef<Module *> getModulesWithMergedDefinition(const NamedDecl *Def);
 
   /// Add a declaration to the list of declarations that are initialized
   /// for a module. This will typically be a global variable (with internal
@@ -1124,7 +1117,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   void addLazyModuleInitializers(Module *M, ArrayRef<GlobalDeclID> IDs);
 
   /// Get the initializations to perform when importing a module, if any.
-  ArrayRef<Decl*> getModuleInitializers(Module *M);
+  ArrayRef<Decl *> getModuleInitializers(Module *M);
 
   /// Set the (C++20) module we are building.
   void setCurrentNamedModule(Module *M);
@@ -1160,9 +1153,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
   CanQualType VoidTy;
   CanQualType BoolTy;
   CanQualType CharTy;
-  CanQualType WCharTy;  // [C++ 3.9.1p5].
+  CanQualType WCharTy;    // [C++ 3.9.1p5].
   CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
-  CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
+  CanQualType
+      WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
   CanQualType Char8Ty;  // [C++20 proposal]
   CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
   CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
@@ -1171,7 +1165,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
   CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty, Ibm128Ty;
   CanQualType ShortAccumTy, AccumTy,
-      LongAccumTy;  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
+      LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
   CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
   CanQualType ShortFractTy, FractTy, LongFractTy;
   CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
@@ -1191,7 +1185,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
   CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
   CanQualType ObjCBuiltinBoolTy;
-#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
+#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
   CanQualType SingletonId;
 #include "clang/Basic/OpenCLImageTypes.def"
   CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
@@ -1199,17 +1193,13 @@ class ASTContext : public RefCountedBase<ASTContext> {
   CanQualType IncompleteMatrixIdxTy;
   CanQualType ArraySectionTy;
   CanQualType OMPArrayShapingTy, OMPIteratorTy;
-#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
-  CanQualType Id##Ty;
+#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) CanQualType Id##Ty;
 #include "clang/Basic/OpenCLExtensionTypes.def"
-#define SVE_TYPE(Name, Id, SingletonId) \
-  CanQualType SingletonId;
+#define SVE_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
 #include "clang/Basic/AArch64SVEACLETypes.def"
-#define PPC_VECTOR_TYPE(Name, Id, Size) \
-  CanQualType Id##Ty;
+#define PPC_VECTOR_TYPE(Name, Id, Size) CanQualType Id##Ty;
 #include "clang/Basic/PPCTypes.def"
-#define RVV_TYPE(Name, Id, SingletonId) \
-  CanQualType SingletonId;
+#define RVV_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
 #include "clang/Basic/RISCVVTypes.def"
 #define WASM_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
 #include "clang/Basic/WebAssemblyReferenceTypes.def"
@@ -1271,9 +1261,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Retrieve a pointer to the external AST source associated
   /// with this AST context, if any.
-  ExternalASTSource *getExternalSource() const {
-    return ExternalSource.get();
-  }
+  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
 
   /// Attach an AST mutation listener to the AST context.
   ///
@@ -1289,7 +1277,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ASTMutationListener *getASTMutationListener() const { return Listener; }
 
   void PrintStats() const;
-  const SmallVectorImpl<Type *>& getTypes() const { return Types; }
+  const SmallVectorImpl<Type *> &getTypes() const { return Types; }
 
   BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
                                                 const IdentifierInfo *II) const;
@@ -1339,8 +1327,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Return the "other" discriminator used for the pointer auth schema used for
   /// vtable pointers in instances of the requested type.
-  uint16_t
-  getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD);
+  uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD);
 
   /// Return the "other" type-specific discriminator for the given type.
   uint16_t getPointerAuthTypeDiscriminator(QualType T);
@@ -1350,8 +1337,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// qualifiers on ObjCObjectPointerType. It can be set to true when
   /// constructing the canonical type of a Objective-C type parameter.
   QualType applyObjCProtocolQualifiers(QualType type,
-      ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
-      bool allowOnPointerType = false) const;
+                                       ArrayRef<ObjCProtocolDecl *> protocols,
+                                       bool &hasError,
+                                       bool allowOnPointerType = false) const;
 
   /// Return the uniqued reference to the type for an Objective-C
   /// gc-qualified type.
@@ -1450,14 +1438,14 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// number with the specified element type.
   QualType getComplexType(QualType T) const;
   CanQualType getComplexType(CanQualType T) const {
-    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
+    return CanQualType::CreateUnsafe(getComplexType((QualType)T));
   }
 
   /// Return the uniqued reference to the type for a pointer to
   /// the specified type.
   QualType getPointerType(QualType T) const;
   CanQualType getPointerType(CanQualType T) const {
-    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
+    return CanQualType::CreateUnsafe(getPointerType((QualType)T));
   }
 
   QualType
@@ -1478,7 +1466,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// pointer types.
   QualType getDecayedType(QualType T) const;
   CanQualType getDecayedType(CanQualType T) const {
-    return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
+    return CanQualType::CreateUnsafe(getDecayedType((QualType)T));
   }
   /// Return the uniqued reference to a specified decay from the original
   /// type to the decayed type.
@@ -1534,9 +1522,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
     cudaConfigureCallDecl = FD;
   }
 
-  FunctionDecl *getcudaConfigureCallDecl() {
-    return cudaConfigureCallDecl;
-  }
+  FunctionDecl *getcudaConfigureCallDecl() { return cudaConfigureCallDecl; }
 
   /// Returns true iff we need copy/dispose helpers for the given type.
   bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
@@ -1544,14 +1530,13 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
   /// is set to false in this case. If HasByrefExtendedLayout returns true,
   /// byref variable has extended lifetime.
-  bool getByrefLifetime(QualType Ty,
-                        Qualifiers::ObjCLifetime &Lifetime,
+  bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime,
                         bool &HasByrefExtendedLayout) const;
 
   /// Return the uniqued reference to the type for an lvalue reference
   /// to the specified type.
-  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
-    const;
+  QualType getLValueReferenceType(QualType T,
+                                  bool SpelledAsLValue = true) const;
 
   /// Return the uniqued reference to the type for an rvalue reference
   /// to the specified type.
@@ -1646,8 +1631,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   /// FIXME: We will need these to be uniqued, or at least comparable, at some
   /// point.
-  QualType getDependentSizedExtVectorType(QualType VectorType,
-                                          Expr *SizeExpr,
+  QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr,
                                           SourceLocation AttrLoc) const;
 
   /// Return the unique reference to the matrix type of the specified element
@@ -1702,7 +1686,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   QualType getTypeDeclType(const TypeDecl *Decl,
                            const TypeDecl *PrevDecl = nullptr) const {
     assert(Decl && "Passed null for Decl param");
-    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
+    if (Decl->TypeForDecl)
+      return QualType(Decl->TypeForDecl, 0);
 
     if (PrevDecl) {
       assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
@@ -1806,8 +1791,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                             const TemplateArgument &ArgPack);
 
   QualType
-  getTemplateTypeParmType(unsigned Depth, unsigned Index,
-                          bool ParameterPack,
+  getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack,
                           TemplateTypeParmDecl *ParmDecl = nullptr) const;
 
   QualType getTemplateSpecializationType(TemplateName T,
@@ -1864,12 +1848,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                 ObjCInterfaceDecl *PrevDecl = nullptr) const;
 
   /// Legacy interface: cannot provide type arguments or __kindof.
-  QualType getObjCObjectType(QualType Base,
-                             ObjCProtocolDecl * const *Protocols,
+  QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols,
                              unsigned NumProtocols) const;
 
-  QualType getObjCObjectType(QualType Base,
-                             ArrayRef<QualType> typeArgs,
+  QualType getObjCObjectType(QualType Base, ArrayRef<QualType> typeArgs,
                              ArrayRef<ObjCProtocolDecl *> protocols,
                              bool isKindOf) const;
 
@@ -1908,10 +1890,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                  UnaryTransformType::UTTKind UKind) const;
 
   /// C++11 deduced auto type.
-  QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
-                       bool IsDependent, bool IsPack = false,
-                       ConceptDecl *TypeConstraintConcept = nullptr,
-                       ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
+  QualType
+  getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
+              bool IsPack = false, ConceptDecl *TypeConstraintConcept = nullptr,
+              ArrayRef<TemplateArgument> TypeConstraintArgs = {}) const;
 
   /// C++11 deduction pattern for 'auto' type.
   QualType getAutoDeductType() const;
@@ -2025,13 +2007,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
     return ObjCConstantStringType;
   }
 
-  QualType getObjCNSStringType() const {
-    return ObjCNSStringType;
-  }
+  QualType getObjCNSStringType() const { return ObjCNSStringType; }
 
-  void setObjCNSStringType(QualType T) {
-    ObjCNSStringType = T;
-  }
+  void setObjCNSStringType(QualType T) { ObjCNSStringType = T; }
 
   /// Retrieve the type that \c id has been defined to, which may be
   /// different from the built-in \c id if \c id has been typedef'd.
@@ -2175,8 +2153,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   /// If \p Field is specified then record field names are also encoded.
   void getObjCEncodingForType(QualType T, std::string &S,
-                              const FieldDecl *Field=nullptr,
-                              QualType *NotEncodedT=nullptr) const;
+                              const FieldDecl *Field = nullptr,
+                              QualType *NotEncodedT = nullptr) const;
 
   /// Emit the Objective-C property type encoding for the given
   /// type \p T into \p S.
@@ -2214,9 +2192,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
                                       ObjCProtocolDecl *rProto) const;
 
-  ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
-                                                  const ObjCPropertyDecl *PD,
-                                                  const Decl *Container) const;
+  ObjCPropertyImplDecl *
+  getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD,
+                                         const Decl *Container) const;
 
   /// Return the size of type \p T for Objective-C encoding purpose,
   /// in characters.
@@ -2230,9 +2208,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
   /// pointer type, a pointer to a struct.
-  QualType getObjCIdType() const {
-    return getTypeDeclType(getObjCIdDecl());
-  }
+  QualType getObjCIdType() const { return getTypeDeclType(getObjCIdDecl()); }
 
   /// Retrieve the typedef corresponding to the predefined 'SEL' type
   /// in Objective-C.
@@ -2240,9 +2216,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Retrieve the type that corresponds to the predefined Objective-C
   /// 'SEL' type.
-  QualType getObjCSelType() const {
-    return getTypeDeclType(getObjCSelDecl());
-  }
+  QualType getObjCSelType() const { return getTypeDeclType(getObjCSelDecl()); }
 
   /// Retrieve the typedef declaration corresponding to the predefined
   /// Objective-C 'Class' type.
@@ -2261,19 +2235,13 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ObjCInterfaceDecl *getObjCProtocolDecl() const;
 
   /// Retrieve declaration of 'BOOL' typedef
-  TypedefDecl *getBOOLDecl() const {
-    return BOOLDecl;
-  }
+  TypedefDecl *getBOOLDecl() const { return BOOLDecl; }
 
   /// Save declaration of 'BOOL' typedef
-  void setBOOLDecl(TypedefDecl *TD) {
-    BOOLDecl = TD;
-  }
+  void setBOOLDecl(TypedefDecl *TD) { BOOLDecl = TD; }
 
   /// type of 'BOOL' type.
-  QualType getBOOLType() const {
-    return getTypeDeclType(getBOOLDecl());
-  }
+  QualType getBOOLType() const { return getTypeDeclType(getBOOLDecl()); }
 
   /// Retrieve the type of the Objective-C \c Protocol class.
   QualType getObjCProtoType() const {
@@ -2520,9 +2488,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
 
   /// Return the size of the character type, in bits.
-  uint64_t getCharWidth() const {
-    return getTypeSize(CharTy);
-  }
+  uint64_t getCharWidth() const { return getTypeSize(CharTy); }
 
   /// Convert a size in bits to a size in characters.
   CharUnits toCharUnitsFromBits(int64_t BitSize) const;
@@ -2579,9 +2545,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
     return toCharUnitsFromBits(getPreferredTypeAlign(T));
   }
 
-  /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
-  /// in characters, before alignment adjustments. This method does not work on
-  /// incomplete types.
+  /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
+  /// type, in characters, before alignment adjustments. This method does not
+  /// work on incomplete types.
   CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
   CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
 
@@ -2654,8 +2620,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Get or compute information about the layout of the specified
   /// Objective-C interface.
-  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
-    const;
+  const ASTRecordLayout &
+  getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const;
 
   void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
                         bool Simple = false) const;
@@ -2718,11 +2684,11 @@ class ASTContext : public RefCountedBase<ASTContext> {
   MangleContext *createDeviceMangleContext(const TargetInfo &T);
 
   void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
-                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
+                            SmallVectorImpl<const ObjCIvarDecl *> &Ivars) const;
 
   unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
-  void CollectInheritedProtocols(const Decl *CDecl,
-                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
+  void CollectInheritedProtocols(
+      const Decl *CDecl, llvm::SmallPtrSet<ObjCProtocolDecl *, 8> &Protocols);
 
   /// Return true if the specified type has unique object representations
   /// according to (C++17 [meta.unary.prop]p9)
@@ -2809,8 +2775,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
         return true;
 
       if (IsParam) {
-        // Ok for the superclass method parameter to be "nonnull" and the subclass
-        // method parameter to be "nullable"
+        // Ok for the superclass method parameter to be "nonnull" and the
+        // subclass method parameter to be "nullable"
         return (*SuperTnullability == NullabilityKind::NonNull &&
                 *SubTnullability == NullabilityKind::Nullable);
       }
@@ -2869,8 +2835,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
 
   /// Retrieves the default calling convention for the current target.
-  CallingConv getDefaultCallingConvention(bool IsVariadic,
-                                          bool IsCXXMethod,
+  CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod,
                                           bool IsBuiltin = false) const;
 
   /// Retrieves the "canonical" template name that refers to a
@@ -2933,8 +2898,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// The canonical template argument is the simplest template argument
   /// (which may be a type, value, expression, or declaration) that
   /// expresses the value of the argument.
-  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
-    const;
+  TemplateArgument
+  getCanonicalTemplateArgument(const TemplateArgument &Arg) const;
 
   /// Type Query functions.  If the type is an instance of the specified class,
   /// return the Type pointer for the underlying maximally pretty type.  This
@@ -2950,8 +2915,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
     return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
   }
-  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
-    const {
+  const DependentSizedArrayType *
+  getAsDependentSizedArrayType(QualType T) const {
     return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
   }
 
@@ -2999,6 +2964,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
   QualType getPromotedIntegerType(QualType PromotableType) const;
 
+  /// If \p E is a widened promoted integer, get its base (unpromoted) type.
+  std::optional<QualType> getUnwidenedIntegerType(const Expr *E) const;
+
   /// Recurses in pointer/array types until it finds an Objective-C
   /// retainable type and returns its ownership.
   Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
@@ -3105,10 +3073,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                const ObjCObjectPointerType *RHSOPT);
   bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
                                const ObjCObjectType *RHS);
-  bool canAssignObjCInterfacesInBlockPointer(
-                                          const ObjCObjectPointerType *LHSOPT,
-                                          const ObjCObjectPointerType *RHSOPT,
-                                          bool BlockReturnType);
+  bool
+  canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT,
+                                        const ObjCObjectPointerType *RHSOPT,
+                                        bool BlockReturnType);
   bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
   QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
                                    const ObjCObjectPointerType *RHSOPT);
@@ -3125,7 +3093,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                        bool OfBlockPointer = false,
                                        bool Unqualified = false);
   QualType mergeTransparentUnionType(QualType, QualType,
-                                     bool OfBlockPointer=false,
+                                     bool OfBlockPointer = false,
                                      bool Unqualified = false);
 
   QualType mergeObjCGCQualifiers(QualType, QualType);
@@ -3151,8 +3119,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   bool mergeExtParameterInfo(
       const FunctionProtoType *FirstFnType,
-      const FunctionProtoType *SecondFnType,
-      bool &CanUseFirst, bool &CanUseSecond,
+      const FunctionProtoType *SecondFnType, bool &CanUseFirst,
+      bool &CanUseSecond,
       SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
 
   void ResetObjCLayout(const ObjCInterfaceDecl *D);
@@ -3228,9 +3196,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
 
   /// Return true if there is at least one \@implementation in the TU.
-  bool AnyObjCImplementation() {
-    return !ObjCImpls.empty();
-  }
+  bool AnyObjCImplementation() { return !ObjCImpls.empty(); }
 
   /// Set the implementation of ObjCInterfaceDecl.
   void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
@@ -3255,11 +3221,11 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Set the copy initialization expression of a block var decl. \p CanThrow
   /// indicates whether the copy expression can throw or not.
-  void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
+  void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow);
 
   /// Get the copy initialization expression of the VarDecl \p VD, or
   /// nullptr if none exists.
-  BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
+  BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const;
 
   /// Allocate an uninitialized TypeSourceInfo.
   ///
@@ -3478,14 +3444,19 @@ class ASTContext : public RefCountedBase<ASTContext> {
   V(EncodingProperty, 3)                                                       \
   V(IsStructField, 4)                                                          \
   V(EncodeBlockParameters, 5)                                                  \
-  V(EncodeClassNames, 6)                                                       \
+  V(EncodeClassNames, 6)
 
-#define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
-OPT_LIST(V)
+#define V(N, I)                                                                \
+  ObjCEncOptions &set##N() {                                                   \
+    Bits |= 1 << I;                                                            \
+    return *this;                                                              \
+  }
+    OPT_LIST(V)
 #undef V
 
-#define V(N,I) bool N() const { return Bits & 1 << I; }
-OPT_LIST(V)
+#define V(N, I)                                                                \
+  bool N() const { return Bits & 1 << I; }
+    OPT_LIST(V)
 #undef V
 
 #undef OPT_LIST
@@ -3495,9 +3466,8 @@ OPT_LIST(V)
     }
 
     [[nodiscard]] ObjCEncOptions forComponentType() const {
-      ObjCEncOptions Mask = ObjCEncOptions()
-                                .setIsOutermostType()
-                                .setIsStructField();
+      ObjCEncOptions Mask =
+          ObjCEncOptions().setIsOutermostType().setIsStructField();
       return Bits & ~Mask.Bits;
     }
   };
@@ -3512,13 +3482,12 @@ OPT_LIST(V)
   void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
                                        const FieldDecl *Field,
                                        bool includeVBases = true,
-                                       QualType *NotEncodedT=nullptr) const;
+                                       QualType *NotEncodedT = nullptr) const;
 
 public:
   // Adds the encoding of a method parameter or return type.
-  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
-                                         QualType T, std::string& S,
-                                         bool Extended) const;
+  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T,
+                                         std::string &S, bool Extended) const;
 
   /// Returns true if this is an inline-initialized static data member
   /// which is treated as a definition for MSVC compatibility.
@@ -3712,7 +3681,7 @@ inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
 /// @param Alignment The alignment of the allocated memory (if the underlying
 ///                  allocator supports it).
 /// @return The allocated memory. Could be nullptr.
-inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
+inline void *operator new[](size_t Bytes, const clang::ASTContext &C,
                             size_t Alignment /* = 8 */) {
   return C.Allocate(Bytes, Alignment);
 }
@@ -3731,8 +3700,8 @@ inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
 template <typename Owner, typename T,
           void (clang::ExternalASTSource::*Update)(Owner)>
 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
-    clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
-        const clang::ASTContext &Ctx, T Value) {
+clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
+    const clang::ASTContext &Ctx, T Value) {
   // Note, this is implemented here so that ExternalASTSource.h doesn't need to
   // include ASTContext.h. We explicitly instantiate it for all relevant types
   // in ASTContext.cpp.
diff --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index df9b84434b015..a15fd1a0fca01 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -17,6 +17,7 @@
 
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/Location.h"
 #include "mlir/IR/Types.h"
 
 namespace cir {
@@ -147,17 +148,6 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
     return createCast(loc, cir::CastKind::bitcast, src, newTy);
   }
 
-  mlir::Value createBinOp(mlir::Value lhs, cir::BinOpKind kind,
-                          const llvm::APInt &rhs) {
-    return create<cir::BinOp>(lhs.getLoc(), lhs.getType(), kind, lhs,
-                              getConstAPInt(lhs.getLoc(), lhs.getType(), rhs));
-  }
-
-  mlir::Value createBinop(mlir::Value lhs, cir::BinOpKind kind,
-                          mlir::Value rhs) {
-    return create<cir::BinOp>(lhs.getLoc(), lhs.getType(), kind, lhs, rhs);
-  }
-
   mlir::Value createBinop(mlir::Location loc, mlir::Value lhs,
                           cir::BinOpKind kind, mlir::Value rhs) {
     return create<cir::BinOp>(loc, lhs.getType(), kind, lhs, rhs);
@@ -166,93 +156,74 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
   mlir::Value createLowBitsSet(mlir::Location loc, unsigned size,
                                unsigned bits) {
     llvm::APInt val = llvm::APInt::getLowBitsSet(size, bits);
-    auto type = cir::IntType::get(getContext(), size, false);
+    auto type = cir::IntType::get(getContext(), size, /*isSigned=*/false);
     return getConstAPInt(loc, type, val);
   }
 
-  mlir::Value createAnd(mlir::Value lhs, const llvm::APInt &rhs) {
-    mlir::Value val = getConstAPInt(lhs.getLoc(), lhs.getType(), rhs);
-    return createBinop(lhs, cir::BinOpKind::And, val);
-  }
-
-  mlir::Value createAnd(mlir::Value lhs, mlir::Value rhs) {
-    return createBinop(lhs, cir::BinOpKind::And, rhs);
-  }
-
   mlir::Value createAnd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     return createBinop(loc, lhs, cir::BinOpKind::And, rhs);
   }
 
-  mlir::Value createOr(mlir::Value lhs, const llvm::APInt &rhs) {
-    mlir::Value val = getConstAPInt(lhs.getLoc(), lhs.getType(), rhs);
-    return createBinop(lhs, cir::BinOpKind::Or, val);
-  }
-
-  mlir::Value createOr(mlir::Value lhs, mlir::Value rhs) {
-    return createBinop(lhs, cir::BinOpKind::Or, rhs);
+  mlir::Value createOr(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
+    return createBinop(loc, lhs, cir::BinOpKind::Or, rhs);
   }
 
-  mlir::Value createMul(mlir::Value lhs, mlir::Value rhs, bool hasNUW = false,
-                        bool hasNSW = false) {
-    auto op = create<cir::BinOp>(lhs.getLoc(), lhs.getType(),
-                                 cir::BinOpKind::Mul, lhs, rhs);
-    if (hasNUW)
-      op.setNoUnsignedWrap(true);
-    if (hasNSW)
-      op.setNoSignedWrap(true);
+  mlir::Value createMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
+                        bool hasNUW = false, bool hasNSW = false) {
+    auto op =
+        create<cir::BinOp>(loc, lhs.getType(), cir::BinOpKind::Mul, lhs, rhs);
+    op.setNoUnsignedWrap(hasNUW);
+    op.setNoSignedWrap(hasNSW);
     return op;
   }
-  mlir::Value createNSWMul(mlir::Value lhs, mlir::Value rhs) {
-    return createMul(lhs, rhs, false, true);
-  }
-  mlir::Value createNUWAMul(mlir::Value lhs, mlir::Value rhs) {
-    return createMul(lhs, rhs, true, false);
+  mlir::Value createNSWMul(mlir::Location loc, mlir::Value lhs,
+                           mlir::Value rhs) {
+    return createMul(loc, lhs, rhs, false, true);
   }
-
-  mlir::Value createMul(mlir::Value lhs, const llvm::APInt &rhs) {
-    mlir::Value val = getConstAPInt(lhs.getLoc(), lhs.getType(), rhs);
-    return createBinop(lhs, cir::BinOpKind::Mul, val);
+  mlir::Value createNUWAMul(mlir::Location loc, mlir::Value lhs,
+                            mlir::Value rhs) {
+    return createMul(loc, lhs, rhs, true, false);
   }
 
-  mlir::Value createSub(mlir::Value lhs, mlir::Value rhs, bool hasNUW = false,
-                        bool hasNSW = false, bool saturated = false) {
-    auto op = create<cir::BinOp>(lhs.getLoc(), lhs.getType(),
-                                 cir::BinOpKind::Sub, lhs, rhs);
-    if (hasNUW)
-      op.setNoUnsignedWrap(true);
-    if (hasNSW)
-      op.setNoSignedWrap(true);
-    if (saturated)
-      op.setSaturated(true);
+  mlir::Value createSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
+                        bool hasNUW = false, bool hasNSW = false,
+                        bool saturated = false) {
+    auto op =
+        create<cir::BinOp>(loc, lhs.getType(), cir::BinOpKind::Sub, lhs, rhs);
+    op.setNoUnsignedWrap(hasNUW);
+    op.setNoSignedWrap(hasNSW);
+    op.setSaturated(saturated);
     return op;
   }
 
-  mlir::Value createNSWSub(mlir::Value lhs, mlir::Value rhs) {
-    return createSub(lhs, rhs, false, true);
+  mlir::Value createNSWSub(mlir::Location loc, mlir::Value lhs,
+                           mlir::Value rhs) {
+    return createSub(loc, lhs, rhs, false, true);
   }
 
-  mlir::Value createNUWSub(mlir::Value lhs, mlir::Value rhs) {
-    return createSub(lhs, rhs, true, false);
+  mlir::Value createNUWSub(mlir::Location loc, mlir::Value lhs,
+                           mlir::Value rhs) {
+    return createSub(loc, lhs, rhs, true, false);
   }
 
-  mlir::Value createAdd(mlir::Value lhs, mlir::Value rhs, bool hasNUW = false,
-                        bool hasNSW = false, bool saturated = false) {
-    auto op = create<cir::BinOp>(lhs.getLoc(), lhs.getType(),
-                                 cir::BinOpKind::Add, lhs, rhs);
-    if (hasNUW)
-      op.setNoUnsignedWrap(true);
-    if (hasNSW)
-      op.setNoSignedWrap(true);
-    if (saturated)
-      op.setSaturated(true);
+  mlir::Value createAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
+                        bool hasNUW = false, bool hasNSW = false,
+                        bool saturated = false) {
+    auto op =
+        create<cir::BinOp>(loc, lhs.getType(), cir::BinOpKind::Add, lhs, rhs);
+    op.setNoUnsignedWrap(hasNUW);
+    op.setNoSignedWrap(hasNSW);
+    op.setSaturated(saturated);
     return op;
   }
 
-  mlir::Value createNSWAdd(mlir::Value lhs, mlir::Value rhs) {
-    return createAdd(lhs, rhs, false, true);
+  mlir::Value createNSWAdd(mlir::Location loc, mlir::Value lhs,
+                           mlir::Value rhs) {
+    return createAdd(loc, lhs, rhs, false, true);
   }
-  mlir::Value createNUWAdd(mlir::Value lhs, mlir::Value rhs) {
-    return createAdd(lhs, rhs, true, false);
+  mlir::Value createNUWAdd(mlir::Location loc, mlir::Value lhs,
+                           mlir::Value rhs) {
+    return createAdd(loc, lhs, rhs, true, false);
   }
 
   //
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index dca17e6cd2d2d..3d49f88b032cb 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -852,7 +852,6 @@ def BinOpKind : I32EnumAttr<
   let cppNamespace = "::cir";
 }
 
-// FIXME: Pure won't work when we add overloading.
 def BinOp : CIR_Op<"binop", [Pure,
   SameTypeOperands, SameOperandsAndResultType]> {
 
diff --git a/clang/include/clang/CIR/MissingFeatures.h b/clang/include/clang/CIR/MissingFeatures.h
index 7ddc7480630aa..3adca513b1c2d 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -96,7 +96,6 @@ struct MissingFeatures {
   static bool stackSaveOp() { return false; }
   static bool aggValueSlot() { return false; }
   static bool generateDebugInfo() { return false; }
-  static bool getFPFeaturesInEffect() { return false; }
   static bool pointerOverflowSanitizer() { return false; }
   static bool fpConstraints() { return false; }
   static bool sanitizers() { return false; }
@@ -137,7 +136,7 @@ struct MissingFeatures {
   static bool tryOp() { return false; }
   static bool zextOp() { return false; }
   static bool ptrStrideOp() { return false; }
-  static bool opPtrDiff() { return false; }
+  static bool ptrDiffOp() { return false; }
 };
 
 } // namespace cir
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index de868ac821745..02491edfa6c28 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -162,8 +162,7 @@ getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr) {
 
   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
-    if (TSK == TSK_ImplicitInstantiation ||
-        TSK == TSK_Undeclared)
+    if (TSK == TSK_ImplicitInstantiation || TSK == TSK_Undeclared)
       return {};
   }
 
@@ -183,8 +182,7 @@ getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr) {
 
   // TODO: we could look up template parameter documentation in the template
   // documentation.
-  if (isa<TemplateTypeParmDecl>(D) ||
-      isa<NonTypeTemplateParmDecl>(D) ||
+  if (isa<TemplateTypeParmDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
       isa<TemplateTemplateParmDecl>(D))
     return {};
 
@@ -293,8 +291,8 @@ RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
 
   // Get the corresponding buffer.
   bool Invalid = false;
-  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
-                                               &Invalid).data();
+  const char *Buffer =
+      SourceMgr.getBufferData(DeclLocDecomp.first, &Invalid).data();
   if (Invalid)
     return nullptr;
 
@@ -419,9 +417,9 @@ static const Decl &adjustDeclToTemplate(const Decl &D) {
   return D;
 }
 
-const RawComment *ASTContext::getRawCommentForAnyRedecl(
-                                                const Decl *D,
-                                                const Decl **OriginalDecl) const {
+const RawComment *
+ASTContext::getRawCommentForAnyRedecl(const Decl *D,
+                                      const Decl **OriginalDecl) const {
   if (!D) {
     if (OriginalDecl)
       OriginalDecl = nullptr;
@@ -510,8 +508,9 @@ void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
   CommentlessRedeclChains.erase(CanonicalDecl);
 }
 
-static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
-                   SmallVectorImpl<const NamedDecl *> &Redeclared) {
+static void
+addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
+                     SmallVectorImpl<const NamedDecl *> &Redeclared) {
   const DeclContext *DC = ObjCMethod->getDeclContext();
   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
@@ -519,9 +518,8 @@ static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
       return;
     // Add redeclared method here.
     for (const auto *Ext : ID->known_extensions()) {
-      if (ObjCMethodDecl *RedeclaredMethod =
-            Ext->getMethod(ObjCMethod->getSelector(),
-                                  ObjCMethod->isInstanceMethod()))
+      if (ObjCMethodDecl *RedeclaredMethod = Ext->getMethod(
+              ObjCMethod->getSelector(), ObjCMethod->isInstanceMethod()))
         Redeclared.push_back(RedeclaredMethod);
     }
   }
@@ -599,19 +597,18 @@ comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
   if (!ThisDeclInfo->TemplateParameters)
     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
   comments::FullComment *CFC =
-    new (*this) comments::FullComment(FC->getBlocks(),
-                                      ThisDeclInfo);
+      new (*this) comments::FullComment(FC->getBlocks(), ThisDeclInfo);
   return CFC;
 }
 
-comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
+comments::FullComment *
+ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
   const RawComment *RC = getRawCommentForDeclNoCache(D);
   return RC ? RC->parse(*this, nullptr, D) : nullptr;
 }
 
-comments::FullComment *ASTContext::getCommentForDecl(
-                                              const Decl *D,
-                                              const Preprocessor *PP) const {
+comments::FullComment *
+ASTContext::getCommentForDecl(const Decl *D, const Preprocessor *PP) const {
   if (!D || D->isInvalidDecl())
     return nullptr;
   D = &adjustDeclToTemplate(*D);
@@ -634,7 +631,7 @@ comments::FullComment *ASTContext::getCommentForDecl(
   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
   if (!RC) {
     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
-      SmallVector<const NamedDecl*, 8> Overridden;
+      SmallVector<const NamedDecl *, 8> Overridden;
       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
       if (OMD && OMD->isPropertyAccessor())
         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
@@ -646,8 +643,7 @@ comments::FullComment *ASTContext::getCommentForDecl(
       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
           return cloneFullComment(FC, D);
-    }
-    else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
+    } else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
       // Attach any tag type's documentation to its typedef if latter
       // does not have one of its own.
       QualType QT = TD->getUnderlyingType();
@@ -655,20 +651,17 @@ comments::FullComment *ASTContext::getCommentForDecl(
         if (const Decl *TD = TT->getDecl())
           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
             return cloneFullComment(FC, D);
-    }
-    else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
+    } else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
       while (IC->getSuperClass()) {
         IC = IC->getSuperClass();
         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
           return cloneFullComment(FC, D);
       }
-    }
-    else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
+    } else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
           return cloneFullComment(FC, D);
-    }
-    else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
+    } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
       if (!(RD = RD->getDefinition()))
         return nullptr;
       // Check non-virtual bases.
@@ -679,10 +672,11 @@ comments::FullComment *ASTContext::getCommentForDecl(
         if (Ty.isNull())
           continue;
         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
-          if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
+          if (!(NonVirtualBase = NonVirtualBase->getDefinition()))
             continue;
 
-          if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
+          if (comments::FullComment *FC =
+                  getCommentForDecl((NonVirtualBase), PP))
             return cloneFullComment(FC, D);
         }
       }
@@ -694,7 +688,7 @@ comments::FullComment *ASTContext::getCommentForDecl(
         if (Ty.isNull())
           continue;
         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
-          if (!(VirtualBase= VirtualBase->getDefinition()))
+          if (!(VirtualBase = VirtualBase->getDefinition()))
             continue;
           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
             return cloneFullComment(FC, D);
@@ -716,10 +710,9 @@ comments::FullComment *ASTContext::getCommentForDecl(
   return FC;
 }
 
-void
-ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
-                                                   const ASTContext &C,
-                                               TemplateTemplateParmDecl *Parm) {
+void ASTContext::CanonicalTemplateTemplateParm::Profile(
+    llvm::FoldingSetNodeID &ID, const ASTContext &C,
+    TemplateTemplateParmDecl *Parm) {
   ID.AddInteger(Parm->getDepth());
   ID.AddInteger(Parm->getPosition());
   ID.AddBoolean(Parm->isParameterPack());
@@ -727,7 +720,7 @@ ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
   TemplateParameterList *Params = Parm->getTemplateParameters();
   ID.AddInteger(Params->size());
   for (TemplateParameterList::const_iterator P = Params->begin(),
-                                          PEnd = Params->end();
+                                             PEnd = Params->end();
        P != PEnd; ++P) {
     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
       ID.AddInteger(0);
@@ -763,15 +756,14 @@ ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
   }
 }
 
-TemplateTemplateParmDecl *
-ASTContext::getCanonicalTemplateTemplateParmDecl(
-                                          TemplateTemplateParmDecl *TTP) const {
+TemplateTemplateParmDecl *ASTContext::getCanonicalTemplateTemplateParmDecl(
+    TemplateTemplateParmDecl *TTP) const {
   // Check if we already have a canonical template template parameter.
   llvm::FoldingSetNodeID ID;
   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
   void *InsertPos = nullptr;
-  CanonicalTemplateTemplateParm *Canonical
-    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
+  CanonicalTemplateTemplateParm *Canonical =
+      CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
   if (Canonical)
     return Canonical->getParam();
 
@@ -780,7 +772,7 @@ ASTContext::getCanonicalTemplateTemplateParmDecl(
   SmallVector<NamedDecl *, 4> CanonParams;
   CanonParams.reserve(Params->size());
   for (TemplateParameterList::const_iterator P = Params->begin(),
-                                          PEnd = Params->end();
+                                             PEnd = Params->end();
        P != PEnd; ++P) {
     // Note that, per C++20 [temp.over.link]/6, when determining whether
     // template-parameters are equivalent, constraints are ignored.
@@ -803,32 +795,23 @@ ASTContext::getCanonicalTemplateTemplateParmDecl(
         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
           ExpandedTInfos.push_back(
-                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
+              getTrivialTypeSourceInfo(ExpandedTypes.back()));
         }
 
-        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
-                                                SourceLocation(),
-                                                SourceLocation(),
-                                                NTTP->getDepth(),
-                                                NTTP->getPosition(), nullptr,
-                                                T,
-                                                TInfo,
-                                                ExpandedTypes,
-                                                ExpandedTInfos);
+        Param = NonTypeTemplateParmDecl::Create(
+            *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
+            NTTP->getDepth(), NTTP->getPosition(), nullptr, T, TInfo,
+            ExpandedTypes, ExpandedTInfos);
       } else {
-        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
-                                                SourceLocation(),
-                                                SourceLocation(),
-                                                NTTP->getDepth(),
-                                                NTTP->getPosition(), nullptr,
-                                                T,
-                                                NTTP->isParameterPack(),
-                                                TInfo);
+        Param = NonTypeTemplateParmDecl::Create(
+            *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
+            NTTP->getDepth(), NTTP->getPosition(), nullptr, T,
+            NTTP->isParameterPack(), TInfo);
       }
       CanonParams.push_back(Param);
     } else
       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
-                                           cast<TemplateTemplateParmDecl>(*P)));
+          cast<TemplateTemplateParmDecl>(*P)));
   }
 
   TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
@@ -864,7 +847,8 @@ TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
 }
 
 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
-  if (!LangOpts.CPlusPlus) return nullptr;
+  if (!LangOpts.CPlusPlus)
+    return nullptr;
 
   switch (getCXXABIKind()) {
   case TargetCXXABI::AppleARM64:
@@ -958,16 +942,18 @@ void ASTContext::cleanup() {
       R->Destroy(*this);
   ObjCLayouts.clear();
 
-  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
-       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
+  for (llvm::DenseMap<const RecordDecl *, const ASTRecordLayout *>::iterator
+           I = ASTRecordLayouts.begin(),
+           E = ASTRecordLayouts.end();
+       I != E;) {
     // Increment in loop to prevent using deallocated memory.
     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
       R->Destroy(*this);
   }
   ASTRecordLayouts.clear();
 
-  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
-                                                    AEnd = DeclAttrs.end();
+  for (llvm::DenseMap<const Decl *, AttrVec *>::iterator A = DeclAttrs.begin(),
+                                                         AEnd = DeclAttrs.end();
        A != AEnd; ++A)
     A->second->~AttrVec();
   DeclAttrs.clear();
@@ -988,8 +974,8 @@ void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
   Deallocations.push_back({Callback, Data});
 }
 
-void
-ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
+void ASTContext::setExternalSource(
+    IntrusiveRefCntPtr<ExternalASTSource> Source) {
   ExternalSource = std::move(Source);
 }
 
@@ -1001,7 +987,7 @@ void ASTContext::PrintStats() const {
 #define TYPE(Name, Parent) 0,
 #define ABSTRACT_TYPE(Name, Parent)
 #include "clang/AST/TypeNodes.inc"
-    0 // Extra
+      0 // Extra
   };
 
   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
@@ -1011,13 +997,12 @@ void ASTContext::PrintStats() const {
 
   unsigned Idx = 0;
   unsigned TotalBytes = 0;
-#define TYPE(Name, Parent)                                              \
-  if (counts[Idx])                                                      \
-    llvm::errs() << "    " << counts[Idx] << " " << #Name               \
-                 << " types, " << sizeof(Name##Type) << " each "        \
-                 << "(" << counts[Idx] * sizeof(Name##Type)             \
-                 << " bytes)\n";                                        \
-  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
+#define TYPE(Name, Parent)                                                     \
+  if (counts[Idx])                                                             \
+    llvm::errs() << "    " << counts[Idx] << " " << #Name << " types, "        \
+                 << sizeof(Name##Type) << " each "                             \
+                 << "(" << counts[Idx] * sizeof(Name##Type) << " bytes)\n";    \
+  TotalBytes += counts[Idx] * sizeof(Name##Type);                              \
   ++Idx;
 #define ABSTRACT_TYPE(Name, Parent)
 #include "clang/AST/TypeNodes.inc"
@@ -1043,8 +1028,7 @@ void ASTContext::PrintStats() const {
                  << NumImplicitMoveAssignmentOperators
                  << " implicit move assignment operators created\n";
   llvm::errs() << NumImplicitDestructorsDeclared << "/"
-               << NumImplicitDestructors
-               << " implicit destructors created\n";
+               << NumImplicitDestructors << " implicit destructors created\n";
 
   if (ExternalSource) {
     llvm::errs() << "\n";
@@ -1070,7 +1054,7 @@ void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
     return;
 
   auto &Merged = It->second;
-  llvm::DenseSet<Module*> Found;
+  llvm::DenseSet<Module *> Found;
   for (Module *&M : Merged)
     if (!Found.insert(M).second)
       M = nullptr;
@@ -1134,8 +1118,8 @@ void ASTContext::addLazyModuleInitializers(Module *M,
   auto *&Inits = ModuleInitializers[M];
   if (!Inits)
     Inits = new (*this) PerModuleInitializers;
-  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
-                                 IDs.begin(), IDs.end());
+  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), IDs.begin(),
+                                 IDs.end());
 }
 
 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
@@ -1182,7 +1166,8 @@ bool ASTContext::isInSameModule(const Module *M1, const Module *M2) {
 
 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
   if (!ExternCContext)
-    ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
+    ExternCContext =
+        ExternCContextDecl::Create(*this, getTranslationUnitDecl());
 
   return ExternCContext;
 }
@@ -1264,78 +1249,78 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
 
   // C99 6.2.5p19.
-  InitBuiltinType(VoidTy,              BuiltinType::Void);
+  InitBuiltinType(VoidTy, BuiltinType::Void);
 
   // C99 6.2.5p2.
-  InitBuiltinType(BoolTy,              BuiltinType::Bool);
+  InitBuiltinType(BoolTy, BuiltinType::Bool);
   // C99 6.2.5p3.
   if (LangOpts.CharIsSigned)
-    InitBuiltinType(CharTy,            BuiltinType::Char_S);
+    InitBuiltinType(CharTy, BuiltinType::Char_S);
   else
-    InitBuiltinType(CharTy,            BuiltinType::Char_U);
+    InitBuiltinType(CharTy, BuiltinType::Char_U);
   // C99 6.2.5p4.
-  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
-  InitBuiltinType(ShortTy,             BuiltinType::Short);
-  InitBuiltinType(IntTy,               BuiltinType::Int);
-  InitBuiltinType(LongTy,              BuiltinType::Long);
-  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
+  InitBuiltinType(SignedCharTy, BuiltinType::SChar);
+  InitBuiltinType(ShortTy, BuiltinType::Short);
+  InitBuiltinType(IntTy, BuiltinType::Int);
+  InitBuiltinType(LongTy, BuiltinType::Long);
+  InitBuiltinType(LongLongTy, BuiltinType::LongLong);
 
   // C99 6.2.5p6.
-  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
-  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
-  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
-  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
-  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
+  InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
+  InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
+  InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
+  InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
+  InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
 
   // C99 6.2.5p10.
-  InitBuiltinType(FloatTy,             BuiltinType::Float);
-  InitBuiltinType(DoubleTy,            BuiltinType::Double);
-  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
+  InitBuiltinType(FloatTy, BuiltinType::Float);
+  InitBuiltinType(DoubleTy, BuiltinType::Double);
+  InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
 
   // GNU extension, __float128 for IEEE quadruple precision
-  InitBuiltinType(Float128Ty,          BuiltinType::Float128);
+  InitBuiltinType(Float128Ty, BuiltinType::Float128);
 
   // __ibm128 for IBM extended precision
   InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
 
   // C11 extension ISO/IEC TS 18661-3
-  InitBuiltinType(Float16Ty,           BuiltinType::Float16);
+  InitBuiltinType(Float16Ty, BuiltinType::Float16);
 
   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
-  InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
-  InitBuiltinType(AccumTy,                 BuiltinType::Accum);
-  InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
-  InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
-  InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
-  InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
-  InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
-  InitBuiltinType(FractTy,                 BuiltinType::Fract);
-  InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
-  InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
-  InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
-  InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
-  InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
-  InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
-  InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
+  InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
+  InitBuiltinType(AccumTy, BuiltinType::Accum);
+  InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
+  InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
+  InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
+  InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
+  InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
+  InitBuiltinType(FractTy, BuiltinType::Fract);
+  InitBuiltinType(LongFractTy, BuiltinType::LongFract);
+  InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
+  InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
+  InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
+  InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
+  InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
+  InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
-  InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
-  InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
-  InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
-  InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
-  InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
+  InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
+  InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
+  InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
+  InitBuiltinType(SatFractTy, BuiltinType::SatFract);
+  InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
-  InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
-  InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
+  InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
+  InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
 
   // GNU extension, 128-bit integers.
-  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
-  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
+  InitBuiltinType(Int128Ty, BuiltinType::Int128);
+  InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
 
   // C++ 3.9.1p5
   if (TargetInfo::isTypeSigned(Target.getWCharType()))
-    InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
-  else  // -fshort-wchar makes wchar_t be unsigned.
-    InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
+    InitBuiltinType(WCharTy, BuiltinType::WChar_S);
+  else // -fshort-wchar makes wchar_t be unsigned.
+    InitBuiltinType(WCharTy, BuiltinType::WChar_U);
   if (LangOpts.CPlusPlus && LangOpts.WChar)
     WideCharTy = WCharTy;
   else {
@@ -1346,15 +1331,15 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   WIntTy = getFromTargetType(Target.getWIntType());
 
   // C++20 (proposed)
-  InitBuiltinType(Char8Ty,              BuiltinType::Char8);
+  InitBuiltinType(Char8Ty, BuiltinType::Char8);
 
   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
-    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
+    InitBuiltinType(Char16Ty, BuiltinType::Char16);
   else // C99
     Char16Ty = getFromTargetType(Target.getChar16Type());
 
   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
-    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
+    InitBuiltinType(Char32Ty, BuiltinType::Char32);
   else // C99
     Char32Ty = getFromTargetType(Target.getChar32Type());
 
@@ -1363,28 +1348,28 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   // DependentTy and users should never see it; however, it is here to
   // help diagnose failures to properly check for type-dependent
   // expressions.
-  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
+  InitBuiltinType(DependentTy, BuiltinType::Dependent);
 
   // Placeholder type for functions.
-  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
+  InitBuiltinType(OverloadTy, BuiltinType::Overload);
 
   // Placeholder type for bound members.
-  InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
+  InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
 
   // Placeholder type for unresolved templates.
   InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
 
   // Placeholder type for pseudo-objects.
-  InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
+  InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
 
   // "any" type; useful for debugger-like clients.
-  InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
+  InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
 
   // Placeholder type for unbridged ARC casts.
-  InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
+  InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
 
   // Placeholder type for builtin functions.
-  InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
+  InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
 
   // Placeholder type for OMP array sections.
   if (LangOpts.OpenMP) {
@@ -1406,8 +1391,8 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
 
   if (LangOpts.OpenCL) {
-#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
-    InitBuiltinType(SingletonId, BuiltinType::Id);
+#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
+  InitBuiltinType(SingletonId, BuiltinType::Id);
 #include "clang/Basic/OpenCLImageTypes.def"
 
     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
@@ -1416,8 +1401,8 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
 
-#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
-    InitBuiltinType(Id##Ty, BuiltinType::Id);
+#define EXT_OPAQUE_TYPE(ExtType, Id, Ext)                                      \
+  InitBuiltinType(Id##Ty, BuiltinType::Id);
 #include "clang/Basic/OpenCLExtensionTypes.def"
   }
 
@@ -1429,17 +1414,17 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
 
   if (Target.hasAArch64SVETypes() ||
       (AuxTarget && AuxTarget->hasAArch64SVETypes())) {
-#define SVE_TYPE(Name, Id, SingletonId) \
-    InitBuiltinType(SingletonId, BuiltinType::Id);
+#define SVE_TYPE(Name, Id, SingletonId)                                        \
+  InitBuiltinType(SingletonId, BuiltinType::Id);
 #include "clang/Basic/AArch64SVEACLETypes.def"
   }
 
   if (Target.getTriple().isPPC64()) {
-#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
-      InitBuiltinType(Id##Ty, BuiltinType::Id);
+#define PPC_VECTOR_MMA_TYPE(Name, Id, Size)                                    \
+  InitBuiltinType(Id##Ty, BuiltinType::Id);
 #include "clang/Basic/PPCTypes.def"
-#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
-    InitBuiltinType(Id##Ty, BuiltinType::Id);
+#define PPC_VECTOR_VSX_TYPE(Name, Id, Size)                                    \
+  InitBuiltinType(Id##Ty, BuiltinType::Id);
 #include "clang/Basic/PPCTypes.def"
   }
 
@@ -1463,8 +1448,8 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   }
 
   // Builtin type for __objc_yes and __objc_no
-  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
-                       SignedCharTy : BoolTy);
+  ObjCBuiltinBoolTy =
+      (Target.useSignedCharForObjCBool() ? SignedCharTy : BoolTy);
 
   ObjCConstantStringType = QualType();
 
@@ -1474,14 +1459,14 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   if (LangOpts.OpenCLGenericAddressSpace) {
     auto Q = VoidTy.getQualifiers();
     Q.setAddressSpace(LangAS::opencl_generic);
-    VoidPtrTy = getPointerType(getCanonicalType(
-        getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
+    VoidPtrTy = getPointerType(
+        getCanonicalType(getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
   } else {
     VoidPtrTy = getPointerType(VoidTy);
   }
 
   // nullptr type (C++0x 2.14.7)
-  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
+  InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
 
   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
   InitBuiltinType(HalfTy, BuiltinType::Half);
@@ -1502,7 +1487,7 @@ DiagnosticsEngine &ASTContext::getDiagnostics() const {
   return SourceMgr.getDiagnostics();
 }
 
-AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
+AttrVec &ASTContext::getDeclAttrs(const Decl *D) {
   AttrVec *&Result = DeclAttrs[D];
   if (!Result) {
     void *Mem = Allocate(sizeof(AttrVec));
@@ -1514,7 +1499,7 @@ AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
 
 /// Erase the attributes corresponding to the given declaration.
 void ASTContext::eraseDeclAttrs(const Decl *D) {
-  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
+  llvm::DenseMap<const Decl *, AttrVec *>::iterator Pos = DeclAttrs.find(D);
   if (Pos != DeclAttrs.end()) {
     Pos->second->~AttrVec();
     DeclAttrs.erase(Pos);
@@ -1539,37 +1524,32 @@ ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
   return Pos->second;
 }
 
-void
-ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
-                                                TemplateSpecializationKind TSK,
-                                          SourceLocation PointOfInstantiation) {
+void ASTContext::setInstantiatedFromStaticDataMember(
+    VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK,
+    SourceLocation PointOfInstantiation) {
   assert(Inst->isStaticDataMember() && "Not a static data member");
   assert(Tmpl->isStaticDataMember() && "Not a static data member");
   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
                                             Tmpl, TSK, PointOfInstantiation));
 }
 
-void
-ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
-                                            TemplateOrSpecializationInfo TSI) {
+void ASTContext::setTemplateOrSpecializationInfo(
+    VarDecl *Inst, TemplateOrSpecializationInfo TSI) {
   assert(!TemplateOrInstantiation[Inst] &&
          "Already noted what the variable was instantiated from");
   TemplateOrInstantiation[Inst] = TSI;
 }
 
-NamedDecl *
-ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
+NamedDecl *ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
   return InstantiatedFromUsingDecl.lookup(UUD);
 }
 
-void
-ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
-  assert((isa<UsingDecl>(Pattern) ||
-          isa<UnresolvedUsingValueDecl>(Pattern) ||
+void ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst,
+                                              NamedDecl *Pattern) {
+  assert((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) ||
           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
          "pattern decl is not a using decl");
-  assert((isa<UsingDecl>(Inst) ||
-          isa<UnresolvedUsingValueDecl>(Inst) ||
+  assert((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) ||
           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
          "instantiation did not produce a using decl");
   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
@@ -1592,9 +1572,8 @@ ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
   return InstantiatedFromUsingShadowDecl.lookup(Inst);
 }
 
-void
-ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
-                                               UsingShadowDecl *Pattern) {
+void ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
+                                                    UsingShadowDecl *Pattern) {
   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
 }
@@ -1648,8 +1627,7 @@ void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
 }
 
 void ASTContext::getOverriddenMethods(
-                      const NamedDecl *D,
-                      SmallVectorImpl<const NamedDecl *> &Overridden) const {
+    const NamedDecl *D, SmallVectorImpl<const NamedDecl *> &Overridden) const {
   assert(D);
 
   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
@@ -1697,8 +1675,10 @@ const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
     return Target->getHalfFormat();
   case BuiltinType::Half:
     return Target->getHalfFormat();
-  case BuiltinType::Float:      return Target->getFloatFormat();
-  case BuiltinType::Double:     return Target->getDoubleFormat();
+  case BuiltinType::Float:
+    return Target->getFloatFormat();
+  case BuiltinType::Double:
+    return Target->getDoubleFormat();
   case BuiltinType::Ibm128:
     return Target->getIbm128Format();
   case BuiltinType::LongDouble:
@@ -1838,13 +1818,12 @@ TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
 
 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
-TypeInfoChars
-static getConstantArrayInfoInChars(const ASTContext &Context,
-                                   const ConstantArrayType *CAT) {
+TypeInfoChars static getConstantArrayInfoInChars(const ASTContext &Context,
+                                                 const ConstantArrayType *CAT) {
   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
   uint64_t Size = CAT->getZExtSize();
   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
-              (uint64_t)(-1)/Size) &&
+                           (uint64_t)(-1) / Size) &&
          "Overflow in array type char size evaluation");
   uint64_t Width = EltInfo.Width.getQuantity() * Size;
   unsigned Align = EltInfo.Align.getQuantity();
@@ -1968,8 +1947,8 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
   case Type::Class:                                                            \
-  assert(!T->isDependentType() && "should not see dependent types here");      \
-  return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
+    assert(!T->isDependentType() && "should not see dependent types here");    \
+    return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
 #include "clang/AST/TypeNodes.inc"
     llvm_unreachable("Should not see dependent types");
 
@@ -2014,7 +1993,7 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
 
     // If the alignment is not a power of 2, round up to the next power of 2.
     // This happens for non-power-of-2 length vectors.
-    if (Align & (Align-1)) {
+    if (Align & (Align - 1)) {
       Align = llvm::bit_ceil(Align);
       Width = llvm::alignTo(Width, Align);
     }
@@ -2052,7 +2031,8 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
 
   case Type::Builtin:
     switch (cast<BuiltinType>(T)->getKind()) {
-    default: llvm_unreachable("Unknown builtin type!");
+    default:
+      llvm_unreachable("Unknown builtin type!");
     case BuiltinType::Void:
       // GCC extension: alignof(void) = 8 bits.
       Width = 0;
@@ -2226,24 +2206,23 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
     case BuiltinType::OCLClkEvent:
     case BuiltinType::OCLQueue:
     case BuiltinType::OCLReserveID:
-#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
-    case BuiltinType::Id:
-#include "clang/Basic/OpenCLImageTypes.def"
-#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
+#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
   case BuiltinType::Id:
+#include "clang/Basic/OpenCLImageTypes.def"
+#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
 #include "clang/Basic/OpenCLExtensionTypes.def"
       AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
       Width = Target->getPointerWidth(AS);
       Align = Target->getPointerAlign(AS);
       break;
-    // The SVE types are effectively target-specific.  The length of an
-    // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
-    // of 128 bits.  There is one predicate bit for each vector byte, so the
-    // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
-    //
-    // Because the length is only known at runtime, we use a dummy value
-    // of 0 for the static length.  The alignment values are those defined
-    // by the Procedure Call Standard for the Arm Architecture.
+      // The SVE types are effectively target-specific.  The length of an
+      // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
+      // of 128 bits.  There is one predicate bit for each vector byte, so the
+      // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
+      //
+      // Because the length is only known at runtime, we use a dummy value
+      // of 0 for the static length.  The alignment values are those defined
+      // by the Procedure Call Standard for the Arm Architecture.
 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId)                    \
   case BuiltinType::Id:                                                        \
     Width = 0;                                                                 \
@@ -2395,8 +2374,8 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
   }
 
   case Type::SubstTemplateTypeParm:
-    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
-                       getReplacementType().getTypePtr());
+    return getTypeInfo(
+        cast<SubstTemplateTypeParmType>(T)->getReplacementType().getTypePtr());
 
   case Type::Auto:
   case Type::DeducedTemplateSpecialization: {
@@ -2441,7 +2420,7 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
 
   case Type::Attributed:
     return getTypeInfo(
-                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
+        cast<AttributedType>(T)->getEquivalentType().getTypePtr());
 
   case Type::CountAttributed:
     return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
@@ -2476,8 +2455,7 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
       // Set the alignment equal to the size.
       Align = static_cast<unsigned>(Width);
     }
-  }
-  break;
+  } break;
 
   case Type::Pipe:
     Width = Target->getPointerWidth(LangAS::opencl_global);
@@ -2653,7 +2631,7 @@ CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
   const ValueDecl *MPD = MP.getMemberPointerDecl();
   CharUnits ThisAdjustment = CharUnits::Zero();
-  ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
+  ArrayRef<const CXXRecordDecl *> Path = MP.getMemberPointerPath();
   bool DerivedMember = MP.isMemberPointerToDerivedMember();
   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
@@ -2674,9 +2652,9 @@ CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
 /// super class and then collects all ivars, including those synthesized for
 /// current class. This routine is used for implementation of current class
 /// when all ivars, declared and synthesized are known.
-void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
-                                      bool leafClass,
-                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
+void ASTContext::DeepCollectObjCIvars(
+    const ObjCInterfaceDecl *OI, bool leafClass,
+    SmallVectorImpl<const ObjCIvarDecl *> &Ivars) const {
   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
     DeepCollectObjCIvars(SuperClass, false, Ivars);
   if (!leafClass) {
@@ -2684,15 +2662,15 @@ void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
   } else {
     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
-         Iv= Iv->getNextIvar())
+         Iv = Iv->getNextIvar())
       Ivars.push_back(Iv);
   }
 }
 
 /// CollectInheritedProtocols - Collect all protocols in current class and
 /// those inherited by it.
-void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
-                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
+void ASTContext::CollectInheritedProtocols(
+    const Decl *CDecl, llvm::SmallPtrSet<ObjCProtocolDecl *, 8> &Protocols) {
   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
     // We can use protocol_iterator here instead of
     // all_referenced_protocol_iterator since we are walking all categories.
@@ -2715,8 +2693,9 @@ void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
     }
   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
     // Insert the protocol.
-    if (!Protocols.insert(
-          const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
+    if (!Protocols
+             .insert(const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl()))
+             .second)
       return;
 
     for (auto *Proto : OP->protocols())
@@ -2967,24 +2946,27 @@ bool ASTContext::isSentinelNullExpr(const Expr *E) {
     return false;
 
   // nullptr_t is always treated as null.
-  if (E->getType()->isNullPtrType()) return true;
+  if (E->getType()->isNullPtrType())
+    return true;
 
   if (E->getType()->isAnyPointerType() &&
-      E->IgnoreParenCasts()->isNullPointerConstant(*this,
-                                                Expr::NPC_ValueDependentIsNull))
+      E->IgnoreParenCasts()->isNullPointerConstant(
+          *this, Expr::NPC_ValueDependentIsNull))
     return true;
 
   // Unfortunately, __null has type 'int'.
-  if (isa<GNUNullExpr>(E)) return true;
+  if (isa<GNUNullExpr>(E))
+    return true;
 
   return false;
 }
 
 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
 /// exists.
-ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
-  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
-    I = ObjCImpls.find(D);
+ObjCImplementationDecl *
+ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
+  llvm::DenseMap<ObjCContainerDecl *, ObjCImplDecl *>::iterator I =
+      ObjCImpls.find(D);
   if (I != ObjCImpls.end())
     return cast<ObjCImplementationDecl>(I->second);
   return nullptr;
@@ -2993,8 +2975,8 @@ ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D)
 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
 /// exists.
 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
-  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
-    I = ObjCImpls.find(D);
+  llvm::DenseMap<ObjCContainerDecl *, ObjCImplDecl *>::iterator I =
+      ObjCImpls.find(D);
   if (I != ObjCImpls.end())
     return cast<ObjCCategoryImplDecl>(I->second);
   return nullptr;
@@ -3002,14 +2984,14 @@ ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
 
 /// Set the implementation of ObjCInterfaceDecl.
 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
-                           ObjCImplementationDecl *ImplD) {
+                                       ObjCImplementationDecl *ImplD) {
   assert(IFaceD && ImplD && "Passed null params");
   ObjCImpls[IFaceD] = ImplD;
 }
 
 /// Set the implementation of ObjCCategoryDecl.
 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
-                           ObjCCategoryImplDecl *ImplD) {
+                                       ObjCCategoryImplDecl *ImplD) {
   assert(CatD && ImplD && "Passed null params");
   ObjCImpls[CatD] = ImplD;
 }
@@ -3025,8 +3007,8 @@ void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
   ObjCMethodRedecls[MD] = Redecl;
 }
 
-const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
-                                              const NamedDecl *ND) const {
+const ObjCInterfaceDecl *
+ASTContext::getObjContainingInterface(const NamedDecl *ND) const {
   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
     return ID;
   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
@@ -3041,8 +3023,7 @@ const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
 /// none exists.
 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
   assert(VD && "Passed null params");
-  assert(VD->hasAttr<BlocksAttr>() &&
-         "getBlockVarCopyInits - not __block var");
+  assert(VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var");
   auto I = BlockVarCopyInits.find(VD);
   if (I != BlockVarCopyInits.end())
     return I->second;
@@ -3050,11 +3031,10 @@ BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
 }
 
 /// Set the copy initialization expression of a block var decl.
-void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
+void ASTContext::setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr,
                                      bool CanThrow) {
   assert(VD && CopyExpr && "Passed null params");
-  assert(VD->hasAttr<BlocksAttr>() &&
-         "setBlockVarCopyInits - not __block var");
+  assert(VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var");
   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
 }
 
@@ -3066,8 +3046,8 @@ TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
            "incorrect data size provided to CreateTypeSourceInfo!");
 
-  auto *TInfo =
-    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
+  auto *TInfo = (TypeSourceInfo *)BumpAlloc.Allocate(
+      sizeof(TypeSourceInfo) + DataSize, 8);
   new (TInfo) TypeSourceInfo(T, DataSize);
   return TInfo;
 }
@@ -3100,8 +3080,8 @@ static auto getCanonicalTemplateArguments(const ASTContext &C,
 //                   Type creation/memoization methods
 //===----------------------------------------------------------------------===//
 
-QualType
-ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
+QualType ASTContext::getExtQualType(const Type *baseType,
+                                    Qualifiers quals) const {
   unsigned fastQuals = quals.getFastQualifiers();
   quals.removeFastQualifiers();
 
@@ -3122,7 +3102,7 @@ ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
 
     // Re-find the insert position.
-    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
+    (void)ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
   }
 
   auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
@@ -3143,8 +3123,7 @@ QualType ASTContext::getAddrSpaceQualType(QualType T,
 
   // If this type already has an address space specified, it cannot get
   // another one.
-  assert(!Quals.hasAddressSpace() &&
-         "Type cannot be in multiple addr spaces!");
+  assert(!Quals.hasAddressSpace() && "Type cannot be in multiple addr spaces!");
   Quals.addAddressSpace(AddressSpace);
 
   return getExtQualType(TypeNode, Quals);
@@ -3544,8 +3523,7 @@ QualType ASTContext::getObjCGCQualType(QualType T,
 
   // If this type already has an ObjCGC specified, it cannot get
   // another one.
-  assert(!Quals.hasObjCGCAttr() &&
-         "Type cannot have multiple ObjCGCs!");
+  assert(!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!");
   Quals.addObjCGCAttr(GCAttr);
 
   return getExtQualType(TypeNode, Quals);
@@ -3593,10 +3571,9 @@ ASTContext::adjustType(QualType Orig,
   switch (Orig->getTypeClass()) {
   case Type::Attributed: {
     const auto *AT = cast<AttributedType>(Orig);
-    return getAttributedType(AT->getAttrKind(),
-                             adjustType(AT->getModifiedType(), Adjust),
-                             adjustType(AT->getEquivalentType(), Adjust),
-                             AT->getAttr());
+    return getAttributedType(
+        AT->getAttrKind(), adjustType(AT->getModifiedType(), Adjust),
+        adjustType(AT->getEquivalentType(), Adjust), AT->getAttr());
   }
 
   case Type::BTFTagAttributed: {
@@ -3715,9 +3692,8 @@ QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
 }
 
 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
-  return hasSameType(T, U) ||
-         hasSameType(getFunctionTypeWithoutPtrSizes(T),
-                     getFunctionTypeWithoutPtrSizes(U));
+  return hasSameType(T, U) || hasSameType(getFunctionTypeWithoutPtrSizes(T),
+                                          getFunctionTypeWithoutPtrSizes(U));
 }
 
 QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
@@ -3739,8 +3715,7 @@ void ASTContext::adjustExceptionSpec(
     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
     bool AsWritten) {
   // Update the type.
-  QualType Updated =
-      getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
+  QualType Updated = getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
   FD->setType(Updated);
 
   if (!AsWritten)
@@ -3783,7 +3758,8 @@ QualType ASTContext::getComplexType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
   auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
   Types.push_back(New);
@@ -3811,7 +3787,8 @@ QualType ASTContext::getPointerType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
   auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
   Types.push_back(New);
@@ -3926,7 +3903,7 @@ QualType ASTContext::getBlockPointerType(QualType T) const {
 
   void *InsertPos = nullptr;
   if (BlockPointerType *PT =
-        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
+          BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(PT, 0);
 
   // If the block pointee type isn't canonical, this won't be a canonical
@@ -3937,8 +3914,9 @@ QualType ASTContext::getBlockPointerType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     BlockPointerType *NewIP =
-      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
   auto *New =
       new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
@@ -3949,8 +3927,8 @@ QualType ASTContext::getBlockPointerType(QualType T) const {
 
 /// getLValueReferenceType - Return the uniqued reference to the type for an
 /// lvalue reference to the specified type.
-QualType
-ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
+QualType ASTContext::getLValueReferenceType(QualType T,
+                                            bool SpelledAsLValue) const {
   assert((!T->isPlaceholderType() ||
           T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
          "Unresolved placeholder type");
@@ -3962,7 +3940,7 @@ ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
 
   void *InsertPos = nullptr;
   if (LValueReferenceType *RT =
-        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
+          LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(RT, 0);
 
   const auto *InnerRef = T->getAs<ReferenceType>();
@@ -3976,8 +3954,9 @@ ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
 
     // Get the new insert position for the node we care about.
     LValueReferenceType *NewIP =
-      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
 
   auto *New = new (*this, alignof(LValueReferenceType))
@@ -4002,7 +3981,7 @@ QualType ASTContext::getRValueReferenceType(QualType T) const {
 
   void *InsertPos = nullptr;
   if (RValueReferenceType *RT =
-        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
+          RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(RT, 0);
 
   const auto *InnerRef = T->getAs<ReferenceType>();
@@ -4016,8 +3995,9 @@ QualType ASTContext::getRValueReferenceType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     RValueReferenceType *NewIP =
-      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
 
   auto *New = new (*this, alignof(RValueReferenceType))
@@ -4045,7 +4025,7 @@ QualType ASTContext::getMemberPointerType(QualType T,
 
   void *InsertPos = nullptr;
   if (MemberPointerType *PT =
-      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
+          MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(PT, 0);
 
   NestedNameSpecifier *CanonicalQualifier = [&] {
@@ -4083,8 +4063,8 @@ QualType ASTContext::getConstantArrayType(QualType EltTy,
                                           const Expr *SizeExpr,
                                           ArraySizeModifier ASM,
                                           unsigned IndexTypeQuals) const {
-  assert((EltTy->isDependentType() ||
-          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
+  assert((EltTy->isDependentType() || EltTy->isIncompleteType() ||
+          EltTy->isConstantSizeType()) &&
          "Constant array of VLAs is illegal!");
 
   // We only need the size as part of the type if it's instantiation-dependent.
@@ -4102,7 +4082,7 @@ QualType ASTContext::getConstantArrayType(QualType EltTy,
 
   void *InsertPos = nullptr;
   if (ConstantArrayType *ATP =
-      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
+          ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(ATP, 0);
 
   // If the element type isn't canonical or has qualifiers, or the array bound
@@ -4118,8 +4098,9 @@ QualType ASTContext::getConstantArrayType(QualType EltTy,
 
     // Get the new insert position for the node we care about.
     ConstantArrayType *NewIP =
-      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+        ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
 
   auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
@@ -4134,7 +4115,8 @@ QualType ASTContext::getConstantArrayType(QualType EltTy,
 /// sizes replaced with [*].
 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
   // Vastly most common case.
-  if (!type->isVariablyModifiedType()) return type;
+  if (!type->isVariablyModifiedType())
+    return type;
 
   QualType result;
 
@@ -4197,22 +4179,22 @@ QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
   // TODO: if we ever care about optimizing VLAs, there are no-op
   // optimizations available here.
   case Type::Pointer:
-    result = getPointerType(getVariableArrayDecayedType(
-                              cast<PointerType>(ty)->getPointeeType()));
+    result = getPointerType(
+        getVariableArrayDecayedType(cast<PointerType>(ty)->getPointeeType()));
     break;
 
   case Type::LValueReference: {
     const auto *lv = cast<LValueReferenceType>(ty);
     result = getLValueReferenceType(
-                 getVariableArrayDecayedType(lv->getPointeeType()),
-                                    lv->isSpelledAsLValue());
+        getVariableArrayDecayedType(lv->getPointeeType()),
+        lv->isSpelledAsLValue());
     break;
   }
 
   case Type::RValueReference: {
     const auto *lv = cast<RValueReferenceType>(ty);
     result = getRValueReferenceType(
-                 getVariableArrayDecayedType(lv->getPointeeType()));
+        getVariableArrayDecayedType(lv->getPointeeType()));
     break;
   }
 
@@ -4225,22 +4207,18 @@ QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
   case Type::ConstantArray: {
     const auto *cat = cast<ConstantArrayType>(ty);
     result = getConstantArrayType(
-                 getVariableArrayDecayedType(cat->getElementType()),
-                                  cat->getSize(),
-                                  cat->getSizeExpr(),
-                                  cat->getSizeModifier(),
-                                  cat->getIndexTypeCVRQualifiers());
+        getVariableArrayDecayedType(cat->getElementType()), cat->getSize(),
+        cat->getSizeExpr(), cat->getSizeModifier(),
+        cat->getIndexTypeCVRQualifiers());
     break;
   }
 
   case Type::DependentSizedArray: {
     const auto *dat = cast<DependentSizedArrayType>(ty);
     result = getDependentSizedArrayType(
-                 getVariableArrayDecayedType(dat->getElementType()),
-                                        dat->getSizeExpr(),
-                                        dat->getSizeModifier(),
-                                        dat->getIndexTypeCVRQualifiers(),
-                                        dat->getBracketsRange());
+        getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
+        dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers(),
+        dat->getBracketsRange());
     break;
   }
 
@@ -4318,7 +4296,7 @@ QualType ASTContext::getDependentSizedArrayType(QualType elementType,
 
   // Look for an existing type with these properties.
   DependentSizedArrayType *canonTy =
-    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
+      DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
 
   // Dependently-sized array types that do not have a specified number
   // of elements will have their sizes deduced from a dependent
@@ -4345,8 +4323,8 @@ QualType ASTContext::getDependentSizedArrayType(QualType elementType,
   }
 
   // Apply qualifiers from the element type to the array.
-  QualType canon = getQualifiedType(QualType(canonTy,0),
-                                    canonElementType.Quals);
+  QualType canon =
+      getQualifiedType(QualType(canonTy, 0), canonElementType.Quals);
 
   // If we didn't need extra canonicalization for the element type or the size
   // expression, then just use that as our result.
@@ -4371,7 +4349,7 @@ QualType ASTContext::getIncompleteArrayType(QualType elementType,
 
   void *insertPos = nullptr;
   if (IncompleteArrayType *iat =
-       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
+          IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
     return QualType(iat, 0);
 
   // If the element type isn't canonical, this won't be a canonical type
@@ -4382,14 +4360,15 @@ QualType ASTContext::getIncompleteArrayType(QualType elementType,
   // FIXME: Check below should look for qualifiers behind sugar.
   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
     SplitQualType canonSplit = getCanonicalType(elementType).split();
-    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
-                                   ASM, elementTypeQuals);
+    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), ASM,
+                                   elementTypeQuals);
     canon = getQualifiedType(canon, canonSplit.Quals);
 
     // Get the new insert position for the node we care about.
     IncompleteArrayType *existing =
-      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
-    assert(!existing && "Shouldn't be in the map!"); (void) existing;
+        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
+    assert(!existing && "Shouldn't be in the map!");
+    (void)existing;
   }
 
   auto *newType = new (*this, alignof(IncompleteArrayType))
@@ -4554,7 +4533,8 @@ QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
 
     // Get the new insert position for the node we care about.
     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
   auto *New = new (*this, alignof(VectorType))
       VectorType(vecType, NumElts, Canonical, VecKind);
@@ -4627,7 +4607,8 @@ QualType ASTContext::getExtVectorType(QualType vecType,
 
     // Get the new insert position for the node we care about.
     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
   auto *New = new (*this, alignof(ExtVectorType))
       ExtVectorType(vecType, NumElts, Canonical);
@@ -4637,16 +4618,15 @@ QualType ASTContext::getExtVectorType(QualType vecType,
 }
 
 QualType
-ASTContext::getDependentSizedExtVectorType(QualType vecType,
-                                           Expr *SizeExpr,
+ASTContext::getDependentSizedExtVectorType(QualType vecType, Expr *SizeExpr,
                                            SourceLocation AttrLoc) const {
   llvm::FoldingSetNodeID ID;
   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
                                        SizeExpr);
 
   void *InsertPos = nullptr;
-  DependentSizedExtVectorType *Canon
-    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
+  DependentSizedExtVectorType *Canon =
+      DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
   DependentSizedExtVectorType *New;
   if (Canon) {
     // We already have a canonical version of this array type; use it as
@@ -4660,8 +4640,8 @@ ASTContext::getDependentSizedExtVectorType(QualType vecType,
       New = new (*this, alignof(DependentSizedExtVectorType))
           DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
 
-      DependentSizedExtVectorType *CanonCheck
-        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
+      DependentSizedExtVectorType *CanonCheck =
+          DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
       (void)CanonCheck;
       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
@@ -4750,9 +4730,8 @@ QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
   return QualType(New, 0);
 }
 
-QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
-                                                  Expr *AddrSpaceExpr,
-                                                  SourceLocation AttrLoc) const {
+QualType ASTContext::getDependentAddressSpaceType(
+    QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const {
   assert(AddrSpaceExpr->isInstantiationDependent());
 
   QualType canonPointeeType = getCanonicalType(PointeeType);
@@ -4763,7 +4742,7 @@ QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
                                      AddrSpaceExpr);
 
   DependentAddressSpaceType *canonTy =
-    DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
+      DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
 
   if (!canonTy) {
     canonTy = new (*this, alignof(DependentAddressSpaceType))
@@ -4799,7 +4778,7 @@ ASTContext::getFunctionNoProtoType(QualType ResultTy,
   // functionality creates a function without a prototype regardless of
   // language mode (so it makes them even in C++). Once the rewriter has been
   // fixed, this assertion can be enabled again.
-  //assert(!LangOpts.requiresStrictPrototypes() &&
+  // assert(!LangOpts.requiresStrictPrototypes() &&
   //       "strict prototypes are disabled");
 
   // Unique functions, to guarantee there is only one function of a particular
@@ -4809,18 +4788,19 @@ ASTContext::getFunctionNoProtoType(QualType ResultTy,
 
   void *InsertPos = nullptr;
   if (FunctionNoProtoType *FT =
-        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
+          FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(FT, 0);
 
   QualType Canonical;
   if (!isCanonicalResultType(ResultTy)) {
     Canonical =
-      getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
+        getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
 
     // Get the new insert position for the node we care about.
     FunctionNoProtoType *NewIP =
-      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
 
   auto *New = new (*this, alignof(FunctionNoProtoType))
@@ -4839,7 +4819,7 @@ ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
     Qualifiers Qs = CanResultType.getQualifiers();
     Qs.removeObjCLifetime();
     return CanQualType::CreateUnsafe(
-             getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
+        getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
   }
 
   return CanResultType;
@@ -4895,7 +4875,7 @@ QualType ASTContext::getFunctionTypeInternal(
 
   void *InsertPos = nullptr;
   if (FunctionProtoType *FPT =
-        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
+          FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
     QualType Existing = QualType(FPT, 0);
 
     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
@@ -4946,11 +4926,15 @@ QualType ASTContext::getFunctionTypeInternal(
       // Exception spec is already OK.
     } else if (NoexceptInType) {
       switch (EPI.ExceptionSpec.Type) {
-      case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
+      case EST_Unparsed:
+      case EST_Unevaluated:
+      case EST_Uninstantiated:
         // We don't know yet. It shouldn't matter what we pick here; no-one
         // should ever look at this.
         [[fallthrough]];
-      case EST_None: case EST_MSAny: case EST_NoexceptFalse:
+      case EST_None:
+      case EST_MSAny:
+      case EST_NoexceptFalse:
         CanonicalEPI.ExceptionSpec.Type = EST_None;
         break;
 
@@ -4993,8 +4977,9 @@ QualType ASTContext::getFunctionTypeInternal(
 
     // Get the new insert position for the node we care about.
     FunctionProtoType *NewIP =
-      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
 
   // Compute the needed size to hold this FunctionProtoType and the
@@ -5098,7 +5083,8 @@ QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
 
 #ifndef NDEBUG
 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
-  if (!isa<CXXRecordDecl>(D)) return false;
+  if (!isa<CXXRecordDecl>(D))
+    return false;
   const auto *RD = cast<CXXRecordDecl>(D);
   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
     return true;
@@ -5220,7 +5206,8 @@ QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
 }
 
 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
-  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
+  if (Decl->TypeForDecl)
+    return QualType(Decl->TypeForDecl, 0);
 
   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
     if (PrevDecl->TypeForDecl)
@@ -5233,7 +5220,8 @@ QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
 }
 
 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
-  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
+  if (Decl->TypeForDecl)
+    return QualType(Decl->TypeForDecl, 0);
 
   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
     if (PrevDecl->TypeForDecl)
@@ -5363,12 +5351,13 @@ QualType ASTContext::getAttributedType(attr::Kind attrKind,
 
   void *insertPos = nullptr;
   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
-  if (type) return QualType(type, 0);
+  if (type)
+    return QualType(type, 0);
 
   assert(!attr || attr->getKind() == attrKind);
 
   QualType canon = getCanonicalType(equivalentType);
-	type = new (*this, alignof(AttributedType))
+  type = new (*this, alignof(AttributedType))
       AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
 
   Types.push_back(type);
@@ -5513,14 +5502,15 @@ ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
 /// Retrieve the template type parameter type for a template
 /// parameter or parameter pack with the given depth, index, and (optionally)
 /// name.
-QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
-                                             bool ParameterPack,
-                                             TemplateTypeParmDecl *TTPDecl) const {
+QualType
+ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
+                                    bool ParameterPack,
+                                    TemplateTypeParmDecl *TTPDecl) const {
   llvm::FoldingSetNodeID ID;
   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
   void *InsertPos = nullptr;
-  TemplateTypeParmType *TypeParm
-    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
+  TemplateTypeParmType *TypeParm =
+      TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
 
   if (TypeParm)
     return QualType(TypeParm, 0);
@@ -5530,8 +5520,8 @@ QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
     TypeParm = new (*this, alignof(TemplateTypeParmType))
         TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
 
-    TemplateTypeParmType *TypeCheck
-      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
+    TemplateTypeParmType *TypeCheck =
+        TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
     assert(!TypeCheck && "Template type parameter canonical type broken");
     (void)TypeCheck;
   } else
@@ -5544,11 +5534,9 @@ QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
   return QualType(TypeParm, 0);
 }
 
-TypeSourceInfo *
-ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
-                                              SourceLocation NameLoc,
-                                        const TemplateArgumentListInfo &Args,
-                                              QualType Underlying) const {
+TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
+    TemplateName Name, SourceLocation NameLoc,
+    const TemplateArgumentListInfo &Args, QualType Underlying) const {
   assert(!Name.getAsDependentTemplateName() &&
          "No dependent template names here!");
   QualType TST =
@@ -5619,9 +5607,8 @@ ASTContext::getTemplateSpecializationType(TemplateName Template,
                            sizeof(TemplateArgument) * Args.size() +
                            (IsTypeAlias ? sizeof(QualType) : 0),
                        alignof(TemplateSpecializationType));
-  auto *Spec
-    = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
-                                         IsTypeAlias ? Underlying : QualType());
+  auto *Spec = new (Mem) TemplateSpecializationType(
+      Template, Args, CanonType, IsTypeAlias ? Underlying : QualType());
 
   Types.push_back(Spec);
   return QualType(Spec, 0);
@@ -5646,20 +5633,18 @@ QualType ASTContext::getCanonicalTemplateSpecializationType(
   // Determine whether this canonical template specialization type already
   // exists.
   llvm::FoldingSetNodeID ID;
-  TemplateSpecializationType::Profile(ID, CanonTemplate,
-                                      CanonArgs, *this);
+  TemplateSpecializationType::Profile(ID, CanonTemplate, CanonArgs, *this);
 
   void *InsertPos = nullptr;
-  TemplateSpecializationType *Spec
-    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
+  TemplateSpecializationType *Spec =
+      TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
 
   if (!Spec) {
     // Allocate a new canonical template specialization type.
     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
                           sizeof(TemplateArgument) * CanonArgs.size()),
                          alignof(TemplateSpecializationType));
-    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
-                                                CanonArgs,
+    Spec = new (Mem) TemplateSpecializationType(CanonTemplate, CanonArgs,
                                                 QualType(), QualType());
     Types.push_back(Spec);
     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
@@ -5700,8 +5685,7 @@ QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
   return QualType(T, 0);
 }
 
-QualType
-ASTContext::getParenType(QualType InnerType) const {
+QualType ASTContext::getParenType(QualType InnerType) const {
   llvm::FoldingSetNodeID ID;
   ParenType::Profile(ID, InnerType);
 
@@ -5751,8 +5735,7 @@ QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
   DependentNameType::Profile(ID, Keyword, NNS, Name);
 
   void *InsertPos = nullptr;
-  DependentNameType *T
-    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
+  DependentNameType *T = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
   if (T)
     return QualType(T, 0);
 
@@ -5773,22 +5756,19 @@ QualType ASTContext::getDependentTemplateSpecializationType(
   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
 }
 
-QualType
-ASTContext::getDependentTemplateSpecializationType(
-                                 ElaboratedTypeKeyword Keyword,
-                                 NestedNameSpecifier *NNS,
-                                 const IdentifierInfo *Name,
-                                 ArrayRef<TemplateArgument> Args) const {
+QualType ASTContext::getDependentTemplateSpecializationType(
+    ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
+    const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const {
   assert((!NNS || NNS->isDependent()) &&
          "nested-name-specifier must be dependent");
 
   llvm::FoldingSetNodeID ID;
-  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
-                                               Name, Args);
+  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, Name,
+                                               Args);
 
   void *InsertPos = nullptr;
-  DependentTemplateSpecializationType *T
-    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
+  DependentTemplateSpecializationType *T =
+      DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
   if (T)
     return QualType(T, 0);
 
@@ -5804,8 +5784,7 @@ ASTContext::getDependentTemplateSpecializationType(
 
   QualType Canon;
   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
-    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
-                                                   Name,
+    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, Name,
                                                    CanonArgs);
 
     // Find the insert position again.
@@ -5817,8 +5796,8 @@ ASTContext::getDependentTemplateSpecializationType(
   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
                         sizeof(TemplateArgument) * Args.size()),
                        alignof(DependentTemplateSpecializationType));
-  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
-                                                    Name, Args, Canon);
+  T = new (Mem)
+      DependentTemplateSpecializationType(Keyword, NNS, Name, Args, Canon);
   Types.push_back(T);
   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
   return QualType(T, 0);
@@ -5913,7 +5892,8 @@ static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
 }
 
 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
-  if (Protocols.empty()) return true;
+  if (Protocols.empty())
+    return true;
 
   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
     return false;
@@ -5940,18 +5920,17 @@ SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
 }
 
 QualType ASTContext::getObjCObjectType(QualType BaseType,
-                                       ObjCProtocolDecl * const *Protocols,
+                                       ObjCProtocolDecl *const *Protocols,
                                        unsigned NumProtocols) const {
   return getObjCObjectType(BaseType, {},
                            llvm::ArrayRef(Protocols, NumProtocols),
                            /*isKindOf=*/false);
 }
 
-QualType ASTContext::getObjCObjectType(
-           QualType baseType,
-           ArrayRef<QualType> typeArgs,
-           ArrayRef<ObjCProtocolDecl *> protocols,
-           bool isKindOf) const {
+QualType ASTContext::getObjCObjectType(QualType baseType,
+                                       ArrayRef<QualType> typeArgs,
+                                       ArrayRef<ObjCProtocolDecl *> protocols,
+                                       bool isKindOf) const {
   // If the base type is an interface and there aren't any protocols or
   // type arguments to add, then the interface type will do just fine.
   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
@@ -5995,7 +5974,7 @@ QualType ASTContext::getObjCObjectType(
     }
 
     ArrayRef<ObjCProtocolDecl *> canonProtocols;
-    SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
+    SmallVector<ObjCProtocolDecl *, 8> canonProtocolsVec;
     if (!protocolsSorted) {
       canonProtocolsVec.append(protocols.begin(), protocols.end());
       SortAndUniqueProtocols(canonProtocolsVec);
@@ -6015,9 +5994,8 @@ QualType ASTContext::getObjCObjectType(
   size += typeArgs.size() * sizeof(QualType);
   size += protocols.size() * sizeof(ObjCProtocolDecl *);
   void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
-  auto *T =
-    new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
-                                 isKindOf);
+  auto *T = new (mem)
+      ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, isKindOf);
 
   Types.push_back(T);
   ObjCObjectTypes.InsertNode(T, InsertPos);
@@ -6027,10 +6005,9 @@ QualType ASTContext::getObjCObjectType(
 /// Apply Objective-C protocol qualifiers to the given type.
 /// If this is for the canonical type of a type parameter, we can apply
 /// protocol qualifiers on the ObjCObjectPointerType.
-QualType
-ASTContext::applyObjCProtocolQualifiers(QualType type,
-                  ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
-                  bool allowOnPointerType) const {
+QualType ASTContext::applyObjCProtocolQualifiers(
+    QualType type, ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
+    bool allowOnPointerType) const {
   hasError = false;
 
   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
@@ -6043,29 +6020,24 @@ ASTContext::applyObjCProtocolQualifiers(QualType type,
             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
       const ObjCObjectType *objT = objPtr->getObjectType();
       // Merge protocol lists and construct ObjCObjectType.
-      SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
-      protocolsVec.append(objT->qual_begin(),
-                          objT->qual_end());
+      SmallVector<ObjCProtocolDecl *, 8> protocolsVec;
+      protocolsVec.append(objT->qual_begin(), objT->qual_end());
       protocolsVec.append(protocols.begin(), protocols.end());
       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
-      type = getObjCObjectType(
-             objT->getBaseType(),
-             objT->getTypeArgsAsWritten(),
-             protocols,
-             objT->isKindOfTypeAsWritten());
+      type =
+          getObjCObjectType(objT->getBaseType(), objT->getTypeArgsAsWritten(),
+                            protocols, objT->isKindOfTypeAsWritten());
       return getObjCObjectPointerType(type);
     }
   }
 
   // Apply protocol qualifiers to ObjCObjectType.
-  if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
+  if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())) {
     // FIXME: Check for protocols to which the class type is already
     // known to conform.
 
-    return getObjCObjectType(objT->getBaseType(),
-                             objT->getTypeArgsAsWritten(),
-                             protocols,
-                             objT->isKindOfTypeAsWritten());
+    return getObjCObjectType(objT->getBaseType(), objT->getTypeArgsAsWritten(),
+                             protocols, objT->isKindOfTypeAsWritten());
   }
 
   // If the canonical type is ObjCObjectType, ...
@@ -6082,7 +6054,7 @@ ASTContext::applyObjCProtocolQualifiers(QualType type,
   if (type->isObjCIdType()) {
     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
-                                 objPtr->isKindOfType());
+                             objPtr->isKindOfType());
     return getObjCObjectPointerType(type);
   }
 
@@ -6090,7 +6062,7 @@ ASTContext::applyObjCProtocolQualifiers(QualType type,
   if (type->isObjCClassType()) {
     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
-                                 objPtr->isKindOfType());
+                             objPtr->isKindOfType());
     return getObjCObjectPointerType(type);
   }
 
@@ -6106,7 +6078,7 @@ ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
   void *InsertPos = nullptr;
   if (ObjCTypeParamType *TypeParam =
-      ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
+          ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(TypeParam, 0);
 
   // We canonicalize to the underlying type.
@@ -6162,8 +6134,8 @@ bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
 /// of protocols.
-bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
-                                                ObjCInterfaceDecl *IDecl) {
+bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(
+    QualType QT, ObjCInterfaceDecl *IDecl) {
   if (!QT->isObjCQualifiedIdType())
     return false;
   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
@@ -6214,7 +6186,7 @@ QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
 
   void *InsertPos = nullptr;
   if (ObjCObjectPointerType *QT =
-              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
+          ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(QT, 0);
 
   // Find the canonical object type.
@@ -6229,8 +6201,7 @@ QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
   // No match.
   void *Mem =
       Allocate(sizeof(ObjCObjectPointerType), alignof(ObjCObjectPointerType));
-  auto *QType =
-    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
+  auto *QType = new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
 
   Types.push_back(QType);
   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
@@ -6349,8 +6320,8 @@ QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
     DependentDecltypeType::Profile(ID, *this, e);
 
     void *InsertPos = nullptr;
-    DependentDecltypeType *Canon
-      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
+    DependentDecltypeType *Canon =
+        DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
     if (!Canon) {
       // Build a new, canonical decltype(expr) type.
       Canon = new (*this, alignof(DependentDecltypeType))
@@ -6404,10 +6375,9 @@ QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
 
 /// getUnaryTransformationType - We don't unique these, since the memory
 /// savings are minimal and these are rare.
-QualType ASTContext::getUnaryTransformType(QualType BaseType,
-                                           QualType UnderlyingType,
-                                           UnaryTransformType::UTTKind Kind)
-    const {
+QualType
+ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
+                                  UnaryTransformType::UTTKind Kind) const {
   UnaryTransformType *ut = nullptr;
 
   if (BaseType->isDependentType()) {
@@ -6416,8 +6386,8 @@ QualType ASTContext::getUnaryTransformType(QualType BaseType,
     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
 
     void *InsertPos = nullptr;
-    DependentUnaryTransformType *Canon
-      = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
+    DependentUnaryTransformType *Canon =
+        DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
 
     if (!Canon) {
       // Build a new, canonical __underlying_type(type) type.
@@ -6583,7 +6553,8 @@ QualType ASTContext::getAtomicType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!");
+    (void)NewIP;
   }
   auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
   Types.push_back(New);
@@ -6616,7 +6587,7 @@ QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
   assert(Decl);
   // FIXME: What is the design on getTagDeclType when it requires casting
   // away const?  mutable?
-  return getTypeDeclType(const_cast<TagDecl*>(Decl));
+  return getTypeDeclType(const_cast<TagDecl *>(Decl));
 }
 
 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
@@ -6697,7 +6668,7 @@ CanQualType ASTContext::getCanonicalParamType(QualType T) const {
   if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
     Result = getArrayParameterType(QualType(Ty, 0));
   } else if (isa<ArrayType>(Ty)) {
-    Result = getArrayDecayedType(QualType(Ty,0));
+    Result = getArrayDecayedType(QualType(Ty, 0));
   } else if (isa<FunctionType>(Ty)) {
     Result = getPointerType(QualType(Ty, 0));
   } else {
@@ -6750,17 +6721,14 @@ QualType ASTContext::getUnqualifiedArrayType(QualType type,
   }
 
   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
-    return getVariableArrayType(unqualElementType,
-                                VAT->getSizeExpr(),
-                                VAT->getSizeModifier(),
-                                VAT->getIndexTypeCVRQualifiers(),
-                                VAT->getBracketsRange());
+    return getVariableArrayType(
+        unqualElementType, VAT->getSizeExpr(), VAT->getSizeModifier(),
+        VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
   }
 
   const auto *DSAT = cast<DependentSizedArrayType>(AT);
   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
-                                    DSAT->getSizeModifier(), 0,
-                                    SourceRange());
+                                    DSAT->getSizeModifier(), 0, SourceRange());
 }
 
 /// Attempt to unwrap two types that may both be array types with the same bound
@@ -6930,15 +6898,14 @@ ASTContext::getNameForTemplate(TemplateName Name,
   }
 
   case TemplateName::SubstTemplateTemplateParm: {
-    SubstTemplateTemplateParmStorage *subst
-      = Name.getAsSubstTemplateTemplateParm();
-    return DeclarationNameInfo(subst->getParameter()->getDeclName(),
-                               NameLoc);
+    SubstTemplateTemplateParmStorage *subst =
+        Name.getAsSubstTemplateTemplateParm();
+    return DeclarationNameInfo(subst->getParameter()->getDeclName(), NameLoc);
   }
 
   case TemplateName::SubstTemplateTemplateParmPack: {
-    SubstTemplateTemplateParmPackStorage *subst
-      = Name.getAsSubstTemplateTemplateParmPack();
+    SubstTemplateTemplateParmPackStorage *subst =
+        Name.getAsSubstTemplateTemplateParmPack();
     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
                                NameLoc);
   }
@@ -6982,7 +6949,7 @@ TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
   switch (Name.getKind()) {
   case TemplateName::Template: {
     TemplateDecl *Template = Name.getAsTemplateDecl();
-    if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
+    if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
       Template = getCanonicalTemplateTemplateParmDecl(TTP);
 
     // The canonical template name is the canonical template declaration.
@@ -7527,54 +7494,54 @@ bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
 TemplateArgument
 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
   switch (Arg.getKind()) {
-    case TemplateArgument::Null:
-      return Arg;
-
-    case TemplateArgument::Expression:
-      return Arg;
-
-    case TemplateArgument::Declaration: {
-      auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
-      return TemplateArgument(D, getCanonicalType(Arg.getParamTypeForDecl()),
-                              Arg.getIsDefaulted());
-    }
-
-    case TemplateArgument::NullPtr:
-      return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
-                              /*isNullPtr*/ true, Arg.getIsDefaulted());
+  case TemplateArgument::Null:
+    return Arg;
 
-    case TemplateArgument::Template:
-      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()),
-                              Arg.getIsDefaulted());
+  case TemplateArgument::Expression:
+    return Arg;
 
-    case TemplateArgument::TemplateExpansion:
-      return TemplateArgument(
-          getCanonicalTemplateName(Arg.getAsTemplateOrTemplatePattern()),
-          Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
-
-    case TemplateArgument::Integral:
-      return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
+  case TemplateArgument::Declaration: {
+    auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
+    return TemplateArgument(D, getCanonicalType(Arg.getParamTypeForDecl()),
+                            Arg.getIsDefaulted());
+  }
 
-    case TemplateArgument::StructuralValue:
-      return TemplateArgument(*this,
-                              getCanonicalType(Arg.getStructuralValueType()),
-                              Arg.getAsStructuralValue(), Arg.getIsDefaulted());
+  case TemplateArgument::NullPtr:
+    return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
+                            /*isNullPtr*/ true, Arg.getIsDefaulted());
 
-    case TemplateArgument::Type:
-      return TemplateArgument(getCanonicalType(Arg.getAsType()),
-                              /*isNullPtr*/ false, Arg.getIsDefaulted());
+  case TemplateArgument::Template:
+    return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()),
+                            Arg.getIsDefaulted());
 
-    case TemplateArgument::Pack: {
-      bool AnyNonCanonArgs = false;
-      auto CanonArgs = ::getCanonicalTemplateArguments(
-          *this, Arg.pack_elements(), AnyNonCanonArgs);
-      if (!AnyNonCanonArgs)
-        return Arg;
-      auto NewArg = TemplateArgument::CreatePackCopy(
-          const_cast<ASTContext &>(*this), CanonArgs);
-      NewArg.setIsDefaulted(Arg.getIsDefaulted());
-      return NewArg;
-    }
+  case TemplateArgument::TemplateExpansion:
+    return TemplateArgument(
+        getCanonicalTemplateName(Arg.getAsTemplateOrTemplatePattern()),
+        Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
+
+  case TemplateArgument::Integral:
+    return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
+
+  case TemplateArgument::StructuralValue:
+    return TemplateArgument(*this,
+                            getCanonicalType(Arg.getStructuralValueType()),
+                            Arg.getAsStructuralValue(), Arg.getIsDefaulted());
+
+  case TemplateArgument::Type:
+    return TemplateArgument(getCanonicalType(Arg.getAsType()),
+                            /*isNullPtr*/ false, Arg.getIsDefaulted());
+
+  case TemplateArgument::Pack: {
+    bool AnyNonCanonArgs = false;
+    auto CanonArgs = ::getCanonicalTemplateArguments(*this, Arg.pack_elements(),
+                                                     AnyNonCanonArgs);
+    if (!AnyNonCanonArgs)
+      return Arg;
+    auto NewArg = TemplateArgument::CreatePackCopy(
+        const_cast<ASTContext &>(*this), CanonArgs);
+    NewArg.setIsDefaulted(Arg.getIsDefaulted());
+    return NewArg;
+  }
   }
 
   // Silence GCC warning
@@ -7589,9 +7556,9 @@ ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
   switch (NNS->getKind()) {
   case NestedNameSpecifier::Identifier:
     // Canonicalize the prefix but keep the identifier the same.
-    return NestedNameSpecifier::Create(*this,
-                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
-                                       NNS->getAsIdentifier());
+    return NestedNameSpecifier::Create(
+        *this, getCanonicalNestedNameSpecifier(NNS->getPrefix()),
+        NNS->getAsIdentifier());
 
   case NestedNameSpecifier::Namespace:
     // A namespace is canonical; build a nested-name-specifier with
@@ -7671,29 +7638,22 @@ const ArrayType *ASTContext::getAsArrayType(QualType T) const {
   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
 
   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
-    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
-                                                CAT->getSizeExpr(),
-                                                CAT->getSizeModifier(),
-                                           CAT->getIndexTypeCVRQualifiers()));
+    return cast<ArrayType>(getConstantArrayType(
+        NewEltTy, CAT->getSize(), CAT->getSizeExpr(), CAT->getSizeModifier(),
+        CAT->getIndexTypeCVRQualifiers()));
   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
-    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
-                                                  IAT->getSizeModifier(),
-                                           IAT->getIndexTypeCVRQualifiers()));
+    return cast<ArrayType>(getIncompleteArrayType(
+        NewEltTy, IAT->getSizeModifier(), IAT->getIndexTypeCVRQualifiers()));
 
   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
-    return cast<ArrayType>(
-                     getDependentSizedArrayType(NewEltTy,
-                                                DSAT->getSizeExpr(),
-                                                DSAT->getSizeModifier(),
-                                              DSAT->getIndexTypeCVRQualifiers(),
-                                                DSAT->getBracketsRange()));
+    return cast<ArrayType>(getDependentSizedArrayType(
+        NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
+        DSAT->getIndexTypeCVRQualifiers(), DSAT->getBracketsRange()));
 
   const auto *VAT = cast<VariableArrayType>(ATy);
-  return cast<ArrayType>(getVariableArrayType(NewEltTy,
-                                              VAT->getSizeExpr(),
-                                              VAT->getSizeModifier(),
-                                              VAT->getIndexTypeCVRQualifiers(),
-                                              VAT->getBracketsRange()));
+  return cast<ArrayType>(getVariableArrayType(
+      NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
+      VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()));
 }
 
 QualType ASTContext::getAdjustedParameterType(QualType T) const {
@@ -7740,8 +7700,8 @@ QualType ASTContext::getArrayDecayedType(QualType Ty) const {
   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
 
   // int x[restrict 4] ->  int *restrict
-  QualType Result = getQualifiedType(PtrTy,
-                                     PrettyArrayType->getIndexTypeQualifiers());
+  QualType Result =
+      getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
 
   // int x[_Nullable] -> int * _Nullable
   if (auto Nullability = Ty->getNullability()) {
@@ -7760,7 +7720,8 @@ QualType ASTContext::getBaseElementType(QualType type) const {
   while (true) {
     SplitQualType split = type.getSplitDesugaredType();
     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
-    if (!array) break;
+    if (!array)
+      break;
 
     type = array->getElementType();
     qs.addConsistentQualifiers(split.Quals);
@@ -7771,12 +7732,12 @@ QualType ASTContext::getBaseElementType(QualType type) const {
 
 /// getConstantArrayElementCount - Returns number of constant array elements.
 uint64_t
-ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
+ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
   uint64_t ElementCount = 1;
   do {
     ElementCount *= CA->getZExtSize();
     CA = dyn_cast_or_null<ConstantArrayType>(
-      CA->getElementType()->getAsArrayTypeUnsafe());
+        CA->getElementType()->getAsArrayTypeUnsafe());
   } while (CA);
   return ElementCount;
 }
@@ -7803,15 +7764,24 @@ static FloatingRank getFloatingRank(QualType T) {
     return getFloatingRank(CT->getElementType());
 
   switch (T->castAs<BuiltinType>()->getKind()) {
-  default: llvm_unreachable("getFloatingRank(): not a floating type");
-  case BuiltinType::Float16:    return Float16Rank;
-  case BuiltinType::Half:       return HalfRank;
-  case BuiltinType::Float:      return FloatRank;
-  case BuiltinType::Double:     return DoubleRank;
-  case BuiltinType::LongDouble: return LongDoubleRank;
-  case BuiltinType::Float128:   return Float128Rank;
-  case BuiltinType::BFloat16:   return BFloat16Rank;
-  case BuiltinType::Ibm128:     return Ibm128Rank;
+  default:
+    llvm_unreachable("getFloatingRank(): not a floating type");
+  case BuiltinType::Float16:
+    return Float16Rank;
+  case BuiltinType::Half:
+    return HalfRank;
+  case BuiltinType::Float:
+    return FloatRank;
+  case BuiltinType::Double:
+    return DoubleRank;
+  case BuiltinType::LongDouble:
+    return LongDoubleRank;
+  case BuiltinType::Float128:
+    return Float128Rank;
+  case BuiltinType::BFloat16:
+    return BFloat16Rank;
+  case BuiltinType::Ibm128:
+    return Ibm128Rank;
   }
 }
 
@@ -7848,7 +7818,8 @@ unsigned ASTContext::getIntegerRank(const Type *T) const {
     return 0 + (EIT->getNumBits() << 3);
 
   switch (cast<BuiltinType>(T)->getKind()) {
-  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
+  default:
+    llvm_unreachable("getIntegerRank(): not a built-in integer");
   case BuiltinType::Bool:
     return 1 + (getIntWidth(BoolTy) << 3);
   case BuiltinType::Char_S:
@@ -7977,8 +7948,9 @@ QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
         BT->getKind() == BuiltinType::Char32) {
       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
       uint64_t FromSize = getTypeSize(BT);
-      QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
-                                  LongLongTy, UnsignedLongLongTy };
+      QualType PromoteTypes[] = {IntTy,      UnsignedIntTy,
+                                 LongTy,     UnsignedLongTy,
+                                 LongLongTy, UnsignedLongLongTy};
       for (const auto &PT : PromoteTypes) {
         uint64_t ToSize = getTypeSize(PT);
         if (FromSize < ToSize ||
@@ -7998,6 +7970,22 @@ QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
 }
 
+/// getUnwidenedIntegerType - If \p E is a widened promoted integer, get its
+/// base (unpromoted) type.
+std::optional<QualType>
+ASTContext::getUnwidenedIntegerType(const Expr *E) const {
+  const Expr *Base = E->IgnoreImpCasts();
+  if (E == Base)
+    return std::nullopt;
+
+  QualType BaseTy = Base->getType();
+  if (!isPromotableIntegerType(BaseTy) ||
+      getTypeSize(BaseTy) >= getTypeSize(E->getType()))
+    return std::nullopt;
+
+  return BaseTy;
+}
+
 /// Recurses in pointer/array types until it finds an objc retainable
 /// type and returns its ownership.
 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
@@ -8038,7 +8026,8 @@ int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
   if (const auto *ET = dyn_cast<EnumType>(RHSC))
     RHSC = getIntegerTypeForEnum(ET);
 
-  if (LHSC == RHSC) return 0;
+  if (LHSC == RHSC)
+    return 0;
 
   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
@@ -8046,8 +8035,9 @@ int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
   unsigned LHSRank = getIntegerRank(LHSC);
   unsigned RHSRank = getIntegerRank(RHSC);
 
-  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
-    if (LHSRank == RHSRank) return 0;
+  if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
+    if (LHSRank == RHSRank)
+      return 0;
     return LHSRank > RHSRank ? 1 : -1;
   }
 
@@ -8120,29 +8110,28 @@ TypedefDecl *ASTContext::getCFConstantStringDecl() const {
   const auto CFRuntime = getLangOpts().CFRuntime;
   if (static_cast<unsigned>(CFRuntime) <
       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
-    Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
-    Fields[Count++] = { IntTy, "flags" };
-    Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
-    Fields[Count++] = { LongTy, "length" };
+    Fields[Count++] = {getPointerType(IntTy.withConst()), "isa"};
+    Fields[Count++] = {IntTy, "flags"};
+    Fields[Count++] = {getPointerType(CharTy.withConst()), "str"};
+    Fields[Count++] = {LongTy, "length"};
   } else {
-    Fields[Count++] = { getUIntPtrType(), "_cfisa" };
-    Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
-    Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
-    Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
+    Fields[Count++] = {getUIntPtrType(), "_cfisa"};
+    Fields[Count++] = {getUIntPtrType(), "_swift_rc"};
+    Fields[Count++] = {getFromTargetType(Target->getUInt64Type()), "_swift_rc"};
+    Fields[Count++] = {getPointerType(CharTy.withConst()), "_ptr"};
     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
-      Fields[Count++] = { IntTy, "_ptr" };
+      Fields[Count++] = {IntTy, "_ptr"};
     else
-      Fields[Count++] = { getUIntPtrType(), "_ptr" };
+      Fields[Count++] = {getUIntPtrType(), "_ptr"};
   }
 
   // Create fields
   for (unsigned i = 0; i < Count; ++i) {
-    FieldDecl *Field =
-        FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
-                          SourceLocation(), &Idents.get(Fields[i].Name),
-                          Fields[i].Type, /*TInfo=*/nullptr,
-                          /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(
+        *this, CFConstantStringTagDecl, SourceLocation(), SourceLocation(),
+        &Idents.get(Fields[i].Name), Fields[i].Type, /*TInfo=*/nullptr,
+        /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
     Field->setAccess(AS_public);
     CFConstantStringTagDecl->addDecl(Field);
   }
@@ -8195,14 +8184,11 @@ QualType ASTContext::getBlockDescriptorType() const {
   RD->startDefinition();
 
   QualType FieldTypes[] = {
-    UnsignedLongTy,
-    UnsignedLongTy,
+      UnsignedLongTy,
+      UnsignedLongTy,
   };
 
-  static const char *const FieldNames[] = {
-    "reserved",
-    "Size"
-  };
+  static const char *const FieldNames[] = {"reserved", "Size"};
 
   for (size_t i = 0; i < 2; ++i) {
     FieldDecl *Field = FieldDecl::Create(
@@ -8229,19 +8215,12 @@ QualType ASTContext::getBlockDescriptorExtendedType() const {
   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
   RD->startDefinition();
 
-  QualType FieldTypes[] = {
-    UnsignedLongTy,
-    UnsignedLongTy,
-    getPointerType(VoidPtrTy),
-    getPointerType(VoidPtrTy)
-  };
+  QualType FieldTypes[] = {UnsignedLongTy, UnsignedLongTy,
+                           getPointerType(VoidPtrTy),
+                           getPointerType(VoidPtrTy)};
 
-  static const char *const FieldNames[] = {
-    "reserved",
-    "Size",
-    "CopyFuncPtr",
-    "DestroyFuncPtr"
-  };
+  static const char *const FieldNames[] = {"reserved", "Size", "CopyFuncPtr",
+                                           "DestroyFuncPtr"};
 
   for (size_t i = 0; i < 4; ++i) {
     FieldDecl *Field = FieldDecl::Create(
@@ -8302,11 +8281,11 @@ LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
 /// requires copy/dispose. Note that this must match the logic
 /// in buildByrefHelpers.
-bool ASTContext::BlockRequiresCopying(QualType Ty,
-                                      const VarDecl *D) {
+bool ASTContext::BlockRequiresCopying(QualType Ty, const VarDecl *D) {
   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
-    if (!copyExpr && record->hasTrivialDestructor()) return false;
+    if (!copyExpr && record->hasTrivialDestructor())
+      return false;
 
     return true;
   }
@@ -8316,25 +8295,27 @@ bool ASTContext::BlockRequiresCopying(QualType Ty,
   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
     return true;
 
-  if (!Ty->isObjCRetainableType()) return false;
+  if (!Ty->isObjCRetainableType())
+    return false;
 
   Qualifiers qs = Ty.getQualifiers();
 
   // If we have lifetime, that dominates.
   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
     switch (lifetime) {
-      case Qualifiers::OCL_None: llvm_unreachable("impossible");
+    case Qualifiers::OCL_None:
+      llvm_unreachable("impossible");
 
-      // These are just bits as far as the runtime is concerned.
-      case Qualifiers::OCL_ExplicitNone:
-      case Qualifiers::OCL_Autoreleasing:
-        return false;
+    // These are just bits as far as the runtime is concerned.
+    case Qualifiers::OCL_ExplicitNone:
+    case Qualifiers::OCL_Autoreleasing:
+      return false;
 
-      // These cases should have been taken care of when checking the type's
-      // non-triviality.
-      case Qualifiers::OCL_Weak:
-      case Qualifiers::OCL_Strong:
-        llvm_unreachable("impossible");
+    // These cases should have been taken care of when checking the type's
+    // non-triviality.
+    case Qualifiers::OCL_Weak:
+    case Qualifiers::OCL_Strong:
+      llvm_unreachable("impossible");
     }
     llvm_unreachable("fell out of lifetime switch!");
   }
@@ -8343,10 +8324,9 @@ bool ASTContext::BlockRequiresCopying(QualType Ty,
 }
 
 bool ASTContext::getByrefLifetime(QualType Ty,
-                              Qualifiers::ObjCLifetime &LifeTime,
-                              bool &HasByrefExtendedLayout) const {
-  if (!getLangOpts().ObjC ||
-      getLangOpts().getGC() != LangOptions::NonGC)
+                                  Qualifiers::ObjCLifetime &LifeTime,
+                                  bool &HasByrefExtendedLayout) const {
+  if (!getLangOpts().ObjC || getLangOpts().getGC() != LangOptions::NonGC)
     return false;
 
   HasByrefExtendedLayout = false;
@@ -8494,8 +8474,8 @@ std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
     } else if (PType->isFunctionType())
       PType = PVDecl->getType();
     if (getLangOpts().EncodeExtendedBlockSig)
-      getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
-                                      S, true /*Extended*/);
+      getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, S,
+                                        true /*Extended*/);
     else
       getObjCEncodingForType(PType, S);
     S += charUnitsToString(ParmOffset);
@@ -8548,7 +8528,7 @@ ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
 /// method parameter or return type. If Extended, include class names and
 /// block object types.
 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
-                                                   QualType T, std::string& S,
+                                                   QualType T, std::string &S,
                                                    bool Extended) const {
   // Encode type qualifier, 'in', 'inout', etc. for the parameter.
   getObjCEncodingForTypeQualifier(QT, S);
@@ -8579,7 +8559,8 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
   // their size.
   CharUnits ParmOffset = 2 * PtrSize;
   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
-       E = Decl->sel_param_end(); PI != E; ++PI) {
+                                            E = Decl->sel_param_end();
+       PI != E; ++PI) {
     QualType PType = (*PI)->getType();
     CharUnits sz = getObjCEncodingTypeSize(PType);
     if (sz.isZero())
@@ -8596,7 +8577,8 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
   // Argument types.
   ParmOffset = 2 * PtrSize;
   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
-       E = Decl->sel_param_end(); PI != E; ++PI) {
+                                            E = Decl->sel_param_end();
+       PI != E; ++PI) {
     const ParmVarDecl *PVDecl = *PI;
     QualType PType = PVDecl->getOriginalType();
     if (const auto *AT =
@@ -8607,8 +8589,8 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
         PType = PVDecl->getType();
     } else if (PType->isFunctionType())
       PType = PVDecl->getType();
-    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
-                                      PType, S, Extended);
+    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), PType, S,
+                                      Extended);
     S += charUnitsToString(ParmOffset);
     ParmOffset += getObjCEncodingTypeSize(PType);
   }
@@ -8616,10 +8598,8 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
   return S;
 }
 
-ObjCPropertyImplDecl *
-ASTContext::getObjCPropertyImplDeclForPropertyDecl(
-                                      const ObjCPropertyDecl *PD,
-                                      const Decl *Container) const {
+ObjCPropertyImplDecl *ASTContext::getObjCPropertyImplDeclForPropertyDecl(
+    const ObjCPropertyDecl *PD, const Decl *Container) const {
   if (!Container)
     return nullptr;
   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
@@ -8669,8 +8649,9 @@ ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
   ObjCPropertyImplDecl *SynthesizePID = nullptr;
 
   if (ObjCPropertyImplDecl *PropertyImpDecl =
-      getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
-    if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
+          getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
+    if (PropertyImpDecl->getPropertyImplementation() ==
+        ObjCPropertyImplDecl::Dynamic)
       Dynamic = true;
     else
       SynthesizePID = PropertyImpDecl;
@@ -8697,10 +8678,17 @@ ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
       S += ",W";
   } else {
     switch (PD->getSetterKind()) {
-    case ObjCPropertyDecl::Assign: break;
-    case ObjCPropertyDecl::Copy:   S += ",C"; break;
-    case ObjCPropertyDecl::Retain: S += ",&"; break;
-    case ObjCPropertyDecl::Weak:   S += ",W"; break;
+    case ObjCPropertyDecl::Assign:
+      break;
+    case ObjCPropertyDecl::Copy:
+      S += ",C";
+      break;
+    case ObjCPropertyDecl::Retain:
+      S += ",&";
+      break;
+    case ObjCPropertyDecl::Weak:
+      S += ",W";
+      break;
     }
   }
 
@@ -8736,19 +8724,19 @@ ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
 /// Another legacy compatibility encoding: 32-bit longs are encoded as
 /// 'l' or 'L' , but not always.  For typedefs, we need to use
 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
-void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
+void ASTContext::getLegacyIntegralTypeEncoding(QualType &PointeeTy) const {
   if (PointeeTy->getAs<TypedefType>()) {
     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
         PointeeTy = UnsignedIntTy;
-      else
-        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
-          PointeeTy = IntTy;
+      else if (BT->getKind() == BuiltinType::Long &&
+               getIntWidth(PointeeTy) == 32)
+        PointeeTy = IntTy;
     }
   }
 }
 
-void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
+void ASTContext::getObjCEncodingForType(QualType T, std::string &S,
                                         const FieldDecl *Field,
                                         QualType *NotEncodedT) const {
   // We follow the behavior of gcc, expanding structures which are
@@ -8764,7 +8752,7 @@ void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
 }
 
 void ASTContext::getObjCEncodingForPropertyType(QualType T,
-                                                std::string& S) const {
+                                                std::string &S) const {
   // Encode result type.
   // GCC has some special rules regarding encoding of properties which
   // closely resembles encoding of ivars.
@@ -8779,70 +8767,85 @@ void ASTContext::getObjCEncodingForPropertyType(QualType T,
 
 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
                                             const BuiltinType *BT) {
-    BuiltinType::Kind kind = BT->getKind();
-    switch (kind) {
-    case BuiltinType::Void:       return 'v';
-    case BuiltinType::Bool:       return 'B';
-    case BuiltinType::Char8:
-    case BuiltinType::Char_U:
-    case BuiltinType::UChar:      return 'C';
-    case BuiltinType::Char16:
-    case BuiltinType::UShort:     return 'S';
-    case BuiltinType::Char32:
-    case BuiltinType::UInt:       return 'I';
-    case BuiltinType::ULong:
-        return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
-    case BuiltinType::UInt128:    return 'T';
-    case BuiltinType::ULongLong:  return 'Q';
-    case BuiltinType::Char_S:
-    case BuiltinType::SChar:      return 'c';
-    case BuiltinType::Short:      return 's';
-    case BuiltinType::WChar_S:
-    case BuiltinType::WChar_U:
-    case BuiltinType::Int:        return 'i';
-    case BuiltinType::Long:
-      return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
-    case BuiltinType::LongLong:   return 'q';
-    case BuiltinType::Int128:     return 't';
-    case BuiltinType::Float:      return 'f';
-    case BuiltinType::Double:     return 'd';
-    case BuiltinType::LongDouble: return 'D';
-    case BuiltinType::NullPtr:    return '*'; // like char*
+  BuiltinType::Kind kind = BT->getKind();
+  switch (kind) {
+  case BuiltinType::Void:
+    return 'v';
+  case BuiltinType::Bool:
+    return 'B';
+  case BuiltinType::Char8:
+  case BuiltinType::Char_U:
+  case BuiltinType::UChar:
+    return 'C';
+  case BuiltinType::Char16:
+  case BuiltinType::UShort:
+    return 'S';
+  case BuiltinType::Char32:
+  case BuiltinType::UInt:
+    return 'I';
+  case BuiltinType::ULong:
+    return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
+  case BuiltinType::UInt128:
+    return 'T';
+  case BuiltinType::ULongLong:
+    return 'Q';
+  case BuiltinType::Char_S:
+  case BuiltinType::SChar:
+    return 'c';
+  case BuiltinType::Short:
+    return 's';
+  case BuiltinType::WChar_S:
+  case BuiltinType::WChar_U:
+  case BuiltinType::Int:
+    return 'i';
+  case BuiltinType::Long:
+    return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
+  case BuiltinType::LongLong:
+    return 'q';
+  case BuiltinType::Int128:
+    return 't';
+  case BuiltinType::Float:
+    return 'f';
+  case BuiltinType::Double:
+    return 'd';
+  case BuiltinType::LongDouble:
+    return 'D';
+  case BuiltinType::NullPtr:
+    return '*'; // like char*
 
-    case BuiltinType::BFloat16:
-    case BuiltinType::Float16:
-    case BuiltinType::Float128:
-    case BuiltinType::Ibm128:
-    case BuiltinType::Half:
-    case BuiltinType::ShortAccum:
-    case BuiltinType::Accum:
-    case BuiltinType::LongAccum:
-    case BuiltinType::UShortAccum:
-    case BuiltinType::UAccum:
-    case BuiltinType::ULongAccum:
-    case BuiltinType::ShortFract:
-    case BuiltinType::Fract:
-    case BuiltinType::LongFract:
-    case BuiltinType::UShortFract:
-    case BuiltinType::UFract:
-    case BuiltinType::ULongFract:
-    case BuiltinType::SatShortAccum:
-    case BuiltinType::SatAccum:
-    case BuiltinType::SatLongAccum:
-    case BuiltinType::SatUShortAccum:
-    case BuiltinType::SatUAccum:
-    case BuiltinType::SatULongAccum:
-    case BuiltinType::SatShortFract:
-    case BuiltinType::SatFract:
-    case BuiltinType::SatLongFract:
-    case BuiltinType::SatUShortFract:
-    case BuiltinType::SatUFract:
-    case BuiltinType::SatULongFract:
-      // FIXME: potentially need @encodes for these!
-      return ' ';
+  case BuiltinType::BFloat16:
+  case BuiltinType::Float16:
+  case BuiltinType::Float128:
+  case BuiltinType::Ibm128:
+  case BuiltinType::Half:
+  case BuiltinType::ShortAccum:
+  case BuiltinType::Accum:
+  case BuiltinType::LongAccum:
+  case BuiltinType::UShortAccum:
+  case BuiltinType::UAccum:
+  case BuiltinType::ULongAccum:
+  case BuiltinType::ShortFract:
+  case BuiltinType::Fract:
+  case BuiltinType::LongFract:
+  case BuiltinType::UShortFract:
+  case BuiltinType::UFract:
+  case BuiltinType::ULongFract:
+  case BuiltinType::SatShortAccum:
+  case BuiltinType::SatAccum:
+  case BuiltinType::SatLongAccum:
+  case BuiltinType::SatUShortAccum:
+  case BuiltinType::SatUAccum:
+  case BuiltinType::SatULongAccum:
+  case BuiltinType::SatShortFract:
+  case BuiltinType::SatFract:
+  case BuiltinType::SatLongFract:
+  case BuiltinType::SatUShortFract:
+  case BuiltinType::SatUFract:
+  case BuiltinType::SatULongFract:
+    // FIXME: potentially need @encodes for these!
+    return ' ';
 
-#define SVE_TYPE(Name, Id, SingletonId) \
-    case BuiltinType::Id:
+#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
 #include "clang/Basic/AArch64SVEACLETypes.def"
 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
 #include "clang/Basic/RISCVVTypes.def"
@@ -8850,44 +8853,41 @@ static char getObjCEncodingForPrimitiveType(const ASTContext *C,
 #include "clang/Basic/WebAssemblyReferenceTypes.def"
 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
 #include "clang/Basic/AMDGPUTypes.def"
-      {
-        DiagnosticsEngine &Diags = C->getDiagnostics();
-        unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
-                                                "cannot yet @encode type %0");
-        Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
-        return ' ';
-      }
+    {
+      DiagnosticsEngine &Diags = C->getDiagnostics();
+      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+                                              "cannot yet @encode type %0");
+      Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
+      return ' ';
+    }
 
-    case BuiltinType::ObjCId:
-    case BuiltinType::ObjCClass:
-    case BuiltinType::ObjCSel:
-      llvm_unreachable("@encoding ObjC primitive type");
+  case BuiltinType::ObjCId:
+  case BuiltinType::ObjCClass:
+  case BuiltinType::ObjCSel:
+    llvm_unreachable("@encoding ObjC primitive type");
 
     // OpenCL and placeholder types don't need @encodings.
-#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
-    case BuiltinType::Id:
+#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
+  case BuiltinType::Id:
 #include "clang/Basic/OpenCLImageTypes.def"
-#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
-    case BuiltinType::Id:
+#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
 #include "clang/Basic/OpenCLExtensionTypes.def"
-    case BuiltinType::OCLEvent:
-    case BuiltinType::OCLClkEvent:
-    case BuiltinType::OCLQueue:
-    case BuiltinType::OCLReserveID:
-    case BuiltinType::OCLSampler:
-    case BuiltinType::Dependent:
-#define PPC_VECTOR_TYPE(Name, Id, Size) \
-    case BuiltinType::Id:
+  case BuiltinType::OCLEvent:
+  case BuiltinType::OCLClkEvent:
+  case BuiltinType::OCLQueue:
+  case BuiltinType::OCLReserveID:
+  case BuiltinType::OCLSampler:
+  case BuiltinType::Dependent:
+#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
 #include "clang/Basic/PPCTypes.def"
 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
 #include "clang/Basic/HLSLIntangibleTypes.def"
 #define BUILTIN_TYPE(KIND, ID)
-#define PLACEHOLDER_TYPE(KIND, ID) \
-    case BuiltinType::KIND:
+#define PLACEHOLDER_TYPE(KIND, ID) case BuiltinType::KIND:
 #include "clang/AST/BuiltinTypes.def"
-      llvm_unreachable("invalid builtin type for @encode");
-    }
-    llvm_unreachable("invalid BuiltinType::Kind value");
+    llvm_unreachable("invalid builtin type for @encode");
+  }
+  llvm_unreachable("invalid BuiltinType::Kind value");
 }
 
 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
@@ -8902,8 +8902,8 @@ static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
   return getObjCEncodingForPrimitiveType(C, BT);
 }
 
-static void EncodeBitField(const ASTContext *Ctx, std::string& S,
-                           QualType T, const FieldDecl *FD) {
+static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T,
+                           const FieldDecl *FD) {
   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
   S += 'b';
   // The NeXT runtime encodes bit fields as b followed by the number of bits.
@@ -9049,7 +9049,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
       // combinations need to be rearranged.
       // Rewrite "in const" from "nr" to "rn"
       if (StringRef(S).ends_with("nr"))
-        S.replace(S.end()-2, S.end(), "rn");
+        S.replace(S.end() - 2, S.end(), "rn");
     }
 
     if (PointeeTy->isCharType()) {
@@ -9110,7 +9110,8 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
         S += llvm::utostr(CAT->getZExtSize());
       else {
-        //Variable length arrays are encoded as a regular array with 0 elements.
+        // Variable length arrays are encoded as a regular array with 0
+        // elements.
         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
                "Unknown array type!");
         S += '0';
@@ -9206,8 +9207,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
     if (Ty->isObjCIdType()) {
       S += "{objc_object=}";
       return;
-    }
-    else if (Ty->isObjCClassType()) {
+    } else if (Ty->isObjCClassType()) {
       S += "{objc_class=}";
       return;
     }
@@ -9223,7 +9223,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
     S += OI->getObjCRuntimeNameAsString();
     if (Options.ExpandStructures()) {
       S += '=';
-      SmallVector<const ObjCIvarDecl*, 32> Ivars;
+      SmallVector<const ObjCIvarDecl *, 32> Ivars;
       DeepCollectObjCIvars(OI, true, Ivars);
       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
         const FieldDecl *Field = Ivars[i];
@@ -9296,10 +9296,10 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
   // FIXME: we should do better than that.  'M' is available.
   case Type::MemberPointer:
   // This matches gcc's encoding, even though technically it is insufficient.
-  //FIXME. We should do a better job than gcc.
+  // FIXME. We should do a better job than gcc.
   case Type::Vector:
   case Type::ExtVector:
-  // Until we have a coherent encoding of these three types, issue warning.
+    // Until we have a coherent encoding of these three types, issue warning.
     if (NotEncodedT)
       *NotEncodedT = T;
     return;
@@ -9327,12 +9327,9 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
   case Type::Pipe:
 #define ABSTRACT_TYPE(KIND, BASE)
 #define TYPE(KIND, BASE)
-#define DEPENDENT_TYPE(KIND, BASE) \
-  case Type::KIND:
-#define NON_CANONICAL_TYPE(KIND, BASE) \
-  case Type::KIND:
-#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
-  case Type::KIND:
+#define DEPENDENT_TYPE(KIND, BASE) case Type::KIND:
+#define NON_CANONICAL_TYPE(KIND, BASE) case Type::KIND:
+#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) case Type::KIND:
 #include "clang/AST/TypeNodes.inc"
     llvm_unreachable("@encode for dependent type!");
   }
@@ -9397,15 +9394,16 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
 #ifndef NDEBUG
   uint64_t CurOffs = 0;
 #endif
-  std::multimap<uint64_t, NamedDecl *>::iterator
-    CurLayObj = FieldOrBaseOffsets.begin();
+  std::multimap<uint64_t, NamedDecl *>::iterator CurLayObj =
+      FieldOrBaseOffsets.begin();
 
   if (CXXRec && CXXRec->isDynamicClass() &&
       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
     if (FD) {
       S += "\"_vptr$";
       std::string recname = CXXRec->getNameAsString();
-      if (recname.empty()) recname = "?";
+      if (recname.empty())
+        recname = "?";
       S += recname;
       S += '"';
     }
@@ -9447,7 +9445,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
       // in the initial structure. Note that this differs from gcc which
       // expands virtual bases each time one is encountered in the hierarchy,
       // making the encoding type bigger than it really is.
-      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
+      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/ false,
                                       NotEncodedT);
       assert(!base->isEmpty());
 #ifndef NDEBUG
@@ -9481,7 +9479,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
 }
 
 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
-                                                 std::string& S) const {
+                                                 std::string &S) const {
   if (QT & Decl::OBJC_TQ_In)
     S += 'n';
   if (QT & Decl::OBJC_TQ_Inout)
@@ -9524,13 +9522,11 @@ TypedefDecl *ASTContext::getObjCClassDecl() const {
 
 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
   if (!ObjCProtocolClassDecl) {
-    ObjCProtocolClassDecl
-      = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
-                                  SourceLocation(),
-                                  &Idents.get("Protocol"),
+    ObjCProtocolClassDecl =
+        ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
+                                  SourceLocation(), &Idents.get("Protocol"),
                                   /*typeParamList=*/nullptr,
-                                  /*PrevDecl=*/nullptr,
-                                  SourceLocation(), true);
+                                  /*PrevDecl=*/nullptr, SourceLocation(), true);
   }
 
   return ObjCProtocolClassDecl;
@@ -9604,15 +9600,12 @@ CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
 
   // Create fields
   for (unsigned i = 0; i < NumFields; ++i) {
-    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
-                                         VaListTagDecl,
-                                         SourceLocation(),
-                                         SourceLocation(),
-                                         &Context->Idents.get(FieldNames[i]),
-                                         FieldTypes[i], /*TInfo=*/nullptr,
-                                         /*BitWidth=*/nullptr,
-                                         /*Mutable=*/false,
-                                         ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(
+        const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
+        SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
+        /*TInfo=*/nullptr,
+        /*BitWidth=*/nullptr,
+        /*Mutable=*/false, ICIS_NoInit);
     Field->setAccess(AS_public);
     VaListTagDecl->addDecl(Field);
   }
@@ -9657,14 +9650,11 @@ static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
 
   // Create fields
   for (unsigned i = 0; i < NumFields; ++i) {
-    FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
-                                         SourceLocation(),
-                                         SourceLocation(),
-                                         &Context->Idents.get(FieldNames[i]),
-                                         FieldTypes[i], /*TInfo=*/nullptr,
-                                         /*BitWidth=*/nullptr,
-                                         /*Mutable=*/false,
-                                         ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(
+        *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
+        &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
+        /*BitWidth=*/nullptr,
+        /*Mutable=*/false, ICIS_NoInit);
     Field->setAccess(AS_public);
     VaListTagDecl->addDecl(Field);
   }
@@ -9676,8 +9666,7 @@ static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
   TypedefDecl *VaListTagTypedefDecl =
       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
 
-  QualType VaListTagTypedefType =
-    Context->getTypedefType(VaListTagTypedefDecl);
+  QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
 
   // typedef __va_list_tag __builtin_va_list[1];
   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
@@ -9715,15 +9704,12 @@ CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
 
   // Create fields
   for (unsigned i = 0; i < NumFields; ++i) {
-    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
-                                         VaListTagDecl,
-                                         SourceLocation(),
-                                         SourceLocation(),
-                                         &Context->Idents.get(FieldNames[i]),
-                                         FieldTypes[i], /*TInfo=*/nullptr,
-                                         /*BitWidth=*/nullptr,
-                                         /*Mutable=*/false,
-                                         ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(
+        const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
+        SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
+        /*TInfo=*/nullptr,
+        /*BitWidth=*/nullptr,
+        /*Mutable=*/false, ICIS_NoInit);
     Field->setAccess(AS_public);
     VaListTagDecl->addDecl(Field);
   }
@@ -9748,8 +9734,7 @@ static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
 }
 
-static TypedefDecl *
-CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
+static TypedefDecl *CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
   // struct __va_list
   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
   if (Context->getLangOpts().CPlusPlus) {
@@ -9767,16 +9752,13 @@ CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
   VaListDecl->startDefinition();
 
   // void * __ap;
-  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
-                                       VaListDecl,
-                                       SourceLocation(),
-                                       SourceLocation(),
-                                       &Context->Idents.get("__ap"),
-                                       Context->getPointerType(Context->VoidTy),
-                                       /*TInfo=*/nullptr,
-                                       /*BitWidth=*/nullptr,
-                                       /*Mutable=*/false,
-                                       ICIS_NoInit);
+  FieldDecl *Field = FieldDecl::Create(
+      const_cast<ASTContext &>(*Context), VaListDecl, SourceLocation(),
+      SourceLocation(), &Context->Idents.get("__ap"),
+      Context->getPointerType(Context->VoidTy),
+      /*TInfo=*/nullptr,
+      /*BitWidth=*/nullptr,
+      /*Mutable=*/false, ICIS_NoInit);
   Field->setAccess(AS_public);
   VaListDecl->addDecl(Field);
 
@@ -9789,8 +9771,7 @@ CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
   return Context->buildImplicitTypedef(T, "__builtin_va_list");
 }
 
-static TypedefDecl *
-CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
+static TypedefDecl *CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
   // struct __va_list_tag {
   RecordDecl *VaListTagDecl;
   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
@@ -9818,15 +9799,12 @@ CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
 
   // Create fields
   for (unsigned i = 0; i < NumFields; ++i) {
-    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
-                                         VaListTagDecl,
-                                         SourceLocation(),
-                                         SourceLocation(),
-                                         &Context->Idents.get(FieldNames[i]),
-                                         FieldTypes[i], /*TInfo=*/nullptr,
-                                         /*BitWidth=*/nullptr,
-                                         /*Mutable=*/false,
-                                         ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(
+        const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
+        SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
+        /*TInfo=*/nullptr,
+        /*BitWidth=*/nullptr,
+        /*Mutable=*/false, ICIS_NoInit);
     Field->setAccess(AS_public);
     VaListTagDecl->addDecl(Field);
   }
@@ -10009,14 +9987,13 @@ ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
   assert(size > 1 && "set is not overloaded!");
 
   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
-                          size * sizeof(FunctionTemplateDecl*));
+                          size * sizeof(FunctionTemplateDecl *));
   auto *OT = new (memory) OverloadedTemplateStorage(size);
 
   NamedDecl **Storage = OT->getStorage();
   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
     NamedDecl *D = *I;
-    assert(isa<FunctionTemplateDecl>(D) ||
-           isa<UnresolvedUsingValueDecl>(D) ||
+    assert(isa<FunctionTemplateDecl>(D) || isa<UnresolvedUsingValueDecl>(D) ||
            (isa<UsingShadowDecl>(D) &&
             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
     *Storage++ = D;
@@ -10046,7 +10023,7 @@ TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
 
   void *InsertPos = nullptr;
   QualifiedTemplateName *QTN =
-    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+      QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
   if (!QTN) {
     QTN = new (*this, alignof(QualifiedTemplateName))
         QualifiedTemplateName(NNS, TemplateKeyword, Template);
@@ -10069,7 +10046,7 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
 
   void *InsertPos = nullptr;
   DependentTemplateName *QTN =
-    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
 
   if (QTN)
     return TemplateName(QTN);
@@ -10083,7 +10060,7 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
     QTN = new (*this, alignof(DependentTemplateName))
         DependentTemplateName(NNS, Name, Canon);
     DependentTemplateName *CheckQTN =
-      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+        DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
     assert(!CheckQTN && "Dependent type name canonicalization broken");
     (void)CheckQTN;
   }
@@ -10104,8 +10081,8 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
   DependentTemplateName::Profile(ID, NNS, Operator);
 
   void *InsertPos = nullptr;
-  DependentTemplateName *QTN
-    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+  DependentTemplateName *QTN =
+      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
 
   if (QTN)
     return TemplateName(QTN);
@@ -10119,8 +10096,8 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
     QTN = new (*this, alignof(DependentTemplateName))
         DependentTemplateName(NNS, Operator, Canon);
 
-    DependentTemplateName *CheckQTN
-      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+    DependentTemplateName *CheckQTN =
+        DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
     assert(!CheckQTN && "Dependent template name canonicalization broken");
     (void)CheckQTN;
   }
@@ -10137,8 +10114,8 @@ TemplateName ASTContext::getSubstTemplateTemplateParm(
                                             Index, PackIndex);
 
   void *insertPos = nullptr;
-  SubstTemplateTemplateParmStorage *subst
-    = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
+  SubstTemplateTemplateParmStorage *subst =
+      SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
 
   if (!subst) {
     subst = new (*this) SubstTemplateTemplateParmStorage(
@@ -10159,8 +10136,8 @@ ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
                                                 AssociatedDecl, Index, Final);
 
   void *InsertPos = nullptr;
-  SubstTemplateTemplateParmPackStorage *Subst
-    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
+  SubstTemplateTemplateParmPackStorage *Subst =
+      SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
 
   if (!Subst) {
     Subst = new (*this) SubstTemplateTemplateParmPackStorage(
@@ -10200,17 +10177,28 @@ ASTContext::getDeducedTemplateName(TemplateName Underlying,
 /// is actually a value of type @c TargetInfo::IntType.
 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
   switch (Type) {
-  case TargetInfo::NoInt: return {};
-  case TargetInfo::SignedChar: return SignedCharTy;
-  case TargetInfo::UnsignedChar: return UnsignedCharTy;
-  case TargetInfo::SignedShort: return ShortTy;
-  case TargetInfo::UnsignedShort: return UnsignedShortTy;
-  case TargetInfo::SignedInt: return IntTy;
-  case TargetInfo::UnsignedInt: return UnsignedIntTy;
-  case TargetInfo::SignedLong: return LongTy;
-  case TargetInfo::UnsignedLong: return UnsignedLongTy;
-  case TargetInfo::SignedLongLong: return LongLongTy;
-  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
+  case TargetInfo::NoInt:
+    return {};
+  case TargetInfo::SignedChar:
+    return SignedCharTy;
+  case TargetInfo::UnsignedChar:
+    return UnsignedCharTy;
+  case TargetInfo::SignedShort:
+    return ShortTy;
+  case TargetInfo::UnsignedShort:
+    return UnsignedShortTy;
+  case TargetInfo::SignedInt:
+    return IntTy;
+  case TargetInfo::UnsignedInt:
+    return UnsignedIntTy;
+  case TargetInfo::SignedLong:
+    return LongTy;
+  case TargetInfo::UnsignedLong:
+    return UnsignedLongTy;
+  case TargetInfo::SignedLongLong:
+    return LongLongTy;
+  case TargetInfo::UnsignedLongLong:
+    return UnsignedLongLongTy;
   }
 
   llvm_unreachable("Unhandled TargetInfo::IntType value");
@@ -10257,8 +10245,7 @@ Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
 
 /// areCompatVectorTypes - Return true if the two specified vector types are
 /// compatible.
-static bool areCompatVectorTypes(const VectorType *LHS,
-                                 const VectorType *RHS) {
+static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS) {
   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
   return LHS->getElementType() == RHS->getElementType() &&
          LHS->getNumElements() == RHS->getNumElements();
@@ -10511,13 +10498,13 @@ bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
 
       Ty = Attr->getModifiedType();
 
-    // X *__strong (...)
+      // X *__strong (...)
     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
       Ty = Paren->getInnerType();
 
-    // We do not want to look through typedefs, typeof(expr),
-    // typeof(type), or any other way that the type is somehow
-    // abstracted.
+      // We do not want to look through typedefs, typeof(expr),
+      // typeof(type), or any other way that the type is somehow
+      // abstracted.
     } else {
       return false;
     }
@@ -10530,9 +10517,8 @@ bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
 
 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
 /// inheritance hierarchy of 'rProto'.
-bool
-ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
-                                           ObjCProtocolDecl *rProto) const {
+bool ASTContext::ProtocolCompatibleWithProtocol(
+    ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const {
   if (declaresSameEntity(lProto, rProto))
     return true;
   for (auto *PI : rProto->protocols())
@@ -10647,7 +10633,8 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
     }
 
     // Static class's protocols, or its super class or category protocols
-    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
+    // must be found, direct or indirect in rhs's qualifier list or it is a
+    // mismatch.
     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
@@ -10679,8 +10666,8 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
 /// protocol qualifiers on the LHS or RHS.
 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
                                          const ObjCObjectPointerType *RHSOPT) {
-  const ObjCObjectType* LHS = LHSOPT->getObjectType();
-  const ObjCObjectType* RHS = RHSOPT->getObjectType();
+  const ObjCObjectType *LHS = LHSOPT->getObjectType();
+  const ObjCObjectType *RHS = RHSOPT->getObjectType();
 
   // If either type represents the built-in 'id' type, return true.
   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
@@ -10731,9 +10718,8 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
 /// not OK. For the return type, the opposite is not OK.
 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
-                                         const ObjCObjectPointerType *LHSOPT,
-                                         const ObjCObjectPointerType *RHSOPT,
-                                         bool BlockReturnType) {
+    const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT,
+    bool BlockReturnType) {
 
   // Function object that propagates a successful result or handles
   // __kindof types.
@@ -10748,9 +10734,8 @@ bool ASTContext::canAssignObjCInterfacesInBlockPointer(
     // Strip off __kindof and protocol qualifiers, then check whether
     // we can assign the other way.
     return canAssignObjCInterfacesInBlockPointer(
-             RHSOPT->stripObjCKindOfTypeAndQuals(*this),
-             LHSOPT->stripObjCKindOfTypeAndQuals(*this),
-             BlockReturnType);
+        RHSOPT->stripObjCKindOfTypeAndQuals(*this),
+        LHSOPT->stripObjCKindOfTypeAndQuals(*this), BlockReturnType);
   };
 
   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
@@ -10774,16 +10759,15 @@ bool ASTContext::canAssignObjCInterfacesInBlockPointer(
           (BlockReturnType ? RHSOPT : LHSOPT), false));
   }
 
-  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
-  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
-  if (LHS && RHS)  { // We have 2 user-defined types.
+  const ObjCInterfaceType *LHS = LHSOPT->getInterfaceType();
+  const ObjCInterfaceType *RHS = RHSOPT->getInterfaceType();
+  if (LHS && RHS) { // We have 2 user-defined types.
     if (LHS != RHS) {
       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
         return finish(BlockReturnType);
       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
         return finish(!BlockReturnType);
-    }
-    else
+    } else
       return true;
   }
   return false;
@@ -10791,8 +10775,8 @@ bool ASTContext::canAssignObjCInterfacesInBlockPointer(
 
 /// Comparison routine for Objective-C protocols to be used with
 /// llvm::array_pod_sort.
-static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
-                                      ObjCProtocolDecl * const *rhs) {
+static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs,
+                                      ObjCProtocolDecl *const *rhs) {
   return (*lhs)->getName().compare((*rhs)->getName());
 }
 
@@ -10801,15 +10785,13 @@ static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
 /// the given common base.
 /// It is used to build composite qualifier list of the composite type of
 /// the conditional expression involving two objective-c pointer objects.
-static
-void getIntersectionOfProtocols(ASTContext &Context,
-                                const ObjCInterfaceDecl *CommonBase,
-                                const ObjCObjectPointerType *LHSOPT,
-                                const ObjCObjectPointerType *RHSOPT,
-      SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
-
-  const ObjCObjectType* LHS = LHSOPT->getObjectType();
-  const ObjCObjectType* RHS = RHSOPT->getObjectType();
+static void getIntersectionOfProtocols(
+    ASTContext &Context, const ObjCInterfaceDecl *CommonBase,
+    const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT,
+    SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
+
+  const ObjCObjectType *LHS = LHSOPT->getObjectType();
+  const ObjCObjectType *RHS = RHSOPT->getObjectType();
   assert(LHS->getInterface() && "LHS must have an interface base");
   assert(RHS->getInterface() && "RHS must have an interface base");
 
@@ -10883,11 +10865,9 @@ static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
 }
 
 // Check that the given Objective-C type argument lists are equivalent.
-static bool sameObjCTypeArgs(ASTContext &ctx,
-                             const ObjCInterfaceDecl *iface,
+static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface,
                              ArrayRef<QualType> lhsArgs,
-                             ArrayRef<QualType> rhsArgs,
-                             bool stripKindOf) {
+                             ArrayRef<QualType> rhsArgs, bool stripKindOf) {
   if (lhsArgs.size() != rhsArgs.size())
     return false;
 
@@ -10923,13 +10903,13 @@ static bool sameObjCTypeArgs(ASTContext &ctx,
   return true;
 }
 
-QualType ASTContext::areCommonBaseCompatible(
-           const ObjCObjectPointerType *Lptr,
-           const ObjCObjectPointerType *Rptr) {
+QualType
+ASTContext::areCommonBaseCompatible(const ObjCObjectPointerType *Lptr,
+                                    const ObjCObjectPointerType *Rptr) {
   const ObjCObjectType *LHS = Lptr->getObjectType();
   const ObjCObjectType *RHS = Rptr->getObjectType();
-  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
-  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
+  const ObjCInterfaceDecl *LDecl = LHS->getInterface();
+  const ObjCInterfaceDecl *RDecl = RHS->getInterface();
 
   if (!LDecl || !RDecl)
     return {};
@@ -10942,7 +10922,7 @@ QualType ASTContext::areCommonBaseCompatible(
   // Follow the left-hand side up the class hierarchy until we either hit a
   // root or find the RHS. Record the ancestors in case we don't find it.
   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
-    LHSAncestors;
+      LHSAncestors;
   while (true) {
     // Record this ancestor. We'll need this if the common type isn't in the
     // path from the LHS to the root.
@@ -10954,8 +10934,8 @@ QualType ASTContext::areCommonBaseCompatible(
       bool anyChanges = false;
       if (LHS->isSpecialized() && RHS->isSpecialized()) {
         // Both have type arguments, compare them.
-        if (!sameObjCTypeArgs(*this, LHS->getInterface(),
-                              LHS->getTypeArgs(), RHS->getTypeArgs(),
+        if (!sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(),
+                              RHS->getTypeArgs(),
                               /*stripKindOf=*/true))
           return {};
       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
@@ -11005,8 +10985,8 @@ QualType ASTContext::areCommonBaseCompatible(
       bool anyChanges = false;
       if (LHS->isSpecialized() && RHS->isSpecialized()) {
         // Both have type arguments, compare them.
-        if (!sameObjCTypeArgs(*this, LHS->getInterface(),
-                              LHS->getTypeArgs(), RHS->getTypeArgs(),
+        if (!sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(),
+                              RHS->getTypeArgs(),
                               /*stripKindOf=*/true))
           return {};
       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
@@ -11067,9 +11047,10 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
-    CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
-    // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
-    // qualifiers.
+    CollectInheritedProtocols(RHS->getInterface(),
+                              SuperClassInheritedProtocols);
+    // Also, if RHS has explicit quelifiers, include them for comparing with
+    // LHS's qualifiers.
     for (auto *RHSPI : RHS->quals())
       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
     // If there is no protocols associated with RHS, it is not a match.
@@ -11098,8 +11079,8 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
 
     // If the RHS is specializd, compare type arguments.
     if (RHSSuper->isSpecialized() &&
-        !sameObjCTypeArgs(*this, LHS->getInterface(),
-                          LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
+        !sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(),
+                          RHSSuper->getTypeArgs(),
                           /*stripKindOf=*/true)) {
       return false;
     }
@@ -11175,13 +11156,13 @@ QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
   // GNU extension: two types are compatible if they appear as a function
   // argument, one of the types is a transparent union type and the other
   // type is compatible with a union member
-  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
-                                              Unqualified);
+  QualType lmerge =
+      mergeTransparentUnionType(lhs, rhs, OfBlockPointer, Unqualified);
   if (!lmerge.isNull())
     return lmerge;
 
-  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
-                                              Unqualified);
+  QualType rmerge =
+      mergeTransparentUnionType(rhs, lhs, OfBlockPointer, Unqualified);
   if (!rmerge.isNull())
     return rmerge;
 
@@ -11208,8 +11189,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
     if (!UnqualifiedResult)
       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
-  }
-  else
+  } else
     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
                          Unqualified);
   if (retType.isNull())
@@ -11233,7 +11213,8 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
   // FIXME: double check this
   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
   //                           rbase->getRegParmAttr() != 0 &&
-  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
+  //                           lbase->getRegParmAttr() !=
+  //                           rbase->getRegParmAttr()?
   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
 
@@ -11354,8 +11335,10 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
         allRTypes = false;
     }
 
-    if (allLTypes) return lhs;
-    if (allRTypes) return rhs;
+    if (allLTypes)
+      return lhs;
+    if (allRTypes)
+      return rhs;
 
     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
     EPI.ExtInfo = einfo;
@@ -11366,8 +11349,10 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
     return getFunctionType(retType, types, EPI);
   }
 
-  if (lproto) allRTypes = false;
-  if (rproto) allLTypes = false;
+  if (lproto)
+    allRTypes = false;
+  if (rproto)
+    allLTypes = false;
 
   const FunctionProtoType *proto = lproto ? lproto : rproto;
   if (proto) {
@@ -11395,8 +11380,10 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
         return {};
     }
 
-    if (allLTypes) return lhs;
-    if (allRTypes) return rhs;
+    if (allLTypes)
+      return lhs;
+    if (allRTypes)
+      return rhs;
 
     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
     EPI.ExtInfo = einfo;
@@ -11405,8 +11392,10 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
     return getFunctionType(retType, proto->getParamTypes(), EPI);
   }
 
-  if (allLTypes) return lhs;
-  if (allRTypes) return rhs;
+  if (allLTypes)
+    return lhs;
+  if (allRTypes)
+    return rhs;
   return getFunctionNoProtoType(retType, einfo);
 }
 
@@ -11457,8 +11446,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
     RHS = RHS.getUnqualifiedType();
   }
 
-  QualType LHSCan = getCanonicalType(LHS),
-           RHSCan = getCanonicalType(RHS);
+  QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS);
 
   // If two types are identical, they are compatible.
   if (LHSCan == RHSCan)
@@ -11504,8 +11492,10 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
 
   // We want to consider the two function types to be the same for these
   // comparisons, just force one to the other.
-  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
-  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
+  if (LHSClass == Type::FunctionProto)
+    LHSClass = Type::FunctionNoProto;
+  if (RHSClass == Type::FunctionProto)
+    RHSClass = Type::FunctionNoProto;
 
   // Same as above for arrays
   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
@@ -11514,12 +11504,16 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
     RHSClass = Type::ConstantArray;
 
   // ObjCInterfaces are just specialized ObjCObjects.
-  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
-  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
+  if (LHSClass == Type::ObjCInterface)
+    LHSClass = Type::ObjCObject;
+  if (RHSClass == Type::ObjCInterface)
+    RHSClass = Type::ObjCObject;
 
   // Canonicalize ExtVector -> Vector.
-  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
-  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
+  if (LHSClass == Type::ExtVector)
+    LHSClass = Type::Vector;
+  if (RHSClass == Type::ExtVector)
+    RHSClass = Type::Vector;
 
   // If the canonical type classes don't match.
   if (LHSClass != RHSClass) {
@@ -11528,13 +11522,13 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
     if (const auto *ETy = LHS->getAs<EnumType>()) {
       return mergeEnumWithInteger(*this, ETy, RHS, false);
     }
-    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
+    if (const EnumType *ETy = RHS->getAs<EnumType>()) {
       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
     }
     // allow block pointer type to match an 'id' type.
     if (OfBlockPointer && !BlockReturnType) {
-       if (LHS->isObjCIdType() && RHS->isBlockPointerType())
-         return LHS;
+      if (LHS->isObjCIdType() && RHS->isBlockPointerType())
+        return LHS;
       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
         return RHS;
     }
@@ -11575,8 +11569,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
   case Type::ExtVector:
     llvm_unreachable("Types are eliminated above");
 
-  case Type::Pointer:
-  {
+  case Type::Pointer: {
     // Merge two pointer types, while trying to preserve typedef info
     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
@@ -11584,8 +11577,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       LHSPointee = LHSPointee.getUnqualifiedType();
       RHSPointee = RHSPointee.getUnqualifiedType();
     }
-    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
-                                     Unqualified);
+    QualType ResultType =
+        mergeTypes(LHSPointee, RHSPointee, false, Unqualified);
     if (ResultType.isNull())
       return {};
     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
@@ -11594,8 +11587,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       return RHS;
     return getPointerType(ResultType);
   }
-  case Type::BlockPointer:
-  {
+  case Type::BlockPointer: {
     // Merge two block pointer types, while trying to preserve typedef info
     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
@@ -11617,8 +11609,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       RHSPointee =
           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
     }
-    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
-                                     Unqualified);
+    QualType ResultType =
+        mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, Unqualified);
     if (ResultType.isNull())
       return {};
     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
@@ -11627,8 +11619,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       return RHS;
     return getBlockPointerType(ResultType);
   }
-  case Type::Atomic:
-  {
+  case Type::Atomic: {
     // Merge two pointer types, while trying to preserve typedef info
     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
@@ -11636,8 +11627,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       LHSValue = LHSValue.getUnqualifiedType();
       RHSValue = RHSValue.getUnqualifiedType();
     }
-    QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
-                                     Unqualified);
+    QualType ResultType = mergeTypes(LHSValue, RHSValue, false, Unqualified);
     if (ResultType.isNull())
       return {};
     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
@@ -11646,10 +11636,9 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       return RHS;
     return getAtomicType(ResultType);
   }
-  case Type::ConstantArray:
-  {
-    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
-    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
+  case Type::ConstantArray: {
+    const ConstantArrayType *LCAT = getAsConstantArrayType(LHS);
+    const ConstantArrayType *RCAT = getAsConstantArrayType(RHS);
     if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
       return {};
 
@@ -11664,15 +11653,15 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
     if (ResultType.isNull())
       return {};
 
-    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
-    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
+    const VariableArrayType *LVAT = getAsVariableArrayType(LHS);
+    const VariableArrayType *RVAT = getAsVariableArrayType(RHS);
 
     // If either side is a variable array, and both are complete, check whether
     // the current dimension is definite.
     if (LVAT || RVAT) {
-      auto SizeFetch = [this](const VariableArrayType* VAT,
-          const ConstantArrayType* CAT)
-          -> std::pair<bool,llvm::APInt> {
+      auto SizeFetch =
+          [this](const VariableArrayType *VAT,
+                 const ConstantArrayType *CAT) -> std::pair<bool, llvm::APInt> {
         if (VAT) {
           std::optional<llvm::APSInt> TheInt;
           Expr *E = VAT->getSizeExpr();
@@ -11719,8 +11708,10 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       // has to be different.
       return RHS;
     }
-    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
-    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
+    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType))
+      return LHS;
+    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType))
+      return RHS;
     return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
   }
   case Type::FunctionNoProto:
@@ -11868,8 +11859,7 @@ void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
 /// 'RHS' attributes and returns the merged version; including for function
 /// return types.
 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
-  QualType LHSCan = getCanonicalType(LHS),
-  RHSCan = getCanonicalType(RHS);
+  QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS);
   // If two types are identical, they are compatible.
   if (LHSCan == RHSCan)
     return LHS;
@@ -11881,7 +11871,7 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
     QualType NewReturnType =
         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
     QualType ResReturnType =
-      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
+        mergeObjCGCQualifiers(NewReturnType, OldReturnType);
     if (ResReturnType.isNull())
       return {};
     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
@@ -12121,8 +12111,7 @@ void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
 /// to be an Integer Constant Expression.
 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
                                   ASTContext::GetBuiltinTypeError &Error,
-                                  bool &RequiresICE,
-                                  bool AllowTypeModifiers) {
+                                  bool &RequiresICE, bool AllowTypeModifiers) {
   // Modifiers.
   int HowLong = 0;
   bool Signed = false, Unsigned = false;
@@ -12130,12 +12119,15 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
 
   // Read the prefixed modifiers first.
   bool Done = false;
-  #ifndef NDEBUG
+#ifndef NDEBUG
   bool IsSpecial = false;
-  #endif
+#endif
   while (!Done) {
     switch (*Str++) {
-    default: Done = true; --Str; break;
+    default:
+      Done = true;
+      --Str;
+      break;
     case 'I':
       RequiresICE = true;
       break;
@@ -12158,9 +12150,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
-      #ifndef NDEBUG
+#ifndef NDEBUG
       IsSpecial = true;
-      #endif
+#endif
       if (Context.getTargetInfo().getLongWidth() == 32)
         ++HowLong;
       break;
@@ -12168,9 +12160,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
       // This modifier represents int64 type.
       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
-      #ifndef NDEBUG
+#ifndef NDEBUG
       IsSpecial = true;
-      #endif
+#endif
       switch (Context.getTargetInfo().getInt64Type()) {
       default:
         llvm_unreachable("Unexpected integer type");
@@ -12186,9 +12178,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
       // This modifier represents int32 type.
       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
-      #ifndef NDEBUG
+#ifndef NDEBUG
       IsSpecial = true;
-      #endif
+#endif
       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
       default:
         llvm_unreachable("Unexpected integer type");
@@ -12206,9 +12198,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
     case 'O':
       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
-      #ifndef NDEBUG
+#ifndef NDEBUG
       IsSpecial = true;
-      #endif
+#endif
       if (Context.getLangOpts().OpenCL)
         HowLong = 1;
       else
@@ -12221,7 +12213,8 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
 
   // Read the base type.
   switch (*Str++) {
-  default: llvm_unreachable("Unknown builtin type letter!");
+  default:
+    llvm_unreachable("Unknown builtin type letter!");
   case 'x':
     assert(HowLong == 0 && !Signed && !Unsigned &&
            "Bad modifiers used with 'x'!");
@@ -12287,11 +12280,11 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
     Type = Context.BoolTy;
     break;
-  case 'z':  // size_t.
+  case 'z': // size_t.
     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
     Type = Context.getSizeType();
     break;
-  case 'w':  // wchar_t.
+  case 'w': // wchar_t.
     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
     Type = Context.getWideCharType();
     break;
@@ -12333,8 +12326,8 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
     assert(End != Str && "Missing vector size");
     Str = End;
 
-    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
-                                             RequiresICE, false);
+    QualType ElementType =
+        DecodeTypeFromStr(Str, Context, Error, RequiresICE, false);
     assert(!RequiresICE && "Can't require vector ICE");
 
     Type = Context.getScalableVectorType(ElementType, NumElements);
@@ -12361,8 +12354,8 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
     assert(End != Str && "Missing vector size");
     Str = End;
 
-    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
-                                             RequiresICE, false);
+    QualType ElementType =
+        DecodeTypeFromStr(Str, Context, Error, RequiresICE, false);
     assert(!RequiresICE && "Can't require vector ICE");
 
     // TODO: No way to make AltiVec vectors in builtins yet.
@@ -12377,14 +12370,14 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
 
     Str = End;
 
-    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
-                                             false);
+    QualType ElementType =
+        DecodeTypeFromStr(Str, Context, Error, RequiresICE, false);
     Type = Context.getExtVectorType(ElementType, NumElements);
     break;
   }
   case 'X': {
-    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
-                                             false);
+    QualType ElementType =
+        DecodeTypeFromStr(Str, Context, Error, RequiresICE, false);
     assert(!RequiresICE && "Can't require complex ICE");
     Type = Context.getComplexType(ElementType);
     break;
@@ -12431,7 +12424,10 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
   Done = !AllowTypeModifiers;
   while (!Done) {
     switch (char c = *Str++) {
-    default: Done = true; --Str; break;
+    default:
+      Done = true;
+      --Str;
+      break;
     case '*':
     case '&': {
       // Both pointers and references can have their pointee types
@@ -12441,8 +12437,7 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
       if (End != Str) {
         // Note AddrSpace == 0 is not the same as an unspecified address space.
         Type = Context.getAddrSpaceQualType(
-          Type,
-          Context.getLangASForBuiltinAddressSpace(AddrSpace));
+            Type, Context.getLangASForBuiltinAddressSpace(AddrSpace));
         Str = End;
       }
       if (c == '*')
@@ -12483,8 +12478,7 @@ QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
 }
 
 /// GetBuiltinType - Return the type for the specified builtin.
-QualType ASTContext::GetBuiltinType(unsigned Id,
-                                    GetBuiltinTypeError &Error,
+QualType ASTContext::GetBuiltinType(unsigned Id, GetBuiltinTypeError &Error,
                                     unsigned *IntegerConstantArgs) const {
   const char *TypeStr = BuiltinInfo.getTypeString(Id);
   if (TypeStr[0] == '\0') {
@@ -12496,8 +12490,8 @@ QualType ASTContext::GetBuiltinType(unsigned Id,
 
   bool RequiresICE = false;
   Error = GE_None;
-  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
-                                       RequiresICE, true);
+  QualType ResType =
+      DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
   if (Error != GE_None)
     return {};
 
@@ -12530,8 +12524,8 @@ QualType ASTContext::GetBuiltinType(unsigned Id,
 
   FunctionType::ExtInfo EI(getDefaultCallingConvention(
       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
-  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
-
+  if (BuiltinInfo.isNoReturn(Id))
+    EI = EI.withNoReturn(true);
 
   // We really shouldn't be making a no-proto type here.
   if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
@@ -12670,9 +12664,10 @@ adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
 }
 
 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
-  return adjustGVALinkageForExternalDefinitionKind(*this, FD,
-           adjustGVALinkageForAttributes(*this, FD,
-             basicGVALinkageForFunction(*this, FD)));
+  return adjustGVALinkageForExternalDefinitionKind(
+      *this, FD,
+      adjustGVALinkageForAttributes(*this, FD,
+                                    basicGVALinkageForFunction(*this, FD)));
 }
 
 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
@@ -12763,9 +12758,10 @@ static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
 }
 
 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
-  return adjustGVALinkageForExternalDefinitionKind(*this, VD,
-           adjustGVALinkageForAttributes(*this, VD,
-             basicGVALinkageForVariable(*this, VD)));
+  return adjustGVALinkageForExternalDefinitionKind(
+      *this, VD,
+      adjustGVALinkageForAttributes(*this, VD,
+                                    basicGVALinkageForVariable(*this, VD)));
 }
 
 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
@@ -12892,7 +12888,7 @@ void ASTContext::forEachMultiversionedFunctionVersion(
     const FunctionDecl *FD,
     llvm::function_ref<void(FunctionDecl *)> Pred) const {
   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
-  llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
+  llvm::SmallDenseSet<const FunctionDecl *, 4> SeenDecls;
   FD = FD->getMostRecentDecl();
   // FIXME: The order of traversal here matters and depends on the order of
   // lookup results, which happens to be (mostly) oldest-to-newest, but we
@@ -13119,7 +13115,7 @@ unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
 
 MangleNumberingContext &
 ASTContext::getManglingNumberContext(const DeclContext *DC) {
-  assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
+  assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
   if (!MCtx)
     MCtx = createMangleNumberingContext();
@@ -13209,8 +13205,7 @@ ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
   return Result;
 }
 
-MSGuidDecl *
-ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
+MSGuidDecl *ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
 
   llvm::FoldingSetNodeID ID;
@@ -13282,15 +13277,13 @@ bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
 }
 
-bool
-ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
-                                const ObjCMethodDecl *MethodImpl) {
+bool ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
+                                     const ObjCMethodDecl *MethodImpl) {
   // No point trying to match an unavailable/deprecated mothod.
-  if (MethodDecl->hasAttr<UnavailableAttr>()
-      || MethodDecl->hasAttr<DeprecatedAttr>())
+  if (MethodDecl->hasAttr<UnavailableAttr>() ||
+      MethodDecl->hasAttr<DeprecatedAttr>())
     return false;
-  if (MethodDecl->getObjCDeclQualifier() !=
-      MethodImpl->getObjCDeclQualifier())
+  if (MethodDecl->getObjCDeclQualifier() != MethodImpl->getObjCDeclQualifier())
     return false;
   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
     return false;
@@ -13299,8 +13292,9 @@ ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
     return false;
 
   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
-       IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
-       EF = MethodDecl->param_end();
+                                            IF = MethodDecl->param_begin(),
+                                            EM = MethodImpl->param_end(),
+                                            EF = MethodDecl->param_end();
        IM != EM && IF != EF; ++IM, ++IF) {
     const ParmVarDecl *DeclVar = (*IF);
     const ParmVarDecl *ImplVar = (*IM);
@@ -14454,35 +14448,36 @@ QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
   assert(Ty->isFixedPointType());
 
-  if (Ty->isSaturatedFixedPointType()) return Ty;
+  if (Ty->isSaturatedFixedPointType())
+    return Ty;
 
   switch (Ty->castAs<BuiltinType>()->getKind()) {
-    default:
-      llvm_unreachable("Not a fixed point type!");
-    case BuiltinType::ShortAccum:
-      return SatShortAccumTy;
-    case BuiltinType::Accum:
-      return SatAccumTy;
-    case BuiltinType::LongAccum:
-      return SatLongAccumTy;
-    case BuiltinType::UShortAccum:
-      return SatUnsignedShortAccumTy;
-    case BuiltinType::UAccum:
-      return SatUnsignedAccumTy;
-    case BuiltinType::ULongAccum:
-      return SatUnsignedLongAccumTy;
-    case BuiltinType::ShortFract:
-      return SatShortFractTy;
-    case BuiltinType::Fract:
-      return SatFractTy;
-    case BuiltinType::LongFract:
-      return SatLongFractTy;
-    case BuiltinType::UShortFract:
-      return SatUnsignedShortFractTy;
-    case BuiltinType::UFract:
-      return SatUnsignedFractTy;
-    case BuiltinType::ULongFract:
-      return SatUnsignedLongFractTy;
+  default:
+    llvm_unreachable("Not a fixed point type!");
+  case BuiltinType::ShortAccum:
+    return SatShortAccumTy;
+  case BuiltinType::Accum:
+    return SatAccumTy;
+  case BuiltinType::LongAccum:
+    return SatLongAccumTy;
+  case BuiltinType::UShortAccum:
+    return SatUnsignedShortAccumTy;
+  case BuiltinType::UAccum:
+    return SatUnsignedAccumTy;
+  case BuiltinType::ULongAccum:
+    return SatUnsignedLongAccumTy;
+  case BuiltinType::ShortFract:
+    return SatShortFractTy;
+  case BuiltinType::Fract:
+    return SatFractTy;
+  case BuiltinType::LongFract:
+    return SatLongFractTy;
+  case BuiltinType::UShortFract:
+    return SatUnsignedShortFractTy;
+  case BuiltinType::UFract:
+    return SatUnsignedFractTy;
+  case BuiltinType::ULongFract:
+    return SatUnsignedLongFractTy;
   }
 }
 
@@ -14498,56 +14493,55 @@ LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
 
 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
 // doesn't include ASTContext.h
-template
-clang::LazyGenerationalUpdatePtr<
+template clang::LazyGenerationalUpdatePtr<
     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
-clang::LazyGenerationalUpdatePtr<
-    const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
-        const clang::ASTContext &Ctx, Decl *Value);
+clang::LazyGenerationalUpdatePtr<const Decl *, Decl *,
+                                 &ExternalASTSource::CompleteRedeclChain>::
+    makeValue(const clang::ASTContext &Ctx, Decl *Value);
 
 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
   assert(Ty->isFixedPointType());
 
   const TargetInfo &Target = getTargetInfo();
   switch (Ty->castAs<BuiltinType>()->getKind()) {
-    default:
-      llvm_unreachable("Not a fixed point type!");
-    case BuiltinType::ShortAccum:
-    case BuiltinType::SatShortAccum:
-      return Target.getShortAccumScale();
-    case BuiltinType::Accum:
-    case BuiltinType::SatAccum:
-      return Target.getAccumScale();
-    case BuiltinType::LongAccum:
-    case BuiltinType::SatLongAccum:
-      return Target.getLongAccumScale();
-    case BuiltinType::UShortAccum:
-    case BuiltinType::SatUShortAccum:
-      return Target.getUnsignedShortAccumScale();
-    case BuiltinType::UAccum:
-    case BuiltinType::SatUAccum:
-      return Target.getUnsignedAccumScale();
-    case BuiltinType::ULongAccum:
-    case BuiltinType::SatULongAccum:
-      return Target.getUnsignedLongAccumScale();
-    case BuiltinType::ShortFract:
-    case BuiltinType::SatShortFract:
-      return Target.getShortFractScale();
-    case BuiltinType::Fract:
-    case BuiltinType::SatFract:
-      return Target.getFractScale();
-    case BuiltinType::LongFract:
-    case BuiltinType::SatLongFract:
-      return Target.getLongFractScale();
-    case BuiltinType::UShortFract:
-    case BuiltinType::SatUShortFract:
-      return Target.getUnsignedShortFractScale();
-    case BuiltinType::UFract:
-    case BuiltinType::SatUFract:
-      return Target.getUnsignedFractScale();
-    case BuiltinType::ULongFract:
-    case BuiltinType::SatULongFract:
-      return Target.getUnsignedLongFractScale();
+  default:
+    llvm_unreachable("Not a fixed point type!");
+  case BuiltinType::ShortAccum:
+  case BuiltinType::SatShortAccum:
+    return Target.getShortAccumScale();
+  case BuiltinType::Accum:
+  case BuiltinType::SatAccum:
+    return Target.getAccumScale();
+  case BuiltinType::LongAccum:
+  case BuiltinType::SatLongAccum:
+    return Target.getLongAccumScale();
+  case BuiltinType::UShortAccum:
+  case BuiltinType::SatUShortAccum:
+    return Target.getUnsignedShortAccumScale();
+  case BuiltinType::UAccum:
+  case BuiltinType::SatUAccum:
+    return Target.getUnsignedAccumScale();
+  case BuiltinType::ULongAccum:
+  case BuiltinType::SatULongAccum:
+    return Target.getUnsignedLongAccumScale();
+  case BuiltinType::ShortFract:
+  case BuiltinType::SatShortFract:
+    return Target.getShortFractScale();
+  case BuiltinType::Fract:
+  case BuiltinType::SatFract:
+    return Target.getFractScale();
+  case BuiltinType::LongFract:
+  case BuiltinType::SatLongFract:
+    return Target.getLongFractScale();
+  case BuiltinType::UShortFract:
+  case BuiltinType::SatUShortFract:
+    return Target.getUnsignedShortFractScale();
+  case BuiltinType::UFract:
+  case BuiltinType::SatUFract:
+    return Target.getUnsignedFractScale();
+  case BuiltinType::ULongFract:
+  case BuiltinType::SatULongFract:
+    return Target.getUnsignedLongFractScale();
   }
 }
 
@@ -14556,39 +14550,39 @@ unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
 
   const TargetInfo &Target = getTargetInfo();
   switch (Ty->castAs<BuiltinType>()->getKind()) {
-    default:
-      llvm_unreachable("Not a fixed point type!");
-    case BuiltinType::ShortAccum:
-    case BuiltinType::SatShortAccum:
-      return Target.getShortAccumIBits();
-    case BuiltinType::Accum:
-    case BuiltinType::SatAccum:
-      return Target.getAccumIBits();
-    case BuiltinType::LongAccum:
-    case BuiltinType::SatLongAccum:
-      return Target.getLongAccumIBits();
-    case BuiltinType::UShortAccum:
-    case BuiltinType::SatUShortAccum:
-      return Target.getUnsignedShortAccumIBits();
-    case BuiltinType::UAccum:
-    case BuiltinType::SatUAccum:
-      return Target.getUnsignedAccumIBits();
-    case BuiltinType::ULongAccum:
-    case BuiltinType::SatULongAccum:
-      return Target.getUnsignedLongAccumIBits();
-    case BuiltinType::ShortFract:
-    case BuiltinType::SatShortFract:
-    case BuiltinType::Fract:
-    case BuiltinType::SatFract:
-    case BuiltinType::LongFract:
-    case BuiltinType::SatLongFract:
-    case BuiltinType::UShortFract:
-    case BuiltinType::SatUShortFract:
-    case BuiltinType::UFract:
-    case BuiltinType::SatUFract:
-    case BuiltinType::ULongFract:
-    case BuiltinType::SatULongFract:
-      return 0;
+  default:
+    llvm_unreachable("Not a fixed point type!");
+  case BuiltinType::ShortAccum:
+  case BuiltinType::SatShortAccum:
+    return Target.getShortAccumIBits();
+  case BuiltinType::Accum:
+  case BuiltinType::SatAccum:
+    return Target.getAccumIBits();
+  case BuiltinType::LongAccum:
+  case BuiltinType::SatLongAccum:
+    return Target.getLongAccumIBits();
+  case BuiltinType::UShortAccum:
+  case BuiltinType::SatUShortAccum:
+    return Target.getUnsignedShortAccumIBits();
+  case BuiltinType::UAccum:
+  case BuiltinType::SatUAccum:
+    return Target.getUnsignedAccumIBits();
+  case BuiltinType::ULongAccum:
+  case BuiltinType::SatULongAccum:
+    return Target.getUnsignedLongAccumIBits();
+  case BuiltinType::ShortFract:
+  case BuiltinType::SatShortFract:
+  case BuiltinType::Fract:
+  case BuiltinType::SatFract:
+  case BuiltinType::LongFract:
+  case BuiltinType::SatLongFract:
+  case BuiltinType::UShortFract:
+  case BuiltinType::SatUShortFract:
+  case BuiltinType::UFract:
+  case BuiltinType::SatUFract:
+  case BuiltinType::ULongFract:
+  case BuiltinType::SatULongFract:
+    return 0;
   }
 }
 
@@ -14819,9 +14813,9 @@ OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
   return *OMPTraitInfoVector.back();
 }
 
-const StreamingDiagnostic &clang::
-operator<<(const StreamingDiagnostic &DB,
-           const ASTContext::SectionInfo &Section) {
+const StreamingDiagnostic &
+clang::operator<<(const StreamingDiagnostic &DB,
+                  const ASTContext::SectionInfo &Section) {
   if (Section.Decl)
     return DB << Section.Decl;
   return DB << "a prior #pragma section";
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.h b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
index dfffc2639b0d2..9aaf63a1e0adc 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuilder.h
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENBUILDER_H
 
 #include "CIRGenTypeCache.h"
+#include "mlir/IR/Location.h"
 #include "clang/CIR/MissingFeatures.h"
 
 #include "clang/CIR/Dialect/Builder/CIRBaseBuilder.h"
@@ -20,7 +21,6 @@ namespace clang::CIRGen {
 
 class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
   const CIRGenTypeCache &typeCache;
-  bool isFPConstrained = false;
 
 public:
   CIRGenBuilderTy(mlir::MLIRContext &mlirContext, const CIRGenTypeCache &tc)
@@ -161,38 +161,34 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
     llvm_unreachable("negation for the given type is NYI");
   }
 
-  mlir::Value createFSub(mlir::Value lhs, mlir::Value rhs) {
+  mlir::Value createFSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     assert(!cir::MissingFeatures::metaDataNode());
-    if (isFPConstrained)
-      llvm_unreachable("Constrained FP NYI");
-
+    assert(!cir::MissingFeatures::fpConstraints());
     assert(!cir::MissingFeatures::foldBinOpFMF());
-    return create<cir::BinOp>(lhs.getLoc(), cir::BinOpKind::Sub, lhs, rhs);
+
+    return create<cir::BinOp>(loc, cir::BinOpKind::Sub, lhs, rhs);
   }
 
-  mlir::Value createFAdd(mlir::Value lhs, mlir::Value rhs) {
+  mlir::Value createFAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     assert(!cir::MissingFeatures::metaDataNode());
-    if (isFPConstrained)
-      llvm_unreachable("Constrained FP NYI");
-
+    assert(!cir::MissingFeatures::fpConstraints());
     assert(!cir::MissingFeatures::foldBinOpFMF());
-    return create<cir::BinOp>(lhs.getLoc(), cir::BinOpKind::Add, lhs, rhs);
+
+    return create<cir::BinOp>(loc, cir::BinOpKind::Add, lhs, rhs);
   }
-  mlir::Value createFMul(mlir::Value lhs, mlir::Value rhs) {
+  mlir::Value createFMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     assert(!cir::MissingFeatures::metaDataNode());
-    if (isFPConstrained)
-      llvm_unreachable("Constrained FP NYI");
-
+    assert(!cir::MissingFeatures::fpConstraints());
     assert(!cir::MissingFeatures::foldBinOpFMF());
-    return create<cir::BinOp>(lhs.getLoc(), cir::BinOpKind::Mul, lhs, rhs);
+
+    return create<cir::BinOp>(loc, cir::BinOpKind::Mul, lhs, rhs);
   }
-  mlir::Value createFDiv(mlir::Value lhs, mlir::Value rhs) {
+  mlir::Value createFDiv(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     assert(!cir::MissingFeatures::metaDataNode());
-    if (isFPConstrained)
-      llvm_unreachable("Constrained FP NYI");
-
+    assert(!cir::MissingFeatures::fpConstraints());
     assert(!cir::MissingFeatures::foldBinOpFMF());
-    return create<cir::BinOp>(lhs.getLoc(), cir::BinOpKind::Div, lhs, rhs);
+
+    return create<cir::BinOp>(loc, cir::BinOpKind::Div, lhs, rhs);
   }
 };
 
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index d3365cbcbbeed..db062f95f122e 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -210,9 +210,10 @@ LValue CIRGenFunction::emitUnaryOpLValue(const UnaryOperator *e) {
 
     if (e->getType()->isAnyComplexType()) {
       cgm.errorNYI(e->getSourceRange(), "UnaryOp complex inc/dec");
-      return LValue();
+      lv = LValue();
+    } else {
+      emitScalarPrePostIncDec(e, lv, isInc, /*isPre=*/true);
     }
-    emitScalarPrePostIncDec(e, lv, isInc, /*isPre=*/true);
 
     return lv;
   }
@@ -250,6 +251,7 @@ LValue CIRGenFunction::emitBinaryOperatorLValue(const BinaryOperator *e) {
 
   switch (CIRGenFunction::getEvaluationKind(e->getType())) {
   case cir::TEK_Scalar: {
+    assert(!cir::MissingFeatures::objCLifetime());
     if (e->getLHS()->getType().getObjCLifetime() !=
         clang::Qualifiers::ObjCLifetime::OCL_None) {
       cgm.errorNYI(e->getSourceRange(), "objc lifetimes");
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index eebf2f622858a..0a6ab62d6a141 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/CIR/MissingFeatures.h"
 
+#include "mlir/IR/Location.h"
 #include "mlir/IR/Value.h"
 
 #include <cassert>
@@ -38,7 +39,7 @@ struct BinOpInfo {
   const Expr *e; // Entire expr, for error unsupported.  May not be binop.
 
   /// Check if the binop computes a division or a remainder.
-  bool isDivremOp() const {
+  bool isDivRemOp() const {
     return opcode == BO_Div || opcode == BO_Rem || opcode == BO_DivAssign ||
            opcode == BO_RemAssign;
   }
@@ -416,8 +417,9 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
     if (lv.isBitField()) {
       cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec bitfield");
       return {};
+    } else {
+      cgf.emitStoreThroughLValue(RValue::get(value), lv);
     }
-    cgf.emitStoreThroughLValue(RValue::get(value), lv);
 
     // If this is a postinc, return the value read from memory, otherwise use
     // the updated value.
@@ -641,7 +643,7 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
     result.opcode = e->getOpcode();
     result.loc = e->getSourceRange();
     // TODO(cir): Result.FPFeatures
-    assert(!cir::MissingFeatures::getFPFeaturesInEffect());
+    assert(!cir::MissingFeatures::cgFPOptionsRAII());
     result.e = e;
     return result;
   }
@@ -739,9 +741,8 @@ LValue ScalarExprEmitter::emitCompoundAssignLValue(
 
   opInfo.fullType = promotionTypeCR;
   opInfo.compType = opInfo.fullType;
-  if (const auto *vecType = dyn_cast_or_null<VectorType>(opInfo.fullType)) {
+  if (const auto *vecType = dyn_cast_or_null<VectorType>(opInfo.fullType))
     opInfo.compType = vecType->getElementType();
-  }
   opInfo.opcode = e->getOpcode();
   opInfo.fpfeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
   opInfo.e = e;
@@ -761,8 +762,7 @@ LValue ScalarExprEmitter::emitCompoundAssignLValue(
       cgf, cgf.getLoc(e->getSourceRange())};
   SourceLocation loc = e->getExprLoc();
   if (!promotionTypeLHS.isNull())
-    opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy, promotionTypeLHS,
-                                      loc);
+    opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy, promotionTypeLHS, loc);
   else
     opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy,
                                       e->getComputationLHSType(), loc);
@@ -772,8 +772,8 @@ LValue ScalarExprEmitter::emitCompoundAssignLValue(
 
   // Convert the result back to the LHS type,
   // potentially with Implicit Conversion sanitizer check.
-  result = emitScalarConversion(result, promotionTypeCR, lhsTy, loc);
-  //                              ScalarConversionOpts(cgf.sanOpts));
+  result = emitScalarConversion(result, promotionTypeCR, lhsTy, loc,
+                                ScalarConversionOpts(cgf.sanOpts));
 
   // Store the result value into the LHS lvalue. Bit-fields are handled
   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
@@ -867,25 +867,10 @@ mlir::Value CIRGenFunction::emitPromotedScalarExpr(const Expr *e,
   return e->getType()->isNullPtrType();
 }
 
-/// If \p e is a widened promoted integer, get its base (unpromoted) type.
-static std::optional<QualType>
-getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e) {
-  const Expr *base = e->IgnoreImpCasts();
-  if (e == base)
-    return std::nullopt;
-
-  QualType baseTy = base->getType();
-  if (!astContext.isPromotableIntegerType(baseTy) ||
-      astContext.getTypeSize(baseTy) >= astContext.getTypeSize(e->getType()))
-    return std::nullopt;
-
-  return baseTy;
-}
-
 /// Check if \p e is a widened promoted integer.
 [[maybe_unused]] static bool isWidenedIntegerOp(const ASTContext &astContext,
                                                 const Expr *e) {
-  return getUnwidenedIntegerType(astContext, e).has_value();
+  return astContext.getUnwidenedIntegerType(e).has_value();
 }
 
 /// Check if we can skip the overflow check for \p Op.
@@ -906,11 +891,13 @@ getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e) {
   // We usually don't need overflow checks for binops with widened operands.
   // Multiplication with promoted unsigned operands is a special case.
   const auto *bo = cast<BinaryOperator>(op.e);
-  auto optionalLHSTy = getUnwidenedIntegerType(astContext, bo->getLHS());
+  std::optional<QualType> optionalLHSTy =
+      astContext.getUnwidenedIntegerType(bo->getLHS());
   if (!optionalLHSTy)
     return false;
 
-  auto optionalRHSTy = getUnwidenedIntegerType(astContext, bo->getRHS());
+  std::optional<QualType> optionalRHSTy =
+      astContext.getUnwidenedIntegerType(bo->getRHS());
   if (!optionalRHSTy)
     return false;
 
@@ -1001,10 +988,10 @@ static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf,
 
     index = cgf.getBuilder().createCast(cir::CastKind::integral, index,
                                         numElements.getType());
-    index = cgf.getBuilder().createMul(index, numElements);
+    index = cgf.getBuilder().createMul(index.getLoc(), index, numElements);
 
     if (cgf.getLangOpts().isSignedOverflowDefined()) {
-      assert(!cir::MissingFeatures::opPtrStride());
+      assert(!cir::MissingFeatures::ptrStrideOp());
       cgf.cgm.errorNYI("pointer stride");
     } else {
       pointer = cgf.emitCheckedInBoundsGEP(elemTy, pointer, index, isSigned,
@@ -1023,7 +1010,7 @@ static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf,
     elemTy = cgf.convertTypeForMem(elementType);
 
   if (cgf.getLangOpts().isSignedOverflowDefined()) {
-    assert(!cir::MissingFeatures::opPtrStride());
+    assert(!cir::MissingFeatures::ptrStrideOp());
     cgf.cgm.errorNYI("pointer stride");
     return pointer;
   }
@@ -1033,19 +1020,20 @@ static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf,
 }
 
 mlir::Value ScalarExprEmitter::emitMul(const BinOpInfo &ops) {
+  const mlir::Location loc = cgf.getLoc(ops.loc);
   if (ops.compType->isSignedIntegerOrEnumerationType()) {
     switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
     case LangOptions::SOB_Defined:
       if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
-        return builder.createMul(ops.lhs, ops.rhs);
+        return builder.createMul(loc, ops.lhs, ops.rhs);
       [[fallthrough]];
     case LangOptions::SOB_Undefined:
       if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
-        return builder.createNSWMul(ops.lhs, ops.rhs);
+        return builder.createNSWMul(loc, ops.lhs, ops.rhs);
       [[fallthrough]];
     case LangOptions::SOB_Trapping:
       if (canElideOverflowCheck(cgf.getContext(), ops))
-        return builder.createNSWMul(ops.lhs, ops.rhs);
+        return builder.createNSWMul(loc, ops.lhs, ops.rhs);
       cgf.cgm.errorNYI("sanitizers");
     }
   }
@@ -1061,7 +1049,7 @@ mlir::Value ScalarExprEmitter::emitMul(const BinOpInfo &ops) {
 
   if (cir::isFPOrFPVectorTy(ops.lhs.getType())) {
     assert(!cir::MissingFeatures::cgFPOptionsRAII());
-    return builder.createFMul(ops.lhs, ops.rhs);
+    return builder.createFMul(loc, ops.lhs, ops.rhs);
   }
 
   if (ops.isFixedPointOp()) {
@@ -1089,19 +1077,21 @@ mlir::Value ScalarExprEmitter::emitAdd(const BinOpInfo &ops) {
   if (mlir::isa<cir::PointerType>(ops.lhs.getType()) ||
       mlir::isa<cir::PointerType>(ops.rhs.getType()))
     return emitPointerArithmetic(cgf, ops, /*isSubtraction=*/false);
+
+  const mlir::Location loc = cgf.getLoc(ops.loc);
   if (ops.compType->isSignedIntegerOrEnumerationType()) {
     switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
     case LangOptions::SOB_Defined:
       if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
-        return builder.createAdd(ops.lhs, ops.rhs);
+        return builder.createAdd(loc, ops.lhs, ops.rhs);
       [[fallthrough]];
     case LangOptions::SOB_Undefined:
       if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
-        return builder.createNSWAdd(ops.lhs, ops.rhs);
+        return builder.createNSWAdd(loc, ops.lhs, ops.rhs);
       [[fallthrough]];
     case LangOptions::SOB_Trapping:
       if (canElideOverflowCheck(cgf.getContext(), ops))
-        return builder.createNSWAdd(ops.lhs, ops.rhs);
+        return builder.createNSWAdd(loc, ops.lhs, ops.rhs);
       cgf.cgm.errorNYI("sanitizers");
     }
   }
@@ -1118,7 +1108,7 @@ mlir::Value ScalarExprEmitter::emitAdd(const BinOpInfo &ops) {
 
   if (cir::isFPOrFPVectorTy(ops.lhs.getType())) {
     assert(!cir::MissingFeatures::cgFPOptionsRAII());
-    return builder.createFAdd(ops.lhs, ops.rhs);
+    return builder.createFAdd(loc, ops.lhs, ops.rhs);
   }
 
   if (ops.isFixedPointOp()) {
@@ -1127,28 +1117,28 @@ mlir::Value ScalarExprEmitter::emitAdd(const BinOpInfo &ops) {
     return {};
   }
 
-  return builder.create<cir::BinOp>(cgf.getLoc(ops.loc),
-                                    cgf.convertType(ops.fullType),
+  return builder.create<cir::BinOp>(loc, cgf.convertType(ops.fullType),
                                     cir::BinOpKind::Add, ops.lhs, ops.rhs);
 }
 
 mlir::Value ScalarExprEmitter::emitSub(const BinOpInfo &ops) {
+  const mlir::Location loc = cgf.getLoc(ops.loc);
   // The LHS is always a pointer if either side is.
   if (!mlir::isa<cir::PointerType>(ops.lhs.getType())) {
     if (ops.compType->isSignedIntegerOrEnumerationType()) {
       switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
       case LangOptions::SOB_Defined: {
         if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
-          return builder.createSub(ops.lhs, ops.rhs);
+          return builder.createSub(loc, ops.lhs, ops.rhs);
         [[fallthrough]];
       }
       case LangOptions::SOB_Undefined:
         if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
-          return builder.createNSWSub(ops.lhs, ops.rhs);
+          return builder.createNSWSub(loc, ops.lhs, ops.rhs);
         [[fallthrough]];
       case LangOptions::SOB_Trapping:
         if (canElideOverflowCheck(cgf.getContext(), ops))
-          return builder.createNSWSub(ops.lhs, ops.rhs);
+          return builder.createNSWSub(loc, ops.lhs, ops.rhs);
         cgf.cgm.errorNYI("sanitizers");
       }
     }
@@ -1166,7 +1156,7 @@ mlir::Value ScalarExprEmitter::emitSub(const BinOpInfo &ops) {
 
     if (cir::isFPOrFPVectorTy(ops.lhs.getType())) {
       assert(!cir::MissingFeatures::cgFPOptionsRAII());
-      return builder.createFSub(ops.lhs, ops.rhs);
+      return builder.createFSub(loc, ops.lhs, ops.rhs);
     }
 
     if (ops.isFixedPointOp()) {
@@ -1193,7 +1183,7 @@ mlir::Value ScalarExprEmitter::emitSub(const BinOpInfo &ops) {
   // LLVM we shall take VLA's, division by element size, etc.
   //
   // See more in `EmitSub` in CGExprScalar.cpp.
-  assert(!cir::MissingFeatures::opPtrDiff());
+  assert(!cir::MissingFeatures::ptrDiffOp());
   cgf.cgm.errorNYI("ptrdiff");
   return {};
 }
@@ -1495,14 +1485,14 @@ mlir::Value CIRGenFunction::emitScalarPrePostIncDec(const UnaryOperator *e,
 mlir::Value CIRGenFunction::emitCheckedInBoundsGEP(
     mlir::Type elemTy, mlir::Value ptr, ArrayRef<mlir::Value> idxList,
     bool signedIndices, bool isSubtraction, SourceLocation loc) {
-  assert(idxList.size() == 1 && "multi-index ptr arithmetic NYI");
-  assert(!cir::MissingFeatures::opPtrStride());
+  assert(!cir::MissingFeatures::ptrStrideOp());
+  if (idxList.size() != 1)
+    cgm.errorNYI("multi-index ptr arithmetic");
   mlir::Value gepVal = nullptr;
 
   // If the pointer overflow sanitizer isn't enabled, do nothing.
   if (!sanOpts.has(SanitizerKind::PointerOverflow))
     return gepVal;
-  return ptr;
 
   assert(!cir::MissingFeatures::pointerOverflowSanitizer());
   cgm.errorNYI("pointer overflow sanitizer");
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp
index eccdcdb497f84..ba14391657720 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -168,24 +168,9 @@ static bool MustVisitNullValue(const Expr *E) {
   return E->getType()->isNullPtrType();
 }
 
-/// If \p E is a widened promoted integer, get its base (unpromoted) type.
-static std::optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
-                                                       const Expr *E) {
-  const Expr *Base = E->IgnoreImpCasts();
-  if (E == Base)
-    return std::nullopt;
-
-  QualType BaseTy = Base->getType();
-  if (!Ctx.isPromotableIntegerType(BaseTy) ||
-      Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
-    return std::nullopt;
-
-  return BaseTy;
-}
-
 /// Check if \p E is a widened promoted integer.
 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
-  return getUnwidenedIntegerType(Ctx, E).has_value();
+  return Ctx.getUnwidenedIntegerType(E).has_value();
 }
 
 /// Check if we can skip the overflow check for \p Op.
@@ -228,11 +213,11 @@ static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
   if (BO->hasExcludedOverflowPattern())
     return true;
 
-  auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
+  auto OptionalLHSTy = Ctx.getUnwidenedIntegerType(BO->getLHS());
   if (!OptionalLHSTy)
     return false;
 
-  auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
+  auto OptionalRHSTy = Ctx.getUnwidenedIntegerType(BO->getRHS());
   if (!OptionalRHSTy)
     return false;
 

>From 77aa79bd512c50046e2bc475199c565f17b35901 Mon Sep 17 00:00:00 2001
From: Morris Hafner <mhafner at nvidia.com>
Date: Tue, 25 Mar 2025 14:53:00 +0000
Subject: [PATCH 08/11] More review feedback addressed

Also revert ASTContext reformat
---
 clang/include/clang/AST/ASTContext.h          |  314 +--
 .../CIR/Dialect/Builder/CIRBaseBuilder.h      |   77 +-
 clang/lib/AST/ASTContext.cpp                  | 2042 +++++++++--------
 clang/lib/CIR/CodeGen/CIRGenBuilder.h         |    1 -
 4 files changed, 1264 insertions(+), 1170 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h
index 2c3170278d3d9..a6b1ae66a4a39 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -200,7 +200,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
       ConstantArrayTypes;
   mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
-  mutable std::vector<VariableArrayType *> VariableArrayTypes;
+  mutable std::vector<VariableArrayType*> VariableArrayTypes;
   mutable llvm::ContextualFoldingSet<DependentSizedArrayType, ASTContext &>
       DependentSizedArrayTypes;
   mutable llvm::ContextualFoldingSet<DependentSizedExtVectorType, ASTContext &>
@@ -214,8 +214,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable llvm::ContextualFoldingSet<DependentSizedMatrixType, ASTContext &>
       DependentSizedMatrixTypes;
   mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
-  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext &>
-      FunctionProtoTypes;
+  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
+    FunctionProtoTypes;
   mutable llvm::ContextualFoldingSet<DependentTypeOfExprType, ASTContext &>
       DependentTypeOfExprTypes;
   mutable llvm::ContextualFoldingSet<DependentDecltypeType, ASTContext &>
@@ -226,11 +226,11 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
   mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
   mutable llvm::FoldingSet<SubstTemplateTypeParmType>
-      SubstTemplateTypeParmTypes;
+    SubstTemplateTypeParmTypes;
   mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
-      SubstTemplateTypeParmPackTypes;
-  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext &>
-      TemplateSpecializationTypes;
+    SubstTemplateTypeParmPackTypes;
+  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
+    TemplateSpecializationTypes;
   mutable llvm::FoldingSet<ParenType> ParenTypes{GeneralTypesLog2InitSize};
   mutable llvm::FoldingSet<UsingType> UsingTypes;
   mutable llvm::FoldingSet<TypedefType> TypedefTypes;
@@ -238,20 +238,20 @@ class ASTContext : public RefCountedBase<ASTContext> {
       GeneralTypesLog2InitSize};
   mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
   mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
-                                     ASTContext &>
-      DependentTemplateSpecializationTypes;
+                                     ASTContext&>
+    DependentTemplateSpecializationTypes;
   mutable llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
   mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
   mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
   mutable llvm::FoldingSet<DependentUnaryTransformType>
-      DependentUnaryTransformTypes;
+    DependentUnaryTransformTypes;
   // An AutoType can have a dependency on another AutoType via its template
   // arguments. Since both dependent and dependency are on the same set,
   // we can end up in an infinite recursion when looking for a node if we used
   // a `FoldingSet`, since both could end up in the same bucket.
   mutable llvm::DenseMap<llvm::FoldingSetNodeID, AutoType *> AutoTypes;
   mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
-      DeducedTemplateSpecializationTypes;
+    DeducedTemplateSpecializationTypes;
   mutable llvm::FoldingSet<AtomicType> AtomicTypes;
   mutable llvm::FoldingSet<AttributedType> AttributedTypes;
   mutable llvm::FoldingSet<PipeType> PipeTypes;
@@ -266,10 +266,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
   mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
   mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
-      SubstTemplateTemplateParms;
+    SubstTemplateTemplateParms;
   mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
-                                     ASTContext &>
-      SubstTemplateTemplateParmPacks;
+                                     ASTContext&>
+    SubstTemplateTemplateParmPacks;
   mutable llvm::ContextualFoldingSet<DeducedTemplateStorage, ASTContext &>
       DeducedTemplates;
 
@@ -285,8 +285,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// A cache mapping from RecordDecls to ASTRecordLayouts.
   ///
   /// This is lazily created.  This is intentionally not serialized.
-  mutable llvm::DenseMap<const RecordDecl *, const ASTRecordLayout *>
-      ASTRecordLayouts;
+  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
+    ASTRecordLayouts;
   mutable llvm::DenseMap<const ObjCInterfaceDecl *, const ASTRecordLayout *>
       ObjCLayouts;
 
@@ -301,15 +301,14 @@ class ASTContext : public RefCountedBase<ASTContext> {
   mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
 
   /// A cache mapping from CXXRecordDecls to key functions.
-  llvm::DenseMap<const CXXRecordDecl *, LazyDeclPtr> KeyFunctions;
+  llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
 
   /// Mapping from ObjCContainers to their ObjCImplementations.
-  llvm::DenseMap<ObjCContainerDecl *, ObjCImplDecl *> ObjCImpls;
+  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
 
   /// Mapping from ObjCMethod to its duplicate declaration in the same
   /// interface.
-  llvm::DenseMap<const ObjCMethodDecl *, const ObjCMethodDecl *>
-      ObjCMethodRedecls;
+  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
 
   /// Mapping from __block VarDecls to BlockVarCopyInit.
   llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
@@ -357,15 +356,16 @@ class ASTContext : public RefCountedBase<ASTContext> {
       Profile(ID, C, Parm);
     }
 
-    static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C,
+    static void Profile(llvm::FoldingSetNodeID &ID,
+                        const ASTContext &C,
                         TemplateTemplateParmDecl *Parm);
   };
   mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
-                                     const ASTContext &>
-      CanonTemplateTemplateParms;
+                                     const ASTContext&>
+    CanonTemplateTemplateParms;
 
   TemplateTemplateParmDecl *
-  getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
+    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
 
   /// The typedef for the __int128_t type.
   mutable TypedefDecl *Int128Decl = nullptr;
@@ -455,29 +455,29 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   /// Since so few decls have attrs, we keep them in a hash map instead of
   /// wasting space in the Decl class.
-  llvm::DenseMap<const Decl *, AttrVec *> DeclAttrs;
+  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
 
   /// A mapping from non-redeclarable declarations in modules that were
   /// merged with other declarations to the canonical declaration that they were
   /// merged into.
-  llvm::DenseMap<Decl *, Decl *> MergedDecls;
+  llvm::DenseMap<Decl*, Decl*> MergedDecls;
 
   /// A mapping from a defining declaration to a list of modules (other
   /// than the owning module of the declaration) that contain merged
   /// definitions of that entity.
-  llvm::DenseMap<NamedDecl *, llvm::TinyPtrVector<Module *>> MergedDefModules;
+  llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
 
   /// Initializers for a module, in order. Each Decl will be either
   /// something that has a semantic effect on startup (such as a variable with
   /// a non-constant initializer), or an ImportDecl (which recursively triggers
   /// initialization of another module).
   struct PerModuleInitializers {
-    llvm::SmallVector<Decl *, 4> Initializers;
+    llvm::SmallVector<Decl*, 4> Initializers;
     llvm::SmallVector<GlobalDeclID, 4> LazyInitializers;
 
     void resolve(ASTContext &Ctx);
   };
-  llvm::DenseMap<Module *, PerModuleInitializers *> ModuleInitializers;
+  llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
 
   /// This is the top-level (C++20) Named module we are building.
   Module *CurrentCXXNamedModule = nullptr;
@@ -545,7 +545,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
   /// class template X) and will be marked TSK_ImplicitInstantiation.
   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
-      TemplateOrInstantiation;
+  TemplateOrInstantiation;
 
   /// Keeps track of the declaration from which a using declaration was
   /// created during instantiation.
@@ -583,8 +583,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
       InstantiatedFromUsingEnumDecl;
 
   /// Simlarly maps instantiated UsingShadowDecls to their origin.
-  llvm::DenseMap<UsingShadowDecl *, UsingShadowDecl *>
-      InstantiatedFromUsingShadowDecl;
+  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
+    InstantiatedFromUsingShadowDecl;
 
   llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
 
@@ -738,8 +738,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
     PrintingPolicy = Policy;
   }
 
-  SourceManager &getSourceManager() { return SourceMgr; }
-  const SourceManager &getSourceManager() const { return SourceMgr; }
+  SourceManager& getSourceManager() { return SourceMgr; }
+  const SourceManager& getSourceManager() const { return SourceMgr; }
 
   // Cleans up some of the data structures. This allows us to do cleanup
   // normally done in the destructor earlier. Renders much of the ASTContext
@@ -747,7 +747,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   // longer need access to the AST.
   void cleanup();
 
-  llvm::BumpPtrAllocator &getAllocator() const { return BumpAlloc; }
+  llvm::BumpPtrAllocator &getAllocator() const {
+    return BumpAlloc;
+  }
 
   void *Allocate(size_t Size, unsigned Align = 8) const {
     return BumpAlloc.Allocate(Size, Align);
@@ -783,7 +785,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Return the total amount of physical memory allocated for representing
   /// AST nodes and type information.
-  size_t getASTAllocatedMemory() const { return BumpAlloc.getTotalMemory(); }
+  size_t getASTAllocatedMemory() const {
+    return BumpAlloc.getTotalMemory();
+  }
 
   /// Return the total memory used for various side tables.
   size_t getSideTableAllocatedMemory() const;
@@ -816,7 +820,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// sets integer QualTy according to specified details:
   /// bitwidth, signed/unsigned.
   /// Returns empty type if there is no appropriate target types.
-  QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const;
+  QualType getIntTypeForBitwidth(unsigned DestWidth,
+                                 unsigned Signed) const;
 
   /// getRealTypeForBitwidth -
   /// sets floating point QualTy according to specified bitwidth.
@@ -826,7 +831,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
 
-  const LangOptions &getLangOpts() const { return LangOpts; }
+  const LangOptions& getLangOpts() const { return LangOpts; }
 
   // If this condition is false, typo correction must be performed eagerly
   // rather than delayed in many places, as it makes use of dependent types.
@@ -841,14 +846,16 @@ class ASTContext : public RefCountedBase<ASTContext> {
   bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
                                 const QualType &Ty) const;
 
-  const XRayFunctionFilter &getXRayFilter() const { return *XRayFilter; }
+  const XRayFunctionFilter &getXRayFilter() const {
+    return *XRayFilter;
+  }
 
   const ProfileList &getProfileList() const { return *ProfList; }
 
   DiagnosticsEngine &getDiagnostics() const;
 
   FullSourceLoc getFullLoc(SourceLocation Loc) const {
-    return FullSourceLoc(Loc, SourceMgr);
+    return FullSourceLoc(Loc,SourceMgr);
   }
 
   /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden
@@ -945,7 +952,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
 
   comments::FullComment *cloneFullComment(comments::FullComment *FC,
-                                          const Decl *D) const;
+                                         const Decl *D) const;
 
 private:
   mutable comments::CommandTraits CommentCommandTraits;
@@ -993,7 +1000,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   }
 
   /// Retrieve the attributes for the given declaration.
-  AttrVec &getDeclAttrs(const Decl *D);
+  AttrVec& getDeclAttrs(const Decl *D);
 
   /// Erase the attributes corresponding to the given declaration.
   void eraseDeclAttrs(const Decl *D);
@@ -1002,14 +1009,14 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// class template specialization, returns the templated static data member
   /// from which it was instantiated.
   // FIXME: Remove ?
-  MemberSpecializationInfo *
-  getInstantiatedFromStaticDataMember(const VarDecl *Var);
+  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
+                                                           const VarDecl *Var);
 
   /// Note that the static data member \p Inst is an instantiation of
   /// the static data member template \p Tmpl of a class template.
-  void setInstantiatedFromStaticDataMember(
-      VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK,
-      SourceLocation PointOfInstantiation = SourceLocation());
+  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
+                                           TemplateSpecializationKind TSK,
+                        SourceLocation PointOfInstantiation = SourceLocation());
 
   TemplateOrSpecializationInfo
   getTemplateOrSpecializationInfo(const VarDecl *Var);
@@ -1069,9 +1076,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// the same selector and is of the same kind (class or instance).
   /// A method in an implementation is not considered as overriding the same
   /// method in the interface or its categories.
-  void
-  getOverriddenMethods(const NamedDecl *Method,
-                       SmallVectorImpl<const NamedDecl *> &Overridden) const;
+  void getOverriddenMethods(
+                        const NamedDecl *Method,
+                        SmallVectorImpl<const NamedDecl *> &Overridden) const;
 
   /// Notify the AST context that a new import declaration has been
   /// parsed or implicitly created within this translation unit.
@@ -1106,7 +1113,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Get the additional modules in which the definition \p Def has
   /// been merged.
-  ArrayRef<Module *> getModulesWithMergedDefinition(const NamedDecl *Def);
+  ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
 
   /// Add a declaration to the list of declarations that are initialized
   /// for a module. This will typically be a global variable (with internal
@@ -1117,7 +1124,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   void addLazyModuleInitializers(Module *M, ArrayRef<GlobalDeclID> IDs);
 
   /// Get the initializations to perform when importing a module, if any.
-  ArrayRef<Decl *> getModuleInitializers(Module *M);
+  ArrayRef<Decl*> getModuleInitializers(Module *M);
 
   /// Set the (C++20) module we are building.
   void setCurrentNamedModule(Module *M);
@@ -1153,10 +1160,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   CanQualType VoidTy;
   CanQualType BoolTy;
   CanQualType CharTy;
-  CanQualType WCharTy;    // [C++ 3.9.1p5].
+  CanQualType WCharTy;  // [C++ 3.9.1p5].
   CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
-  CanQualType
-      WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
+  CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
   CanQualType Char8Ty;  // [C++20 proposal]
   CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
   CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
@@ -1165,7 +1171,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
   CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty, Ibm128Ty;
   CanQualType ShortAccumTy, AccumTy,
-      LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
+      LongAccumTy;  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
   CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
   CanQualType ShortFractTy, FractTy, LongFractTy;
   CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
@@ -1185,7 +1191,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
   CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
   CanQualType ObjCBuiltinBoolTy;
-#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
+#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
   CanQualType SingletonId;
 #include "clang/Basic/OpenCLImageTypes.def"
   CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
@@ -1193,13 +1199,17 @@ class ASTContext : public RefCountedBase<ASTContext> {
   CanQualType IncompleteMatrixIdxTy;
   CanQualType ArraySectionTy;
   CanQualType OMPArrayShapingTy, OMPIteratorTy;
-#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) CanQualType Id##Ty;
+#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
+  CanQualType Id##Ty;
 #include "clang/Basic/OpenCLExtensionTypes.def"
-#define SVE_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
+#define SVE_TYPE(Name, Id, SingletonId) \
+  CanQualType SingletonId;
 #include "clang/Basic/AArch64SVEACLETypes.def"
-#define PPC_VECTOR_TYPE(Name, Id, Size) CanQualType Id##Ty;
+#define PPC_VECTOR_TYPE(Name, Id, Size) \
+  CanQualType Id##Ty;
 #include "clang/Basic/PPCTypes.def"
-#define RVV_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
+#define RVV_TYPE(Name, Id, SingletonId) \
+  CanQualType SingletonId;
 #include "clang/Basic/RISCVVTypes.def"
 #define WASM_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
 #include "clang/Basic/WebAssemblyReferenceTypes.def"
@@ -1261,7 +1271,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Retrieve a pointer to the external AST source associated
   /// with this AST context, if any.
-  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
+  ExternalASTSource *getExternalSource() const {
+    return ExternalSource.get();
+  }
 
   /// Attach an AST mutation listener to the AST context.
   ///
@@ -1277,7 +1289,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ASTMutationListener *getASTMutationListener() const { return Listener; }
 
   void PrintStats() const;
-  const SmallVectorImpl<Type *> &getTypes() const { return Types; }
+  const SmallVectorImpl<Type *>& getTypes() const { return Types; }
 
   BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
                                                 const IdentifierInfo *II) const;
@@ -1327,7 +1339,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Return the "other" discriminator used for the pointer auth schema used for
   /// vtable pointers in instances of the requested type.
-  uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD);
+  uint16_t
+  getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD);
 
   /// Return the "other" type-specific discriminator for the given type.
   uint16_t getPointerAuthTypeDiscriminator(QualType T);
@@ -1337,9 +1350,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// qualifiers on ObjCObjectPointerType. It can be set to true when
   /// constructing the canonical type of a Objective-C type parameter.
   QualType applyObjCProtocolQualifiers(QualType type,
-                                       ArrayRef<ObjCProtocolDecl *> protocols,
-                                       bool &hasError,
-                                       bool allowOnPointerType = false) const;
+      ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
+      bool allowOnPointerType = false) const;
 
   /// Return the uniqued reference to the type for an Objective-C
   /// gc-qualified type.
@@ -1438,14 +1450,14 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// number with the specified element type.
   QualType getComplexType(QualType T) const;
   CanQualType getComplexType(CanQualType T) const {
-    return CanQualType::CreateUnsafe(getComplexType((QualType)T));
+    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
   }
 
   /// Return the uniqued reference to the type for a pointer to
   /// the specified type.
   QualType getPointerType(QualType T) const;
   CanQualType getPointerType(CanQualType T) const {
-    return CanQualType::CreateUnsafe(getPointerType((QualType)T));
+    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
   }
 
   QualType
@@ -1466,7 +1478,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// pointer types.
   QualType getDecayedType(QualType T) const;
   CanQualType getDecayedType(CanQualType T) const {
-    return CanQualType::CreateUnsafe(getDecayedType((QualType)T));
+    return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
   }
   /// Return the uniqued reference to a specified decay from the original
   /// type to the decayed type.
@@ -1522,7 +1534,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
     cudaConfigureCallDecl = FD;
   }
 
-  FunctionDecl *getcudaConfigureCallDecl() { return cudaConfigureCallDecl; }
+  FunctionDecl *getcudaConfigureCallDecl() {
+    return cudaConfigureCallDecl;
+  }
 
   /// Returns true iff we need copy/dispose helpers for the given type.
   bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
@@ -1530,13 +1544,14 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
   /// is set to false in this case. If HasByrefExtendedLayout returns true,
   /// byref variable has extended lifetime.
-  bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime,
+  bool getByrefLifetime(QualType Ty,
+                        Qualifiers::ObjCLifetime &Lifetime,
                         bool &HasByrefExtendedLayout) const;
 
   /// Return the uniqued reference to the type for an lvalue reference
   /// to the specified type.
-  QualType getLValueReferenceType(QualType T,
-                                  bool SpelledAsLValue = true) const;
+  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
+    const;
 
   /// Return the uniqued reference to the type for an rvalue reference
   /// to the specified type.
@@ -1631,7 +1646,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   /// FIXME: We will need these to be uniqued, or at least comparable, at some
   /// point.
-  QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr,
+  QualType getDependentSizedExtVectorType(QualType VectorType,
+                                          Expr *SizeExpr,
                                           SourceLocation AttrLoc) const;
 
   /// Return the unique reference to the matrix type of the specified element
@@ -1686,8 +1702,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
   QualType getTypeDeclType(const TypeDecl *Decl,
                            const TypeDecl *PrevDecl = nullptr) const {
     assert(Decl && "Passed null for Decl param");
-    if (Decl->TypeForDecl)
-      return QualType(Decl->TypeForDecl, 0);
+    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
 
     if (PrevDecl) {
       assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
@@ -1791,7 +1806,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                             const TemplateArgument &ArgPack);
 
   QualType
-  getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack,
+  getTemplateTypeParmType(unsigned Depth, unsigned Index,
+                          bool ParameterPack,
                           TemplateTypeParmDecl *ParmDecl = nullptr) const;
 
   QualType getTemplateSpecializationType(TemplateName T,
@@ -1848,10 +1864,12 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                 ObjCInterfaceDecl *PrevDecl = nullptr) const;
 
   /// Legacy interface: cannot provide type arguments or __kindof.
-  QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols,
+  QualType getObjCObjectType(QualType Base,
+                             ObjCProtocolDecl * const *Protocols,
                              unsigned NumProtocols) const;
 
-  QualType getObjCObjectType(QualType Base, ArrayRef<QualType> typeArgs,
+  QualType getObjCObjectType(QualType Base,
+                             ArrayRef<QualType> typeArgs,
                              ArrayRef<ObjCProtocolDecl *> protocols,
                              bool isKindOf) const;
 
@@ -1890,10 +1908,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                  UnaryTransformType::UTTKind UKind) const;
 
   /// C++11 deduced auto type.
-  QualType
-  getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
-              bool IsPack = false, ConceptDecl *TypeConstraintConcept = nullptr,
-              ArrayRef<TemplateArgument> TypeConstraintArgs = {}) const;
+  QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
+                       bool IsDependent, bool IsPack = false,
+                       ConceptDecl *TypeConstraintConcept = nullptr,
+                       ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
 
   /// C++11 deduction pattern for 'auto' type.
   QualType getAutoDeductType() const;
@@ -2007,9 +2025,13 @@ class ASTContext : public RefCountedBase<ASTContext> {
     return ObjCConstantStringType;
   }
 
-  QualType getObjCNSStringType() const { return ObjCNSStringType; }
+  QualType getObjCNSStringType() const {
+    return ObjCNSStringType;
+  }
 
-  void setObjCNSStringType(QualType T) { ObjCNSStringType = T; }
+  void setObjCNSStringType(QualType T) {
+    ObjCNSStringType = T;
+  }
 
   /// Retrieve the type that \c id has been defined to, which may be
   /// different from the built-in \c id if \c id has been typedef'd.
@@ -2153,8 +2175,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   /// If \p Field is specified then record field names are also encoded.
   void getObjCEncodingForType(QualType T, std::string &S,
-                              const FieldDecl *Field = nullptr,
-                              QualType *NotEncodedT = nullptr) const;
+                              const FieldDecl *Field=nullptr,
+                              QualType *NotEncodedT=nullptr) const;
 
   /// Emit the Objective-C property type encoding for the given
   /// type \p T into \p S.
@@ -2192,9 +2214,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
                                       ObjCProtocolDecl *rProto) const;
 
-  ObjCPropertyImplDecl *
-  getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD,
-                                         const Decl *Container) const;
+  ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
+                                                  const ObjCPropertyDecl *PD,
+                                                  const Decl *Container) const;
 
   /// Return the size of type \p T for Objective-C encoding purpose,
   /// in characters.
@@ -2208,7 +2230,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
   /// pointer type, a pointer to a struct.
-  QualType getObjCIdType() const { return getTypeDeclType(getObjCIdDecl()); }
+  QualType getObjCIdType() const {
+    return getTypeDeclType(getObjCIdDecl());
+  }
 
   /// Retrieve the typedef corresponding to the predefined 'SEL' type
   /// in Objective-C.
@@ -2216,7 +2240,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Retrieve the type that corresponds to the predefined Objective-C
   /// 'SEL' type.
-  QualType getObjCSelType() const { return getTypeDeclType(getObjCSelDecl()); }
+  QualType getObjCSelType() const {
+    return getTypeDeclType(getObjCSelDecl());
+  }
 
   /// Retrieve the typedef declaration corresponding to the predefined
   /// Objective-C 'Class' type.
@@ -2235,13 +2261,19 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ObjCInterfaceDecl *getObjCProtocolDecl() const;
 
   /// Retrieve declaration of 'BOOL' typedef
-  TypedefDecl *getBOOLDecl() const { return BOOLDecl; }
+  TypedefDecl *getBOOLDecl() const {
+    return BOOLDecl;
+  }
 
   /// Save declaration of 'BOOL' typedef
-  void setBOOLDecl(TypedefDecl *TD) { BOOLDecl = TD; }
+  void setBOOLDecl(TypedefDecl *TD) {
+    BOOLDecl = TD;
+  }
 
   /// type of 'BOOL' type.
-  QualType getBOOLType() const { return getTypeDeclType(getBOOLDecl()); }
+  QualType getBOOLType() const {
+    return getTypeDeclType(getBOOLDecl());
+  }
 
   /// Retrieve the type of the Objective-C \c Protocol class.
   QualType getObjCProtoType() const {
@@ -2488,7 +2520,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
 
   /// Return the size of the character type, in bits.
-  uint64_t getCharWidth() const { return getTypeSize(CharTy); }
+  uint64_t getCharWidth() const {
+    return getTypeSize(CharTy);
+  }
 
   /// Convert a size in bits to a size in characters.
   CharUnits toCharUnitsFromBits(int64_t BitSize) const;
@@ -2545,9 +2579,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
     return toCharUnitsFromBits(getPreferredTypeAlign(T));
   }
 
-  /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
-  /// type, in characters, before alignment adjustments. This method does not
-  /// work on incomplete types.
+  /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
+  /// in characters, before alignment adjustments. This method does not work on
+  /// incomplete types.
   CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
   CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
 
@@ -2620,8 +2654,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Get or compute information about the layout of the specified
   /// Objective-C interface.
-  const ASTRecordLayout &
-  getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const;
+  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
+    const;
 
   void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
                         bool Simple = false) const;
@@ -2684,11 +2718,11 @@ class ASTContext : public RefCountedBase<ASTContext> {
   MangleContext *createDeviceMangleContext(const TargetInfo &T);
 
   void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
-                            SmallVectorImpl<const ObjCIvarDecl *> &Ivars) const;
+                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
 
   unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
-  void CollectInheritedProtocols(
-      const Decl *CDecl, llvm::SmallPtrSet<ObjCProtocolDecl *, 8> &Protocols);
+  void CollectInheritedProtocols(const Decl *CDecl,
+                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
 
   /// Return true if the specified type has unique object representations
   /// according to (C++17 [meta.unary.prop]p9)
@@ -2775,8 +2809,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
         return true;
 
       if (IsParam) {
-        // Ok for the superclass method parameter to be "nonnull" and the
-        // subclass method parameter to be "nullable"
+        // Ok for the superclass method parameter to be "nonnull" and the subclass
+        // method parameter to be "nullable"
         return (*SuperTnullability == NullabilityKind::NonNull &&
                 *SubTnullability == NullabilityKind::Nullable);
       }
@@ -2835,7 +2869,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
 
   /// Retrieves the default calling convention for the current target.
-  CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod,
+  CallingConv getDefaultCallingConvention(bool IsVariadic,
+                                          bool IsCXXMethod,
                                           bool IsBuiltin = false) const;
 
   /// Retrieves the "canonical" template name that refers to a
@@ -2898,8 +2933,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// The canonical template argument is the simplest template argument
   /// (which may be a type, value, expression, or declaration) that
   /// expresses the value of the argument.
-  TemplateArgument
-  getCanonicalTemplateArgument(const TemplateArgument &Arg) const;
+  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
+    const;
 
   /// Type Query functions.  If the type is an instance of the specified class,
   /// return the Type pointer for the underlying maximally pretty type.  This
@@ -2915,8 +2950,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
     return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
   }
-  const DependentSizedArrayType *
-  getAsDependentSizedArrayType(QualType T) const {
+  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
+    const {
     return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
   }
 
@@ -3073,10 +3108,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                const ObjCObjectPointerType *RHSOPT);
   bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
                                const ObjCObjectType *RHS);
-  bool
-  canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT,
-                                        const ObjCObjectPointerType *RHSOPT,
-                                        bool BlockReturnType);
+  bool canAssignObjCInterfacesInBlockPointer(
+                                          const ObjCObjectPointerType *LHSOPT,
+                                          const ObjCObjectPointerType *RHSOPT,
+                                          bool BlockReturnType);
   bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
   QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
                                    const ObjCObjectPointerType *RHSOPT);
@@ -3093,7 +3128,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
                                        bool OfBlockPointer = false,
                                        bool Unqualified = false);
   QualType mergeTransparentUnionType(QualType, QualType,
-                                     bool OfBlockPointer = false,
+                                     bool OfBlockPointer=false,
                                      bool Unqualified = false);
 
   QualType mergeObjCGCQualifiers(QualType, QualType);
@@ -3119,8 +3154,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ///
   bool mergeExtParameterInfo(
       const FunctionProtoType *FirstFnType,
-      const FunctionProtoType *SecondFnType, bool &CanUseFirst,
-      bool &CanUseSecond,
+      const FunctionProtoType *SecondFnType,
+      bool &CanUseFirst, bool &CanUseSecond,
       SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
 
   void ResetObjCLayout(const ObjCInterfaceDecl *D);
@@ -3196,7 +3231,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
   ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
 
   /// Return true if there is at least one \@implementation in the TU.
-  bool AnyObjCImplementation() { return !ObjCImpls.empty(); }
+  bool AnyObjCImplementation() {
+    return !ObjCImpls.empty();
+  }
 
   /// Set the implementation of ObjCInterfaceDecl.
   void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
@@ -3221,11 +3258,11 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
   /// Set the copy initialization expression of a block var decl. \p CanThrow
   /// indicates whether the copy expression can throw or not.
-  void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow);
+  void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
 
   /// Get the copy initialization expression of the VarDecl \p VD, or
   /// nullptr if none exists.
-  BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const;
+  BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
 
   /// Allocate an uninitialized TypeSourceInfo.
   ///
@@ -3444,19 +3481,14 @@ class ASTContext : public RefCountedBase<ASTContext> {
   V(EncodingProperty, 3)                                                       \
   V(IsStructField, 4)                                                          \
   V(EncodeBlockParameters, 5)                                                  \
-  V(EncodeClassNames, 6)
+  V(EncodeClassNames, 6)                                                       \
 
-#define V(N, I)                                                                \
-  ObjCEncOptions &set##N() {                                                   \
-    Bits |= 1 << I;                                                            \
-    return *this;                                                              \
-  }
-    OPT_LIST(V)
+#define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
+OPT_LIST(V)
 #undef V
 
-#define V(N, I)                                                                \
-  bool N() const { return Bits & 1 << I; }
-    OPT_LIST(V)
+#define V(N,I) bool N() const { return Bits & 1 << I; }
+OPT_LIST(V)
 #undef V
 
 #undef OPT_LIST
@@ -3466,8 +3498,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
     }
 
     [[nodiscard]] ObjCEncOptions forComponentType() const {
-      ObjCEncOptions Mask =
-          ObjCEncOptions().setIsOutermostType().setIsStructField();
+      ObjCEncOptions Mask = ObjCEncOptions()
+                                .setIsOutermostType()
+                                .setIsStructField();
       return Bits & ~Mask.Bits;
     }
   };
@@ -3482,12 +3515,13 @@ class ASTContext : public RefCountedBase<ASTContext> {
   void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
                                        const FieldDecl *Field,
                                        bool includeVBases = true,
-                                       QualType *NotEncodedT = nullptr) const;
+                                       QualType *NotEncodedT=nullptr) const;
 
 public:
   // Adds the encoding of a method parameter or return type.
-  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T,
-                                         std::string &S, bool Extended) const;
+  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
+                                         QualType T, std::string& S,
+                                         bool Extended) const;
 
   /// Returns true if this is an inline-initialized static data member
   /// which is treated as a definition for MSVC compatibility.
@@ -3681,7 +3715,7 @@ inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
 /// @param Alignment The alignment of the allocated memory (if the underlying
 ///                  allocator supports it).
 /// @return The allocated memory. Could be nullptr.
-inline void *operator new[](size_t Bytes, const clang::ASTContext &C,
+inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
                             size_t Alignment /* = 8 */) {
   return C.Allocate(Bytes, Alignment);
 }
@@ -3700,8 +3734,8 @@ inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
 template <typename Owner, typename T,
           void (clang::ExternalASTSource::*Update)(Owner)>
 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
-clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
-    const clang::ASTContext &Ctx, T Value) {
+    clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
+        const clang::ASTContext &Ctx, T Value) {
   // Note, this is implemented here so that ExternalASTSource.h doesn't need to
   // include ASTContext.h. We explicitly instantiate it for all relevant types
   // in ASTContext.cpp.
diff --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index a15fd1a0fca01..ac7658276ec37 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -13,6 +13,7 @@
 #include "clang/CIR/Dialect/IR/CIRAttrs.h"
 #include "clang/CIR/Dialect/IR/CIRDialect.h"
 #include "clang/CIR/Dialect/IR/CIRTypes.h"
+#include "llvm/ADT/STLForwardCompat.h"
 #include "llvm/Support/ErrorHandling.h"
 
 #include "mlir/IR/Builders.h"
@@ -22,6 +23,35 @@
 
 namespace cir {
 
+enum class OverflowBehavior {
+  None = 0,
+  NoSignedWrap = 1 << 0,
+  NoUnsignedWrap = 1 << 1,
+  Saturated = 1 << 2,
+};
+
+constexpr OverflowBehavior operator|(OverflowBehavior a, OverflowBehavior b) {
+  return static_cast<OverflowBehavior>(llvm::to_underlying(a) |
+                                       llvm::to_underlying(b));
+}
+
+constexpr OverflowBehavior operator&(OverflowBehavior a, OverflowBehavior b) {
+  return static_cast<OverflowBehavior>(llvm::to_underlying(a) &
+                                       llvm::to_underlying(b));
+}
+
+constexpr OverflowBehavior &operator|=(OverflowBehavior &a,
+                                       OverflowBehavior b) {
+  a = a | b;
+  return a;
+}
+
+constexpr OverflowBehavior &operator&=(OverflowBehavior &a,
+                                       OverflowBehavior b) {
+  a = a & b;
+  return a;
+}
+
 class CIRBaseBuilderTy : public mlir::OpBuilder {
 
 public:
@@ -148,6 +178,10 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
     return createCast(loc, cir::CastKind::bitcast, src, newTy);
   }
 
+  //===--------------------------------------------------------------------===//
+  // Binary Operators
+  //===--------------------------------------------------------------------===//
+
   mlir::Value createBinop(mlir::Location loc, mlir::Value lhs,
                           cir::BinOpKind kind, mlir::Value rhs) {
     return create<cir::BinOp>(loc, lhs.getType(), kind, lhs, rhs);
@@ -169,61 +203,66 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
   }
 
   mlir::Value createMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
-                        bool hasNUW = false, bool hasNSW = false) {
+                        OverflowBehavior ob = OverflowBehavior::None) {
     auto op =
         create<cir::BinOp>(loc, lhs.getType(), cir::BinOpKind::Mul, lhs, rhs);
-    op.setNoUnsignedWrap(hasNUW);
-    op.setNoSignedWrap(hasNSW);
+    op.setNoUnsignedWrap(
+        llvm::to_underlying(ob & OverflowBehavior::NoUnsignedWrap));
+    op.setNoSignedWrap(
+        llvm::to_underlying(ob & OverflowBehavior::NoSignedWrap));
     return op;
   }
   mlir::Value createNSWMul(mlir::Location loc, mlir::Value lhs,
                            mlir::Value rhs) {
-    return createMul(loc, lhs, rhs, false, true);
+    return createMul(loc, lhs, rhs, OverflowBehavior::NoSignedWrap);
   }
   mlir::Value createNUWAMul(mlir::Location loc, mlir::Value lhs,
                             mlir::Value rhs) {
-    return createMul(loc, lhs, rhs, true, false);
+    return createMul(loc, lhs, rhs, OverflowBehavior::NoUnsignedWrap);
   }
 
   mlir::Value createSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
-                        bool hasNUW = false, bool hasNSW = false,
-                        bool saturated = false) {
+                        OverflowBehavior ob = OverflowBehavior::Saturated) {
     auto op =
         create<cir::BinOp>(loc, lhs.getType(), cir::BinOpKind::Sub, lhs, rhs);
-    op.setNoUnsignedWrap(hasNUW);
-    op.setNoSignedWrap(hasNSW);
-    op.setSaturated(saturated);
+    op.setNoUnsignedWrap(
+        llvm::to_underlying(ob & OverflowBehavior::NoUnsignedWrap));
+    op.setNoSignedWrap(
+        llvm::to_underlying(ob & OverflowBehavior::NoSignedWrap));
+    op.setSaturated(llvm::to_underlying(ob & OverflowBehavior::Saturated));
     return op;
   }
 
   mlir::Value createNSWSub(mlir::Location loc, mlir::Value lhs,
                            mlir::Value rhs) {
-    return createSub(loc, lhs, rhs, false, true);
+    return createSub(loc, lhs, rhs, OverflowBehavior::NoSignedWrap);
   }
 
   mlir::Value createNUWSub(mlir::Location loc, mlir::Value lhs,
                            mlir::Value rhs) {
-    return createSub(loc, lhs, rhs, true, false);
+    return createSub(loc, lhs, rhs, OverflowBehavior::NoUnsignedWrap);
   }
 
   mlir::Value createAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
-                        bool hasNUW = false, bool hasNSW = false,
-                        bool saturated = false) {
+                        OverflowBehavior ob = OverflowBehavior::None) {
     auto op =
         create<cir::BinOp>(loc, lhs.getType(), cir::BinOpKind::Add, lhs, rhs);
-    op.setNoUnsignedWrap(hasNUW);
-    op.setNoSignedWrap(hasNSW);
-    op.setSaturated(saturated);
+    op.setNoUnsignedWrap(
+        llvm::to_underlying(ob & OverflowBehavior::NoUnsignedWrap));
+    op.setNoSignedWrap(
+        llvm::to_underlying(ob & OverflowBehavior::NoSignedWrap));
+    op.setSaturated(llvm::to_underlying(ob & OverflowBehavior::Saturated));
     return op;
   }
 
   mlir::Value createNSWAdd(mlir::Location loc, mlir::Value lhs,
                            mlir::Value rhs) {
-    return createAdd(loc, lhs, rhs, false, true);
+    return createAdd(loc, lhs, rhs, OverflowBehavior::NoSignedWrap);
   }
+
   mlir::Value createNUWAdd(mlir::Location loc, mlir::Value lhs,
                            mlir::Value rhs) {
-    return createAdd(loc, lhs, rhs, true, false);
+    return createAdd(loc, lhs, rhs, OverflowBehavior::NoUnsignedWrap);
   }
 
   //
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 02491edfa6c28..5b882b10d423b 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -162,7 +162,8 @@ getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr) {
 
   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
-    if (TSK == TSK_ImplicitInstantiation || TSK == TSK_Undeclared)
+    if (TSK == TSK_ImplicitInstantiation ||
+        TSK == TSK_Undeclared)
       return {};
   }
 
@@ -182,7 +183,8 @@ getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr) {
 
   // TODO: we could look up template parameter documentation in the template
   // documentation.
-  if (isa<TemplateTypeParmDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
+  if (isa<TemplateTypeParmDecl>(D) ||
+      isa<NonTypeTemplateParmDecl>(D) ||
       isa<TemplateTemplateParmDecl>(D))
     return {};
 
@@ -291,8 +293,8 @@ RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
 
   // Get the corresponding buffer.
   bool Invalid = false;
-  const char *Buffer =
-      SourceMgr.getBufferData(DeclLocDecomp.first, &Invalid).data();
+  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
+                                               &Invalid).data();
   if (Invalid)
     return nullptr;
 
@@ -417,9 +419,9 @@ static const Decl &adjustDeclToTemplate(const Decl &D) {
   return D;
 }
 
-const RawComment *
-ASTContext::getRawCommentForAnyRedecl(const Decl *D,
-                                      const Decl **OriginalDecl) const {
+const RawComment *ASTContext::getRawCommentForAnyRedecl(
+                                                const Decl *D,
+                                                const Decl **OriginalDecl) const {
   if (!D) {
     if (OriginalDecl)
       OriginalDecl = nullptr;
@@ -508,9 +510,8 @@ void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
   CommentlessRedeclChains.erase(CanonicalDecl);
 }
 
-static void
-addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
-                     SmallVectorImpl<const NamedDecl *> &Redeclared) {
+static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
+                   SmallVectorImpl<const NamedDecl *> &Redeclared) {
   const DeclContext *DC = ObjCMethod->getDeclContext();
   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
@@ -518,8 +519,9 @@ addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
       return;
     // Add redeclared method here.
     for (const auto *Ext : ID->known_extensions()) {
-      if (ObjCMethodDecl *RedeclaredMethod = Ext->getMethod(
-              ObjCMethod->getSelector(), ObjCMethod->isInstanceMethod()))
+      if (ObjCMethodDecl *RedeclaredMethod =
+            Ext->getMethod(ObjCMethod->getSelector(),
+                                  ObjCMethod->isInstanceMethod()))
         Redeclared.push_back(RedeclaredMethod);
     }
   }
@@ -597,18 +599,19 @@ comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
   if (!ThisDeclInfo->TemplateParameters)
     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
   comments::FullComment *CFC =
-      new (*this) comments::FullComment(FC->getBlocks(), ThisDeclInfo);
+    new (*this) comments::FullComment(FC->getBlocks(),
+                                      ThisDeclInfo);
   return CFC;
 }
 
-comments::FullComment *
-ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
+comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
   const RawComment *RC = getRawCommentForDeclNoCache(D);
   return RC ? RC->parse(*this, nullptr, D) : nullptr;
 }
 
-comments::FullComment *
-ASTContext::getCommentForDecl(const Decl *D, const Preprocessor *PP) const {
+comments::FullComment *ASTContext::getCommentForDecl(
+                                              const Decl *D,
+                                              const Preprocessor *PP) const {
   if (!D || D->isInvalidDecl())
     return nullptr;
   D = &adjustDeclToTemplate(*D);
@@ -631,7 +634,7 @@ ASTContext::getCommentForDecl(const Decl *D, const Preprocessor *PP) const {
   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
   if (!RC) {
     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
-      SmallVector<const NamedDecl *, 8> Overridden;
+      SmallVector<const NamedDecl*, 8> Overridden;
       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
       if (OMD && OMD->isPropertyAccessor())
         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
@@ -643,7 +646,8 @@ ASTContext::getCommentForDecl(const Decl *D, const Preprocessor *PP) const {
       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
           return cloneFullComment(FC, D);
-    } else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
+    }
+    else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
       // Attach any tag type's documentation to its typedef if latter
       // does not have one of its own.
       QualType QT = TD->getUnderlyingType();
@@ -651,17 +655,20 @@ ASTContext::getCommentForDecl(const Decl *D, const Preprocessor *PP) const {
         if (const Decl *TD = TT->getDecl())
           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
             return cloneFullComment(FC, D);
-    } else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
+    }
+    else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
       while (IC->getSuperClass()) {
         IC = IC->getSuperClass();
         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
           return cloneFullComment(FC, D);
       }
-    } else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
+    }
+    else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
           return cloneFullComment(FC, D);
-    } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
+    }
+    else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
       if (!(RD = RD->getDefinition()))
         return nullptr;
       // Check non-virtual bases.
@@ -672,11 +679,10 @@ ASTContext::getCommentForDecl(const Decl *D, const Preprocessor *PP) const {
         if (Ty.isNull())
           continue;
         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
-          if (!(NonVirtualBase = NonVirtualBase->getDefinition()))
+          if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
             continue;
 
-          if (comments::FullComment *FC =
-                  getCommentForDecl((NonVirtualBase), PP))
+          if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
             return cloneFullComment(FC, D);
         }
       }
@@ -688,7 +694,7 @@ ASTContext::getCommentForDecl(const Decl *D, const Preprocessor *PP) const {
         if (Ty.isNull())
           continue;
         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
-          if (!(VirtualBase = VirtualBase->getDefinition()))
+          if (!(VirtualBase= VirtualBase->getDefinition()))
             continue;
           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
             return cloneFullComment(FC, D);
@@ -710,9 +716,10 @@ ASTContext::getCommentForDecl(const Decl *D, const Preprocessor *PP) const {
   return FC;
 }
 
-void ASTContext::CanonicalTemplateTemplateParm::Profile(
-    llvm::FoldingSetNodeID &ID, const ASTContext &C,
-    TemplateTemplateParmDecl *Parm) {
+void
+ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
+                                                   const ASTContext &C,
+                                               TemplateTemplateParmDecl *Parm) {
   ID.AddInteger(Parm->getDepth());
   ID.AddInteger(Parm->getPosition());
   ID.AddBoolean(Parm->isParameterPack());
@@ -720,7 +727,7 @@ void ASTContext::CanonicalTemplateTemplateParm::Profile(
   TemplateParameterList *Params = Parm->getTemplateParameters();
   ID.AddInteger(Params->size());
   for (TemplateParameterList::const_iterator P = Params->begin(),
-                                             PEnd = Params->end();
+                                          PEnd = Params->end();
        P != PEnd; ++P) {
     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
       ID.AddInteger(0);
@@ -756,14 +763,15 @@ void ASTContext::CanonicalTemplateTemplateParm::Profile(
   }
 }
 
-TemplateTemplateParmDecl *ASTContext::getCanonicalTemplateTemplateParmDecl(
-    TemplateTemplateParmDecl *TTP) const {
+TemplateTemplateParmDecl *
+ASTContext::getCanonicalTemplateTemplateParmDecl(
+                                          TemplateTemplateParmDecl *TTP) const {
   // Check if we already have a canonical template template parameter.
   llvm::FoldingSetNodeID ID;
   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
   void *InsertPos = nullptr;
-  CanonicalTemplateTemplateParm *Canonical =
-      CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
+  CanonicalTemplateTemplateParm *Canonical
+    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
   if (Canonical)
     return Canonical->getParam();
 
@@ -772,7 +780,7 @@ TemplateTemplateParmDecl *ASTContext::getCanonicalTemplateTemplateParmDecl(
   SmallVector<NamedDecl *, 4> CanonParams;
   CanonParams.reserve(Params->size());
   for (TemplateParameterList::const_iterator P = Params->begin(),
-                                             PEnd = Params->end();
+                                          PEnd = Params->end();
        P != PEnd; ++P) {
     // Note that, per C++20 [temp.over.link]/6, when determining whether
     // template-parameters are equivalent, constraints are ignored.
@@ -795,23 +803,32 @@ TemplateTemplateParmDecl *ASTContext::getCanonicalTemplateTemplateParmDecl(
         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
           ExpandedTInfos.push_back(
-              getTrivialTypeSourceInfo(ExpandedTypes.back()));
+                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
         }
 
-        Param = NonTypeTemplateParmDecl::Create(
-            *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
-            NTTP->getDepth(), NTTP->getPosition(), nullptr, T, TInfo,
-            ExpandedTypes, ExpandedTInfos);
+        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
+                                                SourceLocation(),
+                                                SourceLocation(),
+                                                NTTP->getDepth(),
+                                                NTTP->getPosition(), nullptr,
+                                                T,
+                                                TInfo,
+                                                ExpandedTypes,
+                                                ExpandedTInfos);
       } else {
-        Param = NonTypeTemplateParmDecl::Create(
-            *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
-            NTTP->getDepth(), NTTP->getPosition(), nullptr, T,
-            NTTP->isParameterPack(), TInfo);
+        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
+                                                SourceLocation(),
+                                                SourceLocation(),
+                                                NTTP->getDepth(),
+                                                NTTP->getPosition(), nullptr,
+                                                T,
+                                                NTTP->isParameterPack(),
+                                                TInfo);
       }
       CanonParams.push_back(Param);
     } else
       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
-          cast<TemplateTemplateParmDecl>(*P)));
+                                           cast<TemplateTemplateParmDecl>(*P)));
   }
 
   TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
@@ -847,8 +864,7 @@ TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
 }
 
 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
-  if (!LangOpts.CPlusPlus)
-    return nullptr;
+  if (!LangOpts.CPlusPlus) return nullptr;
 
   switch (getCXXABIKind()) {
   case TargetCXXABI::AppleARM64:
@@ -942,18 +958,16 @@ void ASTContext::cleanup() {
       R->Destroy(*this);
   ObjCLayouts.clear();
 
-  for (llvm::DenseMap<const RecordDecl *, const ASTRecordLayout *>::iterator
-           I = ASTRecordLayouts.begin(),
-           E = ASTRecordLayouts.end();
-       I != E;) {
+  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
+       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
     // Increment in loop to prevent using deallocated memory.
     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
       R->Destroy(*this);
   }
   ASTRecordLayouts.clear();
 
-  for (llvm::DenseMap<const Decl *, AttrVec *>::iterator A = DeclAttrs.begin(),
-                                                         AEnd = DeclAttrs.end();
+  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
+                                                    AEnd = DeclAttrs.end();
        A != AEnd; ++A)
     A->second->~AttrVec();
   DeclAttrs.clear();
@@ -974,8 +988,8 @@ void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
   Deallocations.push_back({Callback, Data});
 }
 
-void ASTContext::setExternalSource(
-    IntrusiveRefCntPtr<ExternalASTSource> Source) {
+void
+ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
   ExternalSource = std::move(Source);
 }
 
@@ -987,7 +1001,7 @@ void ASTContext::PrintStats() const {
 #define TYPE(Name, Parent) 0,
 #define ABSTRACT_TYPE(Name, Parent)
 #include "clang/AST/TypeNodes.inc"
-      0 // Extra
+    0 // Extra
   };
 
   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
@@ -997,12 +1011,13 @@ void ASTContext::PrintStats() const {
 
   unsigned Idx = 0;
   unsigned TotalBytes = 0;
-#define TYPE(Name, Parent)                                                     \
-  if (counts[Idx])                                                             \
-    llvm::errs() << "    " << counts[Idx] << " " << #Name << " types, "        \
-                 << sizeof(Name##Type) << " each "                             \
-                 << "(" << counts[Idx] * sizeof(Name##Type) << " bytes)\n";    \
-  TotalBytes += counts[Idx] * sizeof(Name##Type);                              \
+#define TYPE(Name, Parent)                                              \
+  if (counts[Idx])                                                      \
+    llvm::errs() << "    " << counts[Idx] << " " << #Name               \
+                 << " types, " << sizeof(Name##Type) << " each "        \
+                 << "(" << counts[Idx] * sizeof(Name##Type)             \
+                 << " bytes)\n";                                        \
+  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
   ++Idx;
 #define ABSTRACT_TYPE(Name, Parent)
 #include "clang/AST/TypeNodes.inc"
@@ -1028,7 +1043,8 @@ void ASTContext::PrintStats() const {
                  << NumImplicitMoveAssignmentOperators
                  << " implicit move assignment operators created\n";
   llvm::errs() << NumImplicitDestructorsDeclared << "/"
-               << NumImplicitDestructors << " implicit destructors created\n";
+               << NumImplicitDestructors
+               << " implicit destructors created\n";
 
   if (ExternalSource) {
     llvm::errs() << "\n";
@@ -1054,7 +1070,7 @@ void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
     return;
 
   auto &Merged = It->second;
-  llvm::DenseSet<Module *> Found;
+  llvm::DenseSet<Module*> Found;
   for (Module *&M : Merged)
     if (!Found.insert(M).second)
       M = nullptr;
@@ -1118,8 +1134,8 @@ void ASTContext::addLazyModuleInitializers(Module *M,
   auto *&Inits = ModuleInitializers[M];
   if (!Inits)
     Inits = new (*this) PerModuleInitializers;
-  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), IDs.begin(),
-                                 IDs.end());
+  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
+                                 IDs.begin(), IDs.end());
 }
 
 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
@@ -1166,8 +1182,7 @@ bool ASTContext::isInSameModule(const Module *M1, const Module *M2) {
 
 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
   if (!ExternCContext)
-    ExternCContext =
-        ExternCContextDecl::Create(*this, getTranslationUnitDecl());
+    ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
 
   return ExternCContext;
 }
@@ -1249,78 +1264,78 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
 
   // C99 6.2.5p19.
-  InitBuiltinType(VoidTy, BuiltinType::Void);
+  InitBuiltinType(VoidTy,              BuiltinType::Void);
 
   // C99 6.2.5p2.
-  InitBuiltinType(BoolTy, BuiltinType::Bool);
+  InitBuiltinType(BoolTy,              BuiltinType::Bool);
   // C99 6.2.5p3.
   if (LangOpts.CharIsSigned)
-    InitBuiltinType(CharTy, BuiltinType::Char_S);
+    InitBuiltinType(CharTy,            BuiltinType::Char_S);
   else
-    InitBuiltinType(CharTy, BuiltinType::Char_U);
+    InitBuiltinType(CharTy,            BuiltinType::Char_U);
   // C99 6.2.5p4.
-  InitBuiltinType(SignedCharTy, BuiltinType::SChar);
-  InitBuiltinType(ShortTy, BuiltinType::Short);
-  InitBuiltinType(IntTy, BuiltinType::Int);
-  InitBuiltinType(LongTy, BuiltinType::Long);
-  InitBuiltinType(LongLongTy, BuiltinType::LongLong);
+  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
+  InitBuiltinType(ShortTy,             BuiltinType::Short);
+  InitBuiltinType(IntTy,               BuiltinType::Int);
+  InitBuiltinType(LongTy,              BuiltinType::Long);
+  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
 
   // C99 6.2.5p6.
-  InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
-  InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
-  InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
-  InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
-  InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
+  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
+  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
+  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
+  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
+  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
 
   // C99 6.2.5p10.
-  InitBuiltinType(FloatTy, BuiltinType::Float);
-  InitBuiltinType(DoubleTy, BuiltinType::Double);
-  InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
+  InitBuiltinType(FloatTy,             BuiltinType::Float);
+  InitBuiltinType(DoubleTy,            BuiltinType::Double);
+  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
 
   // GNU extension, __float128 for IEEE quadruple precision
-  InitBuiltinType(Float128Ty, BuiltinType::Float128);
+  InitBuiltinType(Float128Ty,          BuiltinType::Float128);
 
   // __ibm128 for IBM extended precision
   InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
 
   // C11 extension ISO/IEC TS 18661-3
-  InitBuiltinType(Float16Ty, BuiltinType::Float16);
+  InitBuiltinType(Float16Ty,           BuiltinType::Float16);
 
   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
-  InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
-  InitBuiltinType(AccumTy, BuiltinType::Accum);
-  InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
-  InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
-  InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
-  InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
-  InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
-  InitBuiltinType(FractTy, BuiltinType::Fract);
-  InitBuiltinType(LongFractTy, BuiltinType::LongFract);
-  InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
-  InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
-  InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
-  InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
-  InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
-  InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
+  InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
+  InitBuiltinType(AccumTy,                 BuiltinType::Accum);
+  InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
+  InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
+  InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
+  InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
+  InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
+  InitBuiltinType(FractTy,                 BuiltinType::Fract);
+  InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
+  InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
+  InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
+  InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
+  InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
+  InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
+  InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
-  InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
-  InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
-  InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
-  InitBuiltinType(SatFractTy, BuiltinType::SatFract);
-  InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
+  InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
+  InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
+  InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
+  InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
+  InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
-  InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
-  InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
+  InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
+  InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
 
   // GNU extension, 128-bit integers.
-  InitBuiltinType(Int128Ty, BuiltinType::Int128);
-  InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
+  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
+  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
 
   // C++ 3.9.1p5
   if (TargetInfo::isTypeSigned(Target.getWCharType()))
-    InitBuiltinType(WCharTy, BuiltinType::WChar_S);
-  else // -fshort-wchar makes wchar_t be unsigned.
-    InitBuiltinType(WCharTy, BuiltinType::WChar_U);
+    InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
+  else  // -fshort-wchar makes wchar_t be unsigned.
+    InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
   if (LangOpts.CPlusPlus && LangOpts.WChar)
     WideCharTy = WCharTy;
   else {
@@ -1331,15 +1346,15 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   WIntTy = getFromTargetType(Target.getWIntType());
 
   // C++20 (proposed)
-  InitBuiltinType(Char8Ty, BuiltinType::Char8);
+  InitBuiltinType(Char8Ty,              BuiltinType::Char8);
 
   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
-    InitBuiltinType(Char16Ty, BuiltinType::Char16);
+    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
   else // C99
     Char16Ty = getFromTargetType(Target.getChar16Type());
 
   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
-    InitBuiltinType(Char32Ty, BuiltinType::Char32);
+    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
   else // C99
     Char32Ty = getFromTargetType(Target.getChar32Type());
 
@@ -1348,28 +1363,28 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   // DependentTy and users should never see it; however, it is here to
   // help diagnose failures to properly check for type-dependent
   // expressions.
-  InitBuiltinType(DependentTy, BuiltinType::Dependent);
+  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
 
   // Placeholder type for functions.
-  InitBuiltinType(OverloadTy, BuiltinType::Overload);
+  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
 
   // Placeholder type for bound members.
-  InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
+  InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
 
   // Placeholder type for unresolved templates.
   InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
 
   // Placeholder type for pseudo-objects.
-  InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
+  InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
 
   // "any" type; useful for debugger-like clients.
-  InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
+  InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
 
   // Placeholder type for unbridged ARC casts.
-  InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
+  InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
 
   // Placeholder type for builtin functions.
-  InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
+  InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
 
   // Placeholder type for OMP array sections.
   if (LangOpts.OpenMP) {
@@ -1391,8 +1406,8 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
 
   if (LangOpts.OpenCL) {
-#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
-  InitBuiltinType(SingletonId, BuiltinType::Id);
+#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
+    InitBuiltinType(SingletonId, BuiltinType::Id);
 #include "clang/Basic/OpenCLImageTypes.def"
 
     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
@@ -1401,8 +1416,8 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
 
-#define EXT_OPAQUE_TYPE(ExtType, Id, Ext)                                      \
-  InitBuiltinType(Id##Ty, BuiltinType::Id);
+#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
+    InitBuiltinType(Id##Ty, BuiltinType::Id);
 #include "clang/Basic/OpenCLExtensionTypes.def"
   }
 
@@ -1414,17 +1429,17 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
 
   if (Target.hasAArch64SVETypes() ||
       (AuxTarget && AuxTarget->hasAArch64SVETypes())) {
-#define SVE_TYPE(Name, Id, SingletonId)                                        \
-  InitBuiltinType(SingletonId, BuiltinType::Id);
+#define SVE_TYPE(Name, Id, SingletonId) \
+    InitBuiltinType(SingletonId, BuiltinType::Id);
 #include "clang/Basic/AArch64SVEACLETypes.def"
   }
 
   if (Target.getTriple().isPPC64()) {
-#define PPC_VECTOR_MMA_TYPE(Name, Id, Size)                                    \
-  InitBuiltinType(Id##Ty, BuiltinType::Id);
+#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
+      InitBuiltinType(Id##Ty, BuiltinType::Id);
 #include "clang/Basic/PPCTypes.def"
-#define PPC_VECTOR_VSX_TYPE(Name, Id, Size)                                    \
-  InitBuiltinType(Id##Ty, BuiltinType::Id);
+#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
+    InitBuiltinType(Id##Ty, BuiltinType::Id);
 #include "clang/Basic/PPCTypes.def"
   }
 
@@ -1448,8 +1463,8 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   }
 
   // Builtin type for __objc_yes and __objc_no
-  ObjCBuiltinBoolTy =
-      (Target.useSignedCharForObjCBool() ? SignedCharTy : BoolTy);
+  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
+                       SignedCharTy : BoolTy);
 
   ObjCConstantStringType = QualType();
 
@@ -1459,14 +1474,14 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   if (LangOpts.OpenCLGenericAddressSpace) {
     auto Q = VoidTy.getQualifiers();
     Q.setAddressSpace(LangAS::opencl_generic);
-    VoidPtrTy = getPointerType(
-        getCanonicalType(getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
+    VoidPtrTy = getPointerType(getCanonicalType(
+        getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
   } else {
     VoidPtrTy = getPointerType(VoidTy);
   }
 
   // nullptr type (C++0x 2.14.7)
-  InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
+  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
 
   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
   InitBuiltinType(HalfTy, BuiltinType::Half);
@@ -1487,7 +1502,7 @@ DiagnosticsEngine &ASTContext::getDiagnostics() const {
   return SourceMgr.getDiagnostics();
 }
 
-AttrVec &ASTContext::getDeclAttrs(const Decl *D) {
+AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
   AttrVec *&Result = DeclAttrs[D];
   if (!Result) {
     void *Mem = Allocate(sizeof(AttrVec));
@@ -1499,7 +1514,7 @@ AttrVec &ASTContext::getDeclAttrs(const Decl *D) {
 
 /// Erase the attributes corresponding to the given declaration.
 void ASTContext::eraseDeclAttrs(const Decl *D) {
-  llvm::DenseMap<const Decl *, AttrVec *>::iterator Pos = DeclAttrs.find(D);
+  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
   if (Pos != DeclAttrs.end()) {
     Pos->second->~AttrVec();
     DeclAttrs.erase(Pos);
@@ -1524,32 +1539,37 @@ ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
   return Pos->second;
 }
 
-void ASTContext::setInstantiatedFromStaticDataMember(
-    VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK,
-    SourceLocation PointOfInstantiation) {
+void
+ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
+                                                TemplateSpecializationKind TSK,
+                                          SourceLocation PointOfInstantiation) {
   assert(Inst->isStaticDataMember() && "Not a static data member");
   assert(Tmpl->isStaticDataMember() && "Not a static data member");
   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
                                             Tmpl, TSK, PointOfInstantiation));
 }
 
-void ASTContext::setTemplateOrSpecializationInfo(
-    VarDecl *Inst, TemplateOrSpecializationInfo TSI) {
+void
+ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
+                                            TemplateOrSpecializationInfo TSI) {
   assert(!TemplateOrInstantiation[Inst] &&
          "Already noted what the variable was instantiated from");
   TemplateOrInstantiation[Inst] = TSI;
 }
 
-NamedDecl *ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
+NamedDecl *
+ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
   return InstantiatedFromUsingDecl.lookup(UUD);
 }
 
-void ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst,
-                                              NamedDecl *Pattern) {
-  assert((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) ||
+void
+ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
+  assert((isa<UsingDecl>(Pattern) ||
+          isa<UnresolvedUsingValueDecl>(Pattern) ||
           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
          "pattern decl is not a using decl");
-  assert((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) ||
+  assert((isa<UsingDecl>(Inst) ||
+          isa<UnresolvedUsingValueDecl>(Inst) ||
           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
          "instantiation did not produce a using decl");
   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
@@ -1572,8 +1592,9 @@ ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
   return InstantiatedFromUsingShadowDecl.lookup(Inst);
 }
 
-void ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
-                                                    UsingShadowDecl *Pattern) {
+void
+ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
+                                               UsingShadowDecl *Pattern) {
   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
 }
@@ -1627,7 +1648,8 @@ void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
 }
 
 void ASTContext::getOverriddenMethods(
-    const NamedDecl *D, SmallVectorImpl<const NamedDecl *> &Overridden) const {
+                      const NamedDecl *D,
+                      SmallVectorImpl<const NamedDecl *> &Overridden) const {
   assert(D);
 
   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
@@ -1675,10 +1697,8 @@ const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
     return Target->getHalfFormat();
   case BuiltinType::Half:
     return Target->getHalfFormat();
-  case BuiltinType::Float:
-    return Target->getFloatFormat();
-  case BuiltinType::Double:
-    return Target->getDoubleFormat();
+  case BuiltinType::Float:      return Target->getFloatFormat();
+  case BuiltinType::Double:     return Target->getDoubleFormat();
   case BuiltinType::Ibm128:
     return Target->getIbm128Format();
   case BuiltinType::LongDouble:
@@ -1818,12 +1838,13 @@ TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
 
 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
-TypeInfoChars static getConstantArrayInfoInChars(const ASTContext &Context,
-                                                 const ConstantArrayType *CAT) {
+TypeInfoChars
+static getConstantArrayInfoInChars(const ASTContext &Context,
+                                   const ConstantArrayType *CAT) {
   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
   uint64_t Size = CAT->getZExtSize();
   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
-                           (uint64_t)(-1) / Size) &&
+              (uint64_t)(-1)/Size) &&
          "Overflow in array type char size evaluation");
   uint64_t Width = EltInfo.Width.getQuantity() * Size;
   unsigned Align = EltInfo.Align.getQuantity();
@@ -1947,8 +1968,8 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
   case Type::Class:                                                            \
-    assert(!T->isDependentType() && "should not see dependent types here");    \
-    return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
+  assert(!T->isDependentType() && "should not see dependent types here");      \
+  return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
 #include "clang/AST/TypeNodes.inc"
     llvm_unreachable("Should not see dependent types");
 
@@ -1993,7 +2014,7 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
 
     // If the alignment is not a power of 2, round up to the next power of 2.
     // This happens for non-power-of-2 length vectors.
-    if (Align & (Align - 1)) {
+    if (Align & (Align-1)) {
       Align = llvm::bit_ceil(Align);
       Width = llvm::alignTo(Width, Align);
     }
@@ -2031,8 +2052,7 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
 
   case Type::Builtin:
     switch (cast<BuiltinType>(T)->getKind()) {
-    default:
-      llvm_unreachable("Unknown builtin type!");
+    default: llvm_unreachable("Unknown builtin type!");
     case BuiltinType::Void:
       // GCC extension: alignof(void) = 8 bits.
       Width = 0;
@@ -2206,23 +2226,24 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
     case BuiltinType::OCLClkEvent:
     case BuiltinType::OCLQueue:
     case BuiltinType::OCLReserveID:
-#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
-  case BuiltinType::Id:
+#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
+    case BuiltinType::Id:
 #include "clang/Basic/OpenCLImageTypes.def"
-#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
+#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
+  case BuiltinType::Id:
 #include "clang/Basic/OpenCLExtensionTypes.def"
       AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
       Width = Target->getPointerWidth(AS);
       Align = Target->getPointerAlign(AS);
       break;
-      // The SVE types are effectively target-specific.  The length of an
-      // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
-      // of 128 bits.  There is one predicate bit for each vector byte, so the
-      // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
-      //
-      // Because the length is only known at runtime, we use a dummy value
-      // of 0 for the static length.  The alignment values are those defined
-      // by the Procedure Call Standard for the Arm Architecture.
+    // The SVE types are effectively target-specific.  The length of an
+    // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
+    // of 128 bits.  There is one predicate bit for each vector byte, so the
+    // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
+    //
+    // Because the length is only known at runtime, we use a dummy value
+    // of 0 for the static length.  The alignment values are those defined
+    // by the Procedure Call Standard for the Arm Architecture.
 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId)                    \
   case BuiltinType::Id:                                                        \
     Width = 0;                                                                 \
@@ -2374,8 +2395,8 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
   }
 
   case Type::SubstTemplateTypeParm:
-    return getTypeInfo(
-        cast<SubstTemplateTypeParmType>(T)->getReplacementType().getTypePtr());
+    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
+                       getReplacementType().getTypePtr());
 
   case Type::Auto:
   case Type::DeducedTemplateSpecialization: {
@@ -2420,7 +2441,7 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
 
   case Type::Attributed:
     return getTypeInfo(
-        cast<AttributedType>(T)->getEquivalentType().getTypePtr());
+                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
 
   case Type::CountAttributed:
     return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
@@ -2455,7 +2476,8 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
       // Set the alignment equal to the size.
       Align = static_cast<unsigned>(Width);
     }
-  } break;
+  }
+  break;
 
   case Type::Pipe:
     Width = Target->getPointerWidth(LangAS::opencl_global);
@@ -2631,7 +2653,7 @@ CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
   const ValueDecl *MPD = MP.getMemberPointerDecl();
   CharUnits ThisAdjustment = CharUnits::Zero();
-  ArrayRef<const CXXRecordDecl *> Path = MP.getMemberPointerPath();
+  ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
   bool DerivedMember = MP.isMemberPointerToDerivedMember();
   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
@@ -2652,9 +2674,9 @@ CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
 /// super class and then collects all ivars, including those synthesized for
 /// current class. This routine is used for implementation of current class
 /// when all ivars, declared and synthesized are known.
-void ASTContext::DeepCollectObjCIvars(
-    const ObjCInterfaceDecl *OI, bool leafClass,
-    SmallVectorImpl<const ObjCIvarDecl *> &Ivars) const {
+void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
+                                      bool leafClass,
+                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
     DeepCollectObjCIvars(SuperClass, false, Ivars);
   if (!leafClass) {
@@ -2662,15 +2684,15 @@ void ASTContext::DeepCollectObjCIvars(
   } else {
     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
-         Iv = Iv->getNextIvar())
+         Iv= Iv->getNextIvar())
       Ivars.push_back(Iv);
   }
 }
 
 /// CollectInheritedProtocols - Collect all protocols in current class and
 /// those inherited by it.
-void ASTContext::CollectInheritedProtocols(
-    const Decl *CDecl, llvm::SmallPtrSet<ObjCProtocolDecl *, 8> &Protocols) {
+void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
+                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
     // We can use protocol_iterator here instead of
     // all_referenced_protocol_iterator since we are walking all categories.
@@ -2693,9 +2715,8 @@ void ASTContext::CollectInheritedProtocols(
     }
   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
     // Insert the protocol.
-    if (!Protocols
-             .insert(const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl()))
-             .second)
+    if (!Protocols.insert(
+          const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
       return;
 
     for (auto *Proto : OP->protocols())
@@ -2946,27 +2967,24 @@ bool ASTContext::isSentinelNullExpr(const Expr *E) {
     return false;
 
   // nullptr_t is always treated as null.
-  if (E->getType()->isNullPtrType())
-    return true;
+  if (E->getType()->isNullPtrType()) return true;
 
   if (E->getType()->isAnyPointerType() &&
-      E->IgnoreParenCasts()->isNullPointerConstant(
-          *this, Expr::NPC_ValueDependentIsNull))
+      E->IgnoreParenCasts()->isNullPointerConstant(*this,
+                                                Expr::NPC_ValueDependentIsNull))
     return true;
 
   // Unfortunately, __null has type 'int'.
-  if (isa<GNUNullExpr>(E))
-    return true;
+  if (isa<GNUNullExpr>(E)) return true;
 
   return false;
 }
 
 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
 /// exists.
-ObjCImplementationDecl *
-ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
-  llvm::DenseMap<ObjCContainerDecl *, ObjCImplDecl *>::iterator I =
-      ObjCImpls.find(D);
+ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
+  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
+    I = ObjCImpls.find(D);
   if (I != ObjCImpls.end())
     return cast<ObjCImplementationDecl>(I->second);
   return nullptr;
@@ -2975,8 +2993,8 @@ ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
 /// exists.
 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
-  llvm::DenseMap<ObjCContainerDecl *, ObjCImplDecl *>::iterator I =
-      ObjCImpls.find(D);
+  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
+    I = ObjCImpls.find(D);
   if (I != ObjCImpls.end())
     return cast<ObjCCategoryImplDecl>(I->second);
   return nullptr;
@@ -2984,14 +3002,14 @@ ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
 
 /// Set the implementation of ObjCInterfaceDecl.
 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
-                                       ObjCImplementationDecl *ImplD) {
+                           ObjCImplementationDecl *ImplD) {
   assert(IFaceD && ImplD && "Passed null params");
   ObjCImpls[IFaceD] = ImplD;
 }
 
 /// Set the implementation of ObjCCategoryDecl.
 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
-                                       ObjCCategoryImplDecl *ImplD) {
+                           ObjCCategoryImplDecl *ImplD) {
   assert(CatD && ImplD && "Passed null params");
   ObjCImpls[CatD] = ImplD;
 }
@@ -3007,8 +3025,8 @@ void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
   ObjCMethodRedecls[MD] = Redecl;
 }
 
-const ObjCInterfaceDecl *
-ASTContext::getObjContainingInterface(const NamedDecl *ND) const {
+const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
+                                              const NamedDecl *ND) const {
   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
     return ID;
   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
@@ -3023,7 +3041,8 @@ ASTContext::getObjContainingInterface(const NamedDecl *ND) const {
 /// none exists.
 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
   assert(VD && "Passed null params");
-  assert(VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var");
+  assert(VD->hasAttr<BlocksAttr>() &&
+         "getBlockVarCopyInits - not __block var");
   auto I = BlockVarCopyInits.find(VD);
   if (I != BlockVarCopyInits.end())
     return I->second;
@@ -3031,10 +3050,11 @@ BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
 }
 
 /// Set the copy initialization expression of a block var decl.
-void ASTContext::setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr,
+void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
                                      bool CanThrow) {
   assert(VD && CopyExpr && "Passed null params");
-  assert(VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var");
+  assert(VD->hasAttr<BlocksAttr>() &&
+         "setBlockVarCopyInits - not __block var");
   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
 }
 
@@ -3046,8 +3066,8 @@ TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
            "incorrect data size provided to CreateTypeSourceInfo!");
 
-  auto *TInfo = (TypeSourceInfo *)BumpAlloc.Allocate(
-      sizeof(TypeSourceInfo) + DataSize, 8);
+  auto *TInfo =
+    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
   new (TInfo) TypeSourceInfo(T, DataSize);
   return TInfo;
 }
@@ -3080,8 +3100,8 @@ static auto getCanonicalTemplateArguments(const ASTContext &C,
 //                   Type creation/memoization methods
 //===----------------------------------------------------------------------===//
 
-QualType ASTContext::getExtQualType(const Type *baseType,
-                                    Qualifiers quals) const {
+QualType
+ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
   unsigned fastQuals = quals.getFastQualifiers();
   quals.removeFastQualifiers();
 
@@ -3102,7 +3122,7 @@ QualType ASTContext::getExtQualType(const Type *baseType,
     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
 
     // Re-find the insert position.
-    (void)ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
+    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
   }
 
   auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
@@ -3123,7 +3143,8 @@ QualType ASTContext::getAddrSpaceQualType(QualType T,
 
   // If this type already has an address space specified, it cannot get
   // another one.
-  assert(!Quals.hasAddressSpace() && "Type cannot be in multiple addr spaces!");
+  assert(!Quals.hasAddressSpace() &&
+         "Type cannot be in multiple addr spaces!");
   Quals.addAddressSpace(AddressSpace);
 
   return getExtQualType(TypeNode, Quals);
@@ -3523,7 +3544,8 @@ QualType ASTContext::getObjCGCQualType(QualType T,
 
   // If this type already has an ObjCGC specified, it cannot get
   // another one.
-  assert(!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!");
+  assert(!Quals.hasObjCGCAttr() &&
+         "Type cannot have multiple ObjCGCs!");
   Quals.addObjCGCAttr(GCAttr);
 
   return getExtQualType(TypeNode, Quals);
@@ -3571,9 +3593,10 @@ ASTContext::adjustType(QualType Orig,
   switch (Orig->getTypeClass()) {
   case Type::Attributed: {
     const auto *AT = cast<AttributedType>(Orig);
-    return getAttributedType(
-        AT->getAttrKind(), adjustType(AT->getModifiedType(), Adjust),
-        adjustType(AT->getEquivalentType(), Adjust), AT->getAttr());
+    return getAttributedType(AT->getAttrKind(),
+                             adjustType(AT->getModifiedType(), Adjust),
+                             adjustType(AT->getEquivalentType(), Adjust),
+                             AT->getAttr());
   }
 
   case Type::BTFTagAttributed: {
@@ -3692,8 +3715,9 @@ QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
 }
 
 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
-  return hasSameType(T, U) || hasSameType(getFunctionTypeWithoutPtrSizes(T),
-                                          getFunctionTypeWithoutPtrSizes(U));
+  return hasSameType(T, U) ||
+         hasSameType(getFunctionTypeWithoutPtrSizes(T),
+                     getFunctionTypeWithoutPtrSizes(U));
 }
 
 QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
@@ -3715,7 +3739,8 @@ void ASTContext::adjustExceptionSpec(
     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
     bool AsWritten) {
   // Update the type.
-  QualType Updated = getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
+  QualType Updated =
+      getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
   FD->setType(Updated);
 
   if (!AsWritten)
@@ -3758,8 +3783,7 @@ QualType ASTContext::getComplexType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
   auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
   Types.push_back(New);
@@ -3787,8 +3811,7 @@ QualType ASTContext::getPointerType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
   auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
   Types.push_back(New);
@@ -3903,7 +3926,7 @@ QualType ASTContext::getBlockPointerType(QualType T) const {
 
   void *InsertPos = nullptr;
   if (BlockPointerType *PT =
-          BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
+        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(PT, 0);
 
   // If the block pointee type isn't canonical, this won't be a canonical
@@ -3914,9 +3937,8 @@ QualType ASTContext::getBlockPointerType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     BlockPointerType *NewIP =
-        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
   auto *New =
       new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
@@ -3927,8 +3949,8 @@ QualType ASTContext::getBlockPointerType(QualType T) const {
 
 /// getLValueReferenceType - Return the uniqued reference to the type for an
 /// lvalue reference to the specified type.
-QualType ASTContext::getLValueReferenceType(QualType T,
-                                            bool SpelledAsLValue) const {
+QualType
+ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
   assert((!T->isPlaceholderType() ||
           T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
          "Unresolved placeholder type");
@@ -3940,7 +3962,7 @@ QualType ASTContext::getLValueReferenceType(QualType T,
 
   void *InsertPos = nullptr;
   if (LValueReferenceType *RT =
-          LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
+        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(RT, 0);
 
   const auto *InnerRef = T->getAs<ReferenceType>();
@@ -3954,9 +3976,8 @@ QualType ASTContext::getLValueReferenceType(QualType T,
 
     // Get the new insert position for the node we care about.
     LValueReferenceType *NewIP =
-        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
   auto *New = new (*this, alignof(LValueReferenceType))
@@ -3981,7 +4002,7 @@ QualType ASTContext::getRValueReferenceType(QualType T) const {
 
   void *InsertPos = nullptr;
   if (RValueReferenceType *RT =
-          RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
+        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(RT, 0);
 
   const auto *InnerRef = T->getAs<ReferenceType>();
@@ -3995,9 +4016,8 @@ QualType ASTContext::getRValueReferenceType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     RValueReferenceType *NewIP =
-        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
   auto *New = new (*this, alignof(RValueReferenceType))
@@ -4025,7 +4045,7 @@ QualType ASTContext::getMemberPointerType(QualType T,
 
   void *InsertPos = nullptr;
   if (MemberPointerType *PT =
-          MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
+      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(PT, 0);
 
   NestedNameSpecifier *CanonicalQualifier = [&] {
@@ -4063,8 +4083,8 @@ QualType ASTContext::getConstantArrayType(QualType EltTy,
                                           const Expr *SizeExpr,
                                           ArraySizeModifier ASM,
                                           unsigned IndexTypeQuals) const {
-  assert((EltTy->isDependentType() || EltTy->isIncompleteType() ||
-          EltTy->isConstantSizeType()) &&
+  assert((EltTy->isDependentType() ||
+          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
          "Constant array of VLAs is illegal!");
 
   // We only need the size as part of the type if it's instantiation-dependent.
@@ -4082,7 +4102,7 @@ QualType ASTContext::getConstantArrayType(QualType EltTy,
 
   void *InsertPos = nullptr;
   if (ConstantArrayType *ATP =
-          ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
+      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(ATP, 0);
 
   // If the element type isn't canonical or has qualifiers, or the array bound
@@ -4098,9 +4118,8 @@ QualType ASTContext::getConstantArrayType(QualType EltTy,
 
     // Get the new insert position for the node we care about.
     ConstantArrayType *NewIP =
-        ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
   auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
@@ -4115,8 +4134,7 @@ QualType ASTContext::getConstantArrayType(QualType EltTy,
 /// sizes replaced with [*].
 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
   // Vastly most common case.
-  if (!type->isVariablyModifiedType())
-    return type;
+  if (!type->isVariablyModifiedType()) return type;
 
   QualType result;
 
@@ -4179,22 +4197,22 @@ QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
   // TODO: if we ever care about optimizing VLAs, there are no-op
   // optimizations available here.
   case Type::Pointer:
-    result = getPointerType(
-        getVariableArrayDecayedType(cast<PointerType>(ty)->getPointeeType()));
+    result = getPointerType(getVariableArrayDecayedType(
+                              cast<PointerType>(ty)->getPointeeType()));
     break;
 
   case Type::LValueReference: {
     const auto *lv = cast<LValueReferenceType>(ty);
     result = getLValueReferenceType(
-        getVariableArrayDecayedType(lv->getPointeeType()),
-        lv->isSpelledAsLValue());
+                 getVariableArrayDecayedType(lv->getPointeeType()),
+                                    lv->isSpelledAsLValue());
     break;
   }
 
   case Type::RValueReference: {
     const auto *lv = cast<RValueReferenceType>(ty);
     result = getRValueReferenceType(
-        getVariableArrayDecayedType(lv->getPointeeType()));
+                 getVariableArrayDecayedType(lv->getPointeeType()));
     break;
   }
 
@@ -4207,18 +4225,22 @@ QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
   case Type::ConstantArray: {
     const auto *cat = cast<ConstantArrayType>(ty);
     result = getConstantArrayType(
-        getVariableArrayDecayedType(cat->getElementType()), cat->getSize(),
-        cat->getSizeExpr(), cat->getSizeModifier(),
-        cat->getIndexTypeCVRQualifiers());
+                 getVariableArrayDecayedType(cat->getElementType()),
+                                  cat->getSize(),
+                                  cat->getSizeExpr(),
+                                  cat->getSizeModifier(),
+                                  cat->getIndexTypeCVRQualifiers());
     break;
   }
 
   case Type::DependentSizedArray: {
     const auto *dat = cast<DependentSizedArrayType>(ty);
     result = getDependentSizedArrayType(
-        getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
-        dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers(),
-        dat->getBracketsRange());
+                 getVariableArrayDecayedType(dat->getElementType()),
+                                        dat->getSizeExpr(),
+                                        dat->getSizeModifier(),
+                                        dat->getIndexTypeCVRQualifiers(),
+                                        dat->getBracketsRange());
     break;
   }
 
@@ -4296,7 +4318,7 @@ QualType ASTContext::getDependentSizedArrayType(QualType elementType,
 
   // Look for an existing type with these properties.
   DependentSizedArrayType *canonTy =
-      DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
+    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
 
   // Dependently-sized array types that do not have a specified number
   // of elements will have their sizes deduced from a dependent
@@ -4323,8 +4345,8 @@ QualType ASTContext::getDependentSizedArrayType(QualType elementType,
   }
 
   // Apply qualifiers from the element type to the array.
-  QualType canon =
-      getQualifiedType(QualType(canonTy, 0), canonElementType.Quals);
+  QualType canon = getQualifiedType(QualType(canonTy,0),
+                                    canonElementType.Quals);
 
   // If we didn't need extra canonicalization for the element type or the size
   // expression, then just use that as our result.
@@ -4349,7 +4371,7 @@ QualType ASTContext::getIncompleteArrayType(QualType elementType,
 
   void *insertPos = nullptr;
   if (IncompleteArrayType *iat =
-          IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
+       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
     return QualType(iat, 0);
 
   // If the element type isn't canonical, this won't be a canonical type
@@ -4360,15 +4382,14 @@ QualType ASTContext::getIncompleteArrayType(QualType elementType,
   // FIXME: Check below should look for qualifiers behind sugar.
   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
     SplitQualType canonSplit = getCanonicalType(elementType).split();
-    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), ASM,
-                                   elementTypeQuals);
+    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
+                                   ASM, elementTypeQuals);
     canon = getQualifiedType(canon, canonSplit.Quals);
 
     // Get the new insert position for the node we care about.
     IncompleteArrayType *existing =
-        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
-    assert(!existing && "Shouldn't be in the map!");
-    (void)existing;
+      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
+    assert(!existing && "Shouldn't be in the map!"); (void) existing;
   }
 
   auto *newType = new (*this, alignof(IncompleteArrayType))
@@ -4533,8 +4554,7 @@ QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
 
     // Get the new insert position for the node we care about.
     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
   auto *New = new (*this, alignof(VectorType))
       VectorType(vecType, NumElts, Canonical, VecKind);
@@ -4607,8 +4627,7 @@ QualType ASTContext::getExtVectorType(QualType vecType,
 
     // Get the new insert position for the node we care about.
     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
   auto *New = new (*this, alignof(ExtVectorType))
       ExtVectorType(vecType, NumElts, Canonical);
@@ -4618,15 +4637,16 @@ QualType ASTContext::getExtVectorType(QualType vecType,
 }
 
 QualType
-ASTContext::getDependentSizedExtVectorType(QualType vecType, Expr *SizeExpr,
+ASTContext::getDependentSizedExtVectorType(QualType vecType,
+                                           Expr *SizeExpr,
                                            SourceLocation AttrLoc) const {
   llvm::FoldingSetNodeID ID;
   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
                                        SizeExpr);
 
   void *InsertPos = nullptr;
-  DependentSizedExtVectorType *Canon =
-      DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
+  DependentSizedExtVectorType *Canon
+    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
   DependentSizedExtVectorType *New;
   if (Canon) {
     // We already have a canonical version of this array type; use it as
@@ -4640,8 +4660,8 @@ ASTContext::getDependentSizedExtVectorType(QualType vecType, Expr *SizeExpr,
       New = new (*this, alignof(DependentSizedExtVectorType))
           DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
 
-      DependentSizedExtVectorType *CanonCheck =
-          DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
+      DependentSizedExtVectorType *CanonCheck
+        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
       (void)CanonCheck;
       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
@@ -4730,8 +4750,9 @@ QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
   return QualType(New, 0);
 }
 
-QualType ASTContext::getDependentAddressSpaceType(
-    QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const {
+QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
+                                                  Expr *AddrSpaceExpr,
+                                                  SourceLocation AttrLoc) const {
   assert(AddrSpaceExpr->isInstantiationDependent());
 
   QualType canonPointeeType = getCanonicalType(PointeeType);
@@ -4742,7 +4763,7 @@ QualType ASTContext::getDependentAddressSpaceType(
                                      AddrSpaceExpr);
 
   DependentAddressSpaceType *canonTy =
-      DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
+    DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
 
   if (!canonTy) {
     canonTy = new (*this, alignof(DependentAddressSpaceType))
@@ -4778,7 +4799,7 @@ ASTContext::getFunctionNoProtoType(QualType ResultTy,
   // functionality creates a function without a prototype regardless of
   // language mode (so it makes them even in C++). Once the rewriter has been
   // fixed, this assertion can be enabled again.
-  // assert(!LangOpts.requiresStrictPrototypes() &&
+  //assert(!LangOpts.requiresStrictPrototypes() &&
   //       "strict prototypes are disabled");
 
   // Unique functions, to guarantee there is only one function of a particular
@@ -4788,19 +4809,18 @@ ASTContext::getFunctionNoProtoType(QualType ResultTy,
 
   void *InsertPos = nullptr;
   if (FunctionNoProtoType *FT =
-          FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
+        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(FT, 0);
 
   QualType Canonical;
   if (!isCanonicalResultType(ResultTy)) {
     Canonical =
-        getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
+      getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
 
     // Get the new insert position for the node we care about.
     FunctionNoProtoType *NewIP =
-        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
   auto *New = new (*this, alignof(FunctionNoProtoType))
@@ -4819,7 +4839,7 @@ ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
     Qualifiers Qs = CanResultType.getQualifiers();
     Qs.removeObjCLifetime();
     return CanQualType::CreateUnsafe(
-        getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
+             getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
   }
 
   return CanResultType;
@@ -4875,7 +4895,7 @@ QualType ASTContext::getFunctionTypeInternal(
 
   void *InsertPos = nullptr;
   if (FunctionProtoType *FPT =
-          FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
+        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
     QualType Existing = QualType(FPT, 0);
 
     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
@@ -4926,15 +4946,11 @@ QualType ASTContext::getFunctionTypeInternal(
       // Exception spec is already OK.
     } else if (NoexceptInType) {
       switch (EPI.ExceptionSpec.Type) {
-      case EST_Unparsed:
-      case EST_Unevaluated:
-      case EST_Uninstantiated:
+      case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
         // We don't know yet. It shouldn't matter what we pick here; no-one
         // should ever look at this.
         [[fallthrough]];
-      case EST_None:
-      case EST_MSAny:
-      case EST_NoexceptFalse:
+      case EST_None: case EST_MSAny: case EST_NoexceptFalse:
         CanonicalEPI.ExceptionSpec.Type = EST_None;
         break;
 
@@ -4977,9 +4993,8 @@ QualType ASTContext::getFunctionTypeInternal(
 
     // Get the new insert position for the node we care about.
     FunctionProtoType *NewIP =
-        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
   // Compute the needed size to hold this FunctionProtoType and the
@@ -5083,8 +5098,7 @@ QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
 
 #ifndef NDEBUG
 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
-  if (!isa<CXXRecordDecl>(D))
-    return false;
+  if (!isa<CXXRecordDecl>(D)) return false;
   const auto *RD = cast<CXXRecordDecl>(D);
   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
     return true;
@@ -5206,8 +5220,7 @@ QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
 }
 
 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
-  if (Decl->TypeForDecl)
-    return QualType(Decl->TypeForDecl, 0);
+  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
 
   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
     if (PrevDecl->TypeForDecl)
@@ -5220,8 +5233,7 @@ QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
 }
 
 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
-  if (Decl->TypeForDecl)
-    return QualType(Decl->TypeForDecl, 0);
+  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
 
   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
     if (PrevDecl->TypeForDecl)
@@ -5351,13 +5363,12 @@ QualType ASTContext::getAttributedType(attr::Kind attrKind,
 
   void *insertPos = nullptr;
   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
-  if (type)
-    return QualType(type, 0);
+  if (type) return QualType(type, 0);
 
   assert(!attr || attr->getKind() == attrKind);
 
   QualType canon = getCanonicalType(equivalentType);
-  type = new (*this, alignof(AttributedType))
+	type = new (*this, alignof(AttributedType))
       AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
 
   Types.push_back(type);
@@ -5502,15 +5513,14 @@ ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
 /// Retrieve the template type parameter type for a template
 /// parameter or parameter pack with the given depth, index, and (optionally)
 /// name.
-QualType
-ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
-                                    bool ParameterPack,
-                                    TemplateTypeParmDecl *TTPDecl) const {
+QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
+                                             bool ParameterPack,
+                                             TemplateTypeParmDecl *TTPDecl) const {
   llvm::FoldingSetNodeID ID;
   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
   void *InsertPos = nullptr;
-  TemplateTypeParmType *TypeParm =
-      TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
+  TemplateTypeParmType *TypeParm
+    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
 
   if (TypeParm)
     return QualType(TypeParm, 0);
@@ -5520,8 +5530,8 @@ ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
     TypeParm = new (*this, alignof(TemplateTypeParmType))
         TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
 
-    TemplateTypeParmType *TypeCheck =
-        TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
+    TemplateTypeParmType *TypeCheck
+      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
     assert(!TypeCheck && "Template type parameter canonical type broken");
     (void)TypeCheck;
   } else
@@ -5534,9 +5544,11 @@ ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
   return QualType(TypeParm, 0);
 }
 
-TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
-    TemplateName Name, SourceLocation NameLoc,
-    const TemplateArgumentListInfo &Args, QualType Underlying) const {
+TypeSourceInfo *
+ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
+                                              SourceLocation NameLoc,
+                                        const TemplateArgumentListInfo &Args,
+                                              QualType Underlying) const {
   assert(!Name.getAsDependentTemplateName() &&
          "No dependent template names here!");
   QualType TST =
@@ -5607,8 +5619,9 @@ ASTContext::getTemplateSpecializationType(TemplateName Template,
                            sizeof(TemplateArgument) * Args.size() +
                            (IsTypeAlias ? sizeof(QualType) : 0),
                        alignof(TemplateSpecializationType));
-  auto *Spec = new (Mem) TemplateSpecializationType(
-      Template, Args, CanonType, IsTypeAlias ? Underlying : QualType());
+  auto *Spec
+    = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
+                                         IsTypeAlias ? Underlying : QualType());
 
   Types.push_back(Spec);
   return QualType(Spec, 0);
@@ -5633,18 +5646,20 @@ QualType ASTContext::getCanonicalTemplateSpecializationType(
   // Determine whether this canonical template specialization type already
   // exists.
   llvm::FoldingSetNodeID ID;
-  TemplateSpecializationType::Profile(ID, CanonTemplate, CanonArgs, *this);
+  TemplateSpecializationType::Profile(ID, CanonTemplate,
+                                      CanonArgs, *this);
 
   void *InsertPos = nullptr;
-  TemplateSpecializationType *Spec =
-      TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
+  TemplateSpecializationType *Spec
+    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
 
   if (!Spec) {
     // Allocate a new canonical template specialization type.
     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
                           sizeof(TemplateArgument) * CanonArgs.size()),
                          alignof(TemplateSpecializationType));
-    Spec = new (Mem) TemplateSpecializationType(CanonTemplate, CanonArgs,
+    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
+                                                CanonArgs,
                                                 QualType(), QualType());
     Types.push_back(Spec);
     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
@@ -5685,7 +5700,8 @@ QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
   return QualType(T, 0);
 }
 
-QualType ASTContext::getParenType(QualType InnerType) const {
+QualType
+ASTContext::getParenType(QualType InnerType) const {
   llvm::FoldingSetNodeID ID;
   ParenType::Profile(ID, InnerType);
 
@@ -5735,7 +5751,8 @@ QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
   DependentNameType::Profile(ID, Keyword, NNS, Name);
 
   void *InsertPos = nullptr;
-  DependentNameType *T = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
+  DependentNameType *T
+    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
   if (T)
     return QualType(T, 0);
 
@@ -5756,19 +5773,22 @@ QualType ASTContext::getDependentTemplateSpecializationType(
   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
 }
 
-QualType ASTContext::getDependentTemplateSpecializationType(
-    ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
-    const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const {
+QualType
+ASTContext::getDependentTemplateSpecializationType(
+                                 ElaboratedTypeKeyword Keyword,
+                                 NestedNameSpecifier *NNS,
+                                 const IdentifierInfo *Name,
+                                 ArrayRef<TemplateArgument> Args) const {
   assert((!NNS || NNS->isDependent()) &&
          "nested-name-specifier must be dependent");
 
   llvm::FoldingSetNodeID ID;
-  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, Name,
-                                               Args);
+  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
+                                               Name, Args);
 
   void *InsertPos = nullptr;
-  DependentTemplateSpecializationType *T =
-      DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
+  DependentTemplateSpecializationType *T
+    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
   if (T)
     return QualType(T, 0);
 
@@ -5784,7 +5804,8 @@ QualType ASTContext::getDependentTemplateSpecializationType(
 
   QualType Canon;
   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
-    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, Name,
+    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
+                                                   Name,
                                                    CanonArgs);
 
     // Find the insert position again.
@@ -5796,8 +5817,8 @@ QualType ASTContext::getDependentTemplateSpecializationType(
   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
                         sizeof(TemplateArgument) * Args.size()),
                        alignof(DependentTemplateSpecializationType));
-  T = new (Mem)
-      DependentTemplateSpecializationType(Keyword, NNS, Name, Args, Canon);
+  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
+                                                    Name, Args, Canon);
   Types.push_back(T);
   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
   return QualType(T, 0);
@@ -5892,8 +5913,7 @@ static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
 }
 
 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
-  if (Protocols.empty())
-    return true;
+  if (Protocols.empty()) return true;
 
   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
     return false;
@@ -5920,17 +5940,18 @@ SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
 }
 
 QualType ASTContext::getObjCObjectType(QualType BaseType,
-                                       ObjCProtocolDecl *const *Protocols,
+                                       ObjCProtocolDecl * const *Protocols,
                                        unsigned NumProtocols) const {
   return getObjCObjectType(BaseType, {},
                            llvm::ArrayRef(Protocols, NumProtocols),
                            /*isKindOf=*/false);
 }
 
-QualType ASTContext::getObjCObjectType(QualType baseType,
-                                       ArrayRef<QualType> typeArgs,
-                                       ArrayRef<ObjCProtocolDecl *> protocols,
-                                       bool isKindOf) const {
+QualType ASTContext::getObjCObjectType(
+           QualType baseType,
+           ArrayRef<QualType> typeArgs,
+           ArrayRef<ObjCProtocolDecl *> protocols,
+           bool isKindOf) const {
   // If the base type is an interface and there aren't any protocols or
   // type arguments to add, then the interface type will do just fine.
   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
@@ -5974,7 +5995,7 @@ QualType ASTContext::getObjCObjectType(QualType baseType,
     }
 
     ArrayRef<ObjCProtocolDecl *> canonProtocols;
-    SmallVector<ObjCProtocolDecl *, 8> canonProtocolsVec;
+    SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
     if (!protocolsSorted) {
       canonProtocolsVec.append(protocols.begin(), protocols.end());
       SortAndUniqueProtocols(canonProtocolsVec);
@@ -5994,8 +6015,9 @@ QualType ASTContext::getObjCObjectType(QualType baseType,
   size += typeArgs.size() * sizeof(QualType);
   size += protocols.size() * sizeof(ObjCProtocolDecl *);
   void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
-  auto *T = new (mem)
-      ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, isKindOf);
+  auto *T =
+    new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
+                                 isKindOf);
 
   Types.push_back(T);
   ObjCObjectTypes.InsertNode(T, InsertPos);
@@ -6005,9 +6027,10 @@ QualType ASTContext::getObjCObjectType(QualType baseType,
 /// Apply Objective-C protocol qualifiers to the given type.
 /// If this is for the canonical type of a type parameter, we can apply
 /// protocol qualifiers on the ObjCObjectPointerType.
-QualType ASTContext::applyObjCProtocolQualifiers(
-    QualType type, ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
-    bool allowOnPointerType) const {
+QualType
+ASTContext::applyObjCProtocolQualifiers(QualType type,
+                  ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
+                  bool allowOnPointerType) const {
   hasError = false;
 
   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
@@ -6020,24 +6043,29 @@ QualType ASTContext::applyObjCProtocolQualifiers(
             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
       const ObjCObjectType *objT = objPtr->getObjectType();
       // Merge protocol lists and construct ObjCObjectType.
-      SmallVector<ObjCProtocolDecl *, 8> protocolsVec;
-      protocolsVec.append(objT->qual_begin(), objT->qual_end());
+      SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
+      protocolsVec.append(objT->qual_begin(),
+                          objT->qual_end());
       protocolsVec.append(protocols.begin(), protocols.end());
       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
-      type =
-          getObjCObjectType(objT->getBaseType(), objT->getTypeArgsAsWritten(),
-                            protocols, objT->isKindOfTypeAsWritten());
+      type = getObjCObjectType(
+             objT->getBaseType(),
+             objT->getTypeArgsAsWritten(),
+             protocols,
+             objT->isKindOfTypeAsWritten());
       return getObjCObjectPointerType(type);
     }
   }
 
   // Apply protocol qualifiers to ObjCObjectType.
-  if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())) {
+  if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
     // FIXME: Check for protocols to which the class type is already
     // known to conform.
 
-    return getObjCObjectType(objT->getBaseType(), objT->getTypeArgsAsWritten(),
-                             protocols, objT->isKindOfTypeAsWritten());
+    return getObjCObjectType(objT->getBaseType(),
+                             objT->getTypeArgsAsWritten(),
+                             protocols,
+                             objT->isKindOfTypeAsWritten());
   }
 
   // If the canonical type is ObjCObjectType, ...
@@ -6054,7 +6082,7 @@ QualType ASTContext::applyObjCProtocolQualifiers(
   if (type->isObjCIdType()) {
     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
-                             objPtr->isKindOfType());
+                                 objPtr->isKindOfType());
     return getObjCObjectPointerType(type);
   }
 
@@ -6062,7 +6090,7 @@ QualType ASTContext::applyObjCProtocolQualifiers(
   if (type->isObjCClassType()) {
     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
-                             objPtr->isKindOfType());
+                                 objPtr->isKindOfType());
     return getObjCObjectPointerType(type);
   }
 
@@ -6078,7 +6106,7 @@ ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
   void *InsertPos = nullptr;
   if (ObjCTypeParamType *TypeParam =
-          ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
+      ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(TypeParam, 0);
 
   // We canonicalize to the underlying type.
@@ -6134,8 +6162,8 @@ bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
 /// of protocols.
-bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(
-    QualType QT, ObjCInterfaceDecl *IDecl) {
+bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
+                                                ObjCInterfaceDecl *IDecl) {
   if (!QT->isObjCQualifiedIdType())
     return false;
   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
@@ -6186,7 +6214,7 @@ QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
 
   void *InsertPos = nullptr;
   if (ObjCObjectPointerType *QT =
-          ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
+              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
     return QualType(QT, 0);
 
   // Find the canonical object type.
@@ -6201,7 +6229,8 @@ QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
   // No match.
   void *Mem =
       Allocate(sizeof(ObjCObjectPointerType), alignof(ObjCObjectPointerType));
-  auto *QType = new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
+  auto *QType =
+    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
 
   Types.push_back(QType);
   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
@@ -6320,8 +6349,8 @@ QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
     DependentDecltypeType::Profile(ID, *this, e);
 
     void *InsertPos = nullptr;
-    DependentDecltypeType *Canon =
-        DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
+    DependentDecltypeType *Canon
+      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
     if (!Canon) {
       // Build a new, canonical decltype(expr) type.
       Canon = new (*this, alignof(DependentDecltypeType))
@@ -6375,9 +6404,10 @@ QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
 
 /// getUnaryTransformationType - We don't unique these, since the memory
 /// savings are minimal and these are rare.
-QualType
-ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
-                                  UnaryTransformType::UTTKind Kind) const {
+QualType ASTContext::getUnaryTransformType(QualType BaseType,
+                                           QualType UnderlyingType,
+                                           UnaryTransformType::UTTKind Kind)
+    const {
   UnaryTransformType *ut = nullptr;
 
   if (BaseType->isDependentType()) {
@@ -6386,8 +6416,8 @@ ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
 
     void *InsertPos = nullptr;
-    DependentUnaryTransformType *Canon =
-        DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
+    DependentUnaryTransformType *Canon
+      = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
 
     if (!Canon) {
       // Build a new, canonical __underlying_type(type) type.
@@ -6553,8 +6583,7 @@ QualType ASTContext::getAtomicType(QualType T) const {
 
     // Get the new insert position for the node we care about.
     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
-    assert(!NewIP && "Shouldn't be in the map!");
-    (void)NewIP;
+    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
   auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
   Types.push_back(New);
@@ -6587,7 +6616,7 @@ QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
   assert(Decl);
   // FIXME: What is the design on getTagDeclType when it requires casting
   // away const?  mutable?
-  return getTypeDeclType(const_cast<TagDecl *>(Decl));
+  return getTypeDeclType(const_cast<TagDecl*>(Decl));
 }
 
 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
@@ -6668,7 +6697,7 @@ CanQualType ASTContext::getCanonicalParamType(QualType T) const {
   if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
     Result = getArrayParameterType(QualType(Ty, 0));
   } else if (isa<ArrayType>(Ty)) {
-    Result = getArrayDecayedType(QualType(Ty, 0));
+    Result = getArrayDecayedType(QualType(Ty,0));
   } else if (isa<FunctionType>(Ty)) {
     Result = getPointerType(QualType(Ty, 0));
   } else {
@@ -6721,14 +6750,17 @@ QualType ASTContext::getUnqualifiedArrayType(QualType type,
   }
 
   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
-    return getVariableArrayType(
-        unqualElementType, VAT->getSizeExpr(), VAT->getSizeModifier(),
-        VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
+    return getVariableArrayType(unqualElementType,
+                                VAT->getSizeExpr(),
+                                VAT->getSizeModifier(),
+                                VAT->getIndexTypeCVRQualifiers(),
+                                VAT->getBracketsRange());
   }
 
   const auto *DSAT = cast<DependentSizedArrayType>(AT);
   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
-                                    DSAT->getSizeModifier(), 0, SourceRange());
+                                    DSAT->getSizeModifier(), 0,
+                                    SourceRange());
 }
 
 /// Attempt to unwrap two types that may both be array types with the same bound
@@ -6898,14 +6930,15 @@ ASTContext::getNameForTemplate(TemplateName Name,
   }
 
   case TemplateName::SubstTemplateTemplateParm: {
-    SubstTemplateTemplateParmStorage *subst =
-        Name.getAsSubstTemplateTemplateParm();
-    return DeclarationNameInfo(subst->getParameter()->getDeclName(), NameLoc);
+    SubstTemplateTemplateParmStorage *subst
+      = Name.getAsSubstTemplateTemplateParm();
+    return DeclarationNameInfo(subst->getParameter()->getDeclName(),
+                               NameLoc);
   }
 
   case TemplateName::SubstTemplateTemplateParmPack: {
-    SubstTemplateTemplateParmPackStorage *subst =
-        Name.getAsSubstTemplateTemplateParmPack();
+    SubstTemplateTemplateParmPackStorage *subst
+      = Name.getAsSubstTemplateTemplateParmPack();
     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
                                NameLoc);
   }
@@ -6949,7 +6982,7 @@ TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
   switch (Name.getKind()) {
   case TemplateName::Template: {
     TemplateDecl *Template = Name.getAsTemplateDecl();
-    if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
+    if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
       Template = getCanonicalTemplateTemplateParmDecl(TTP);
 
     // The canonical template name is the canonical template declaration.
@@ -7494,54 +7527,54 @@ bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
 TemplateArgument
 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
   switch (Arg.getKind()) {
-  case TemplateArgument::Null:
-    return Arg;
+    case TemplateArgument::Null:
+      return Arg;
 
-  case TemplateArgument::Expression:
-    return Arg;
+    case TemplateArgument::Expression:
+      return Arg;
 
-  case TemplateArgument::Declaration: {
-    auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
-    return TemplateArgument(D, getCanonicalType(Arg.getParamTypeForDecl()),
-                            Arg.getIsDefaulted());
-  }
+    case TemplateArgument::Declaration: {
+      auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
+      return TemplateArgument(D, getCanonicalType(Arg.getParamTypeForDecl()),
+                              Arg.getIsDefaulted());
+    }
 
-  case TemplateArgument::NullPtr:
-    return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
-                            /*isNullPtr*/ true, Arg.getIsDefaulted());
+    case TemplateArgument::NullPtr:
+      return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
+                              /*isNullPtr*/ true, Arg.getIsDefaulted());
 
-  case TemplateArgument::Template:
-    return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()),
-                            Arg.getIsDefaulted());
+    case TemplateArgument::Template:
+      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()),
+                              Arg.getIsDefaulted());
 
-  case TemplateArgument::TemplateExpansion:
-    return TemplateArgument(
-        getCanonicalTemplateName(Arg.getAsTemplateOrTemplatePattern()),
-        Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
-
-  case TemplateArgument::Integral:
-    return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
-
-  case TemplateArgument::StructuralValue:
-    return TemplateArgument(*this,
-                            getCanonicalType(Arg.getStructuralValueType()),
-                            Arg.getAsStructuralValue(), Arg.getIsDefaulted());
-
-  case TemplateArgument::Type:
-    return TemplateArgument(getCanonicalType(Arg.getAsType()),
-                            /*isNullPtr*/ false, Arg.getIsDefaulted());
-
-  case TemplateArgument::Pack: {
-    bool AnyNonCanonArgs = false;
-    auto CanonArgs = ::getCanonicalTemplateArguments(*this, Arg.pack_elements(),
-                                                     AnyNonCanonArgs);
-    if (!AnyNonCanonArgs)
-      return Arg;
-    auto NewArg = TemplateArgument::CreatePackCopy(
-        const_cast<ASTContext &>(*this), CanonArgs);
-    NewArg.setIsDefaulted(Arg.getIsDefaulted());
-    return NewArg;
-  }
+    case TemplateArgument::TemplateExpansion:
+      return TemplateArgument(
+          getCanonicalTemplateName(Arg.getAsTemplateOrTemplatePattern()),
+          Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
+
+    case TemplateArgument::Integral:
+      return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
+
+    case TemplateArgument::StructuralValue:
+      return TemplateArgument(*this,
+                              getCanonicalType(Arg.getStructuralValueType()),
+                              Arg.getAsStructuralValue(), Arg.getIsDefaulted());
+
+    case TemplateArgument::Type:
+      return TemplateArgument(getCanonicalType(Arg.getAsType()),
+                              /*isNullPtr*/ false, Arg.getIsDefaulted());
+
+    case TemplateArgument::Pack: {
+      bool AnyNonCanonArgs = false;
+      auto CanonArgs = ::getCanonicalTemplateArguments(
+          *this, Arg.pack_elements(), AnyNonCanonArgs);
+      if (!AnyNonCanonArgs)
+        return Arg;
+      auto NewArg = TemplateArgument::CreatePackCopy(
+          const_cast<ASTContext &>(*this), CanonArgs);
+      NewArg.setIsDefaulted(Arg.getIsDefaulted());
+      return NewArg;
+    }
   }
 
   // Silence GCC warning
@@ -7556,9 +7589,9 @@ ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
   switch (NNS->getKind()) {
   case NestedNameSpecifier::Identifier:
     // Canonicalize the prefix but keep the identifier the same.
-    return NestedNameSpecifier::Create(
-        *this, getCanonicalNestedNameSpecifier(NNS->getPrefix()),
-        NNS->getAsIdentifier());
+    return NestedNameSpecifier::Create(*this,
+                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
+                                       NNS->getAsIdentifier());
 
   case NestedNameSpecifier::Namespace:
     // A namespace is canonical; build a nested-name-specifier with
@@ -7638,22 +7671,29 @@ const ArrayType *ASTContext::getAsArrayType(QualType T) const {
   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
 
   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
-    return cast<ArrayType>(getConstantArrayType(
-        NewEltTy, CAT->getSize(), CAT->getSizeExpr(), CAT->getSizeModifier(),
-        CAT->getIndexTypeCVRQualifiers()));
+    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
+                                                CAT->getSizeExpr(),
+                                                CAT->getSizeModifier(),
+                                           CAT->getIndexTypeCVRQualifiers()));
   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
-    return cast<ArrayType>(getIncompleteArrayType(
-        NewEltTy, IAT->getSizeModifier(), IAT->getIndexTypeCVRQualifiers()));
+    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
+                                                  IAT->getSizeModifier(),
+                                           IAT->getIndexTypeCVRQualifiers()));
 
   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
-    return cast<ArrayType>(getDependentSizedArrayType(
-        NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
-        DSAT->getIndexTypeCVRQualifiers(), DSAT->getBracketsRange()));
+    return cast<ArrayType>(
+                     getDependentSizedArrayType(NewEltTy,
+                                                DSAT->getSizeExpr(),
+                                                DSAT->getSizeModifier(),
+                                              DSAT->getIndexTypeCVRQualifiers(),
+                                                DSAT->getBracketsRange()));
 
   const auto *VAT = cast<VariableArrayType>(ATy);
-  return cast<ArrayType>(getVariableArrayType(
-      NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
-      VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()));
+  return cast<ArrayType>(getVariableArrayType(NewEltTy,
+                                              VAT->getSizeExpr(),
+                                              VAT->getSizeModifier(),
+                                              VAT->getIndexTypeCVRQualifiers(),
+                                              VAT->getBracketsRange()));
 }
 
 QualType ASTContext::getAdjustedParameterType(QualType T) const {
@@ -7700,8 +7740,8 @@ QualType ASTContext::getArrayDecayedType(QualType Ty) const {
   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
 
   // int x[restrict 4] ->  int *restrict
-  QualType Result =
-      getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
+  QualType Result = getQualifiedType(PtrTy,
+                                     PrettyArrayType->getIndexTypeQualifiers());
 
   // int x[_Nullable] -> int * _Nullable
   if (auto Nullability = Ty->getNullability()) {
@@ -7720,8 +7760,7 @@ QualType ASTContext::getBaseElementType(QualType type) const {
   while (true) {
     SplitQualType split = type.getSplitDesugaredType();
     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
-    if (!array)
-      break;
+    if (!array) break;
 
     type = array->getElementType();
     qs.addConsistentQualifiers(split.Quals);
@@ -7732,12 +7771,12 @@ QualType ASTContext::getBaseElementType(QualType type) const {
 
 /// getConstantArrayElementCount - Returns number of constant array elements.
 uint64_t
-ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
+ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
   uint64_t ElementCount = 1;
   do {
     ElementCount *= CA->getZExtSize();
     CA = dyn_cast_or_null<ConstantArrayType>(
-        CA->getElementType()->getAsArrayTypeUnsafe());
+      CA->getElementType()->getAsArrayTypeUnsafe());
   } while (CA);
   return ElementCount;
 }
@@ -7764,24 +7803,15 @@ static FloatingRank getFloatingRank(QualType T) {
     return getFloatingRank(CT->getElementType());
 
   switch (T->castAs<BuiltinType>()->getKind()) {
-  default:
-    llvm_unreachable("getFloatingRank(): not a floating type");
-  case BuiltinType::Float16:
-    return Float16Rank;
-  case BuiltinType::Half:
-    return HalfRank;
-  case BuiltinType::Float:
-    return FloatRank;
-  case BuiltinType::Double:
-    return DoubleRank;
-  case BuiltinType::LongDouble:
-    return LongDoubleRank;
-  case BuiltinType::Float128:
-    return Float128Rank;
-  case BuiltinType::BFloat16:
-    return BFloat16Rank;
-  case BuiltinType::Ibm128:
-    return Ibm128Rank;
+  default: llvm_unreachable("getFloatingRank(): not a floating type");
+  case BuiltinType::Float16:    return Float16Rank;
+  case BuiltinType::Half:       return HalfRank;
+  case BuiltinType::Float:      return FloatRank;
+  case BuiltinType::Double:     return DoubleRank;
+  case BuiltinType::LongDouble: return LongDoubleRank;
+  case BuiltinType::Float128:   return Float128Rank;
+  case BuiltinType::BFloat16:   return BFloat16Rank;
+  case BuiltinType::Ibm128:     return Ibm128Rank;
   }
 }
 
@@ -7818,8 +7848,7 @@ unsigned ASTContext::getIntegerRank(const Type *T) const {
     return 0 + (EIT->getNumBits() << 3);
 
   switch (cast<BuiltinType>(T)->getKind()) {
-  default:
-    llvm_unreachable("getIntegerRank(): not a built-in integer");
+  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
   case BuiltinType::Bool:
     return 1 + (getIntWidth(BoolTy) << 3);
   case BuiltinType::Char_S:
@@ -7948,9 +7977,8 @@ QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
         BT->getKind() == BuiltinType::Char32) {
       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
       uint64_t FromSize = getTypeSize(BT);
-      QualType PromoteTypes[] = {IntTy,      UnsignedIntTy,
-                                 LongTy,     UnsignedLongTy,
-                                 LongLongTy, UnsignedLongLongTy};
+      QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
+                                  LongLongTy, UnsignedLongLongTy };
       for (const auto &PT : PromoteTypes) {
         uint64_t ToSize = getTypeSize(PT);
         if (FromSize < ToSize ||
@@ -8026,8 +8054,7 @@ int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
   if (const auto *ET = dyn_cast<EnumType>(RHSC))
     RHSC = getIntegerTypeForEnum(ET);
 
-  if (LHSC == RHSC)
-    return 0;
+  if (LHSC == RHSC) return 0;
 
   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
@@ -8035,9 +8062,8 @@ int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
   unsigned LHSRank = getIntegerRank(LHSC);
   unsigned RHSRank = getIntegerRank(RHSC);
 
-  if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
-    if (LHSRank == RHSRank)
-      return 0;
+  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
+    if (LHSRank == RHSRank) return 0;
     return LHSRank > RHSRank ? 1 : -1;
   }
 
@@ -8110,28 +8136,29 @@ TypedefDecl *ASTContext::getCFConstantStringDecl() const {
   const auto CFRuntime = getLangOpts().CFRuntime;
   if (static_cast<unsigned>(CFRuntime) <
       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
-    Fields[Count++] = {getPointerType(IntTy.withConst()), "isa"};
-    Fields[Count++] = {IntTy, "flags"};
-    Fields[Count++] = {getPointerType(CharTy.withConst()), "str"};
-    Fields[Count++] = {LongTy, "length"};
+    Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
+    Fields[Count++] = { IntTy, "flags" };
+    Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
+    Fields[Count++] = { LongTy, "length" };
   } else {
-    Fields[Count++] = {getUIntPtrType(), "_cfisa"};
-    Fields[Count++] = {getUIntPtrType(), "_swift_rc"};
-    Fields[Count++] = {getFromTargetType(Target->getUInt64Type()), "_swift_rc"};
-    Fields[Count++] = {getPointerType(CharTy.withConst()), "_ptr"};
+    Fields[Count++] = { getUIntPtrType(), "_cfisa" };
+    Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
+    Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
+    Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
-      Fields[Count++] = {IntTy, "_ptr"};
+      Fields[Count++] = { IntTy, "_ptr" };
     else
-      Fields[Count++] = {getUIntPtrType(), "_ptr"};
+      Fields[Count++] = { getUIntPtrType(), "_ptr" };
   }
 
   // Create fields
   for (unsigned i = 0; i < Count; ++i) {
-    FieldDecl *Field = FieldDecl::Create(
-        *this, CFConstantStringTagDecl, SourceLocation(), SourceLocation(),
-        &Idents.get(Fields[i].Name), Fields[i].Type, /*TInfo=*/nullptr,
-        /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
+    FieldDecl *Field =
+        FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
+                          SourceLocation(), &Idents.get(Fields[i].Name),
+                          Fields[i].Type, /*TInfo=*/nullptr,
+                          /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
     Field->setAccess(AS_public);
     CFConstantStringTagDecl->addDecl(Field);
   }
@@ -8184,11 +8211,14 @@ QualType ASTContext::getBlockDescriptorType() const {
   RD->startDefinition();
 
   QualType FieldTypes[] = {
-      UnsignedLongTy,
-      UnsignedLongTy,
+    UnsignedLongTy,
+    UnsignedLongTy,
   };
 
-  static const char *const FieldNames[] = {"reserved", "Size"};
+  static const char *const FieldNames[] = {
+    "reserved",
+    "Size"
+  };
 
   for (size_t i = 0; i < 2; ++i) {
     FieldDecl *Field = FieldDecl::Create(
@@ -8215,12 +8245,19 @@ QualType ASTContext::getBlockDescriptorExtendedType() const {
   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
   RD->startDefinition();
 
-  QualType FieldTypes[] = {UnsignedLongTy, UnsignedLongTy,
-                           getPointerType(VoidPtrTy),
-                           getPointerType(VoidPtrTy)};
+  QualType FieldTypes[] = {
+    UnsignedLongTy,
+    UnsignedLongTy,
+    getPointerType(VoidPtrTy),
+    getPointerType(VoidPtrTy)
+  };
 
-  static const char *const FieldNames[] = {"reserved", "Size", "CopyFuncPtr",
-                                           "DestroyFuncPtr"};
+  static const char *const FieldNames[] = {
+    "reserved",
+    "Size",
+    "CopyFuncPtr",
+    "DestroyFuncPtr"
+  };
 
   for (size_t i = 0; i < 4; ++i) {
     FieldDecl *Field = FieldDecl::Create(
@@ -8281,11 +8318,11 @@ LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
 /// requires copy/dispose. Note that this must match the logic
 /// in buildByrefHelpers.
-bool ASTContext::BlockRequiresCopying(QualType Ty, const VarDecl *D) {
+bool ASTContext::BlockRequiresCopying(QualType Ty,
+                                      const VarDecl *D) {
   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
-    if (!copyExpr && record->hasTrivialDestructor())
-      return false;
+    if (!copyExpr && record->hasTrivialDestructor()) return false;
 
     return true;
   }
@@ -8295,27 +8332,25 @@ bool ASTContext::BlockRequiresCopying(QualType Ty, const VarDecl *D) {
   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
     return true;
 
-  if (!Ty->isObjCRetainableType())
-    return false;
+  if (!Ty->isObjCRetainableType()) return false;
 
   Qualifiers qs = Ty.getQualifiers();
 
   // If we have lifetime, that dominates.
   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
     switch (lifetime) {
-    case Qualifiers::OCL_None:
-      llvm_unreachable("impossible");
+      case Qualifiers::OCL_None: llvm_unreachable("impossible");
 
-    // These are just bits as far as the runtime is concerned.
-    case Qualifiers::OCL_ExplicitNone:
-    case Qualifiers::OCL_Autoreleasing:
-      return false;
+      // These are just bits as far as the runtime is concerned.
+      case Qualifiers::OCL_ExplicitNone:
+      case Qualifiers::OCL_Autoreleasing:
+        return false;
 
-    // These cases should have been taken care of when checking the type's
-    // non-triviality.
-    case Qualifiers::OCL_Weak:
-    case Qualifiers::OCL_Strong:
-      llvm_unreachable("impossible");
+      // These cases should have been taken care of when checking the type's
+      // non-triviality.
+      case Qualifiers::OCL_Weak:
+      case Qualifiers::OCL_Strong:
+        llvm_unreachable("impossible");
     }
     llvm_unreachable("fell out of lifetime switch!");
   }
@@ -8324,9 +8359,10 @@ bool ASTContext::BlockRequiresCopying(QualType Ty, const VarDecl *D) {
 }
 
 bool ASTContext::getByrefLifetime(QualType Ty,
-                                  Qualifiers::ObjCLifetime &LifeTime,
-                                  bool &HasByrefExtendedLayout) const {
-  if (!getLangOpts().ObjC || getLangOpts().getGC() != LangOptions::NonGC)
+                              Qualifiers::ObjCLifetime &LifeTime,
+                              bool &HasByrefExtendedLayout) const {
+  if (!getLangOpts().ObjC ||
+      getLangOpts().getGC() != LangOptions::NonGC)
     return false;
 
   HasByrefExtendedLayout = false;
@@ -8474,8 +8510,8 @@ std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
     } else if (PType->isFunctionType())
       PType = PVDecl->getType();
     if (getLangOpts().EncodeExtendedBlockSig)
-      getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, S,
-                                        true /*Extended*/);
+      getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
+                                      S, true /*Extended*/);
     else
       getObjCEncodingForType(PType, S);
     S += charUnitsToString(ParmOffset);
@@ -8528,7 +8564,7 @@ ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
 /// method parameter or return type. If Extended, include class names and
 /// block object types.
 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
-                                                   QualType T, std::string &S,
+                                                   QualType T, std::string& S,
                                                    bool Extended) const {
   // Encode type qualifier, 'in', 'inout', etc. for the parameter.
   getObjCEncodingForTypeQualifier(QT, S);
@@ -8559,8 +8595,7 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
   // their size.
   CharUnits ParmOffset = 2 * PtrSize;
   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
-                                            E = Decl->sel_param_end();
-       PI != E; ++PI) {
+       E = Decl->sel_param_end(); PI != E; ++PI) {
     QualType PType = (*PI)->getType();
     CharUnits sz = getObjCEncodingTypeSize(PType);
     if (sz.isZero())
@@ -8577,8 +8612,7 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
   // Argument types.
   ParmOffset = 2 * PtrSize;
   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
-                                            E = Decl->sel_param_end();
-       PI != E; ++PI) {
+       E = Decl->sel_param_end(); PI != E; ++PI) {
     const ParmVarDecl *PVDecl = *PI;
     QualType PType = PVDecl->getOriginalType();
     if (const auto *AT =
@@ -8589,8 +8623,8 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
         PType = PVDecl->getType();
     } else if (PType->isFunctionType())
       PType = PVDecl->getType();
-    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), PType, S,
-                                      Extended);
+    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
+                                      PType, S, Extended);
     S += charUnitsToString(ParmOffset);
     ParmOffset += getObjCEncodingTypeSize(PType);
   }
@@ -8598,8 +8632,10 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
   return S;
 }
 
-ObjCPropertyImplDecl *ASTContext::getObjCPropertyImplDeclForPropertyDecl(
-    const ObjCPropertyDecl *PD, const Decl *Container) const {
+ObjCPropertyImplDecl *
+ASTContext::getObjCPropertyImplDeclForPropertyDecl(
+                                      const ObjCPropertyDecl *PD,
+                                      const Decl *Container) const {
   if (!Container)
     return nullptr;
   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
@@ -8649,9 +8685,8 @@ ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
   ObjCPropertyImplDecl *SynthesizePID = nullptr;
 
   if (ObjCPropertyImplDecl *PropertyImpDecl =
-          getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
-    if (PropertyImpDecl->getPropertyImplementation() ==
-        ObjCPropertyImplDecl::Dynamic)
+      getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
+    if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
       Dynamic = true;
     else
       SynthesizePID = PropertyImpDecl;
@@ -8678,17 +8713,10 @@ ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
       S += ",W";
   } else {
     switch (PD->getSetterKind()) {
-    case ObjCPropertyDecl::Assign:
-      break;
-    case ObjCPropertyDecl::Copy:
-      S += ",C";
-      break;
-    case ObjCPropertyDecl::Retain:
-      S += ",&";
-      break;
-    case ObjCPropertyDecl::Weak:
-      S += ",W";
-      break;
+    case ObjCPropertyDecl::Assign: break;
+    case ObjCPropertyDecl::Copy:   S += ",C"; break;
+    case ObjCPropertyDecl::Retain: S += ",&"; break;
+    case ObjCPropertyDecl::Weak:   S += ",W"; break;
     }
   }
 
@@ -8724,19 +8752,19 @@ ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
 /// Another legacy compatibility encoding: 32-bit longs are encoded as
 /// 'l' or 'L' , but not always.  For typedefs, we need to use
 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
-void ASTContext::getLegacyIntegralTypeEncoding(QualType &PointeeTy) const {
+void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
   if (PointeeTy->getAs<TypedefType>()) {
     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
         PointeeTy = UnsignedIntTy;
-      else if (BT->getKind() == BuiltinType::Long &&
-               getIntWidth(PointeeTy) == 32)
-        PointeeTy = IntTy;
+      else
+        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
+          PointeeTy = IntTy;
     }
   }
 }
 
-void ASTContext::getObjCEncodingForType(QualType T, std::string &S,
+void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
                                         const FieldDecl *Field,
                                         QualType *NotEncodedT) const {
   // We follow the behavior of gcc, expanding structures which are
@@ -8752,7 +8780,7 @@ void ASTContext::getObjCEncodingForType(QualType T, std::string &S,
 }
 
 void ASTContext::getObjCEncodingForPropertyType(QualType T,
-                                                std::string &S) const {
+                                                std::string& S) const {
   // Encode result type.
   // GCC has some special rules regarding encoding of properties which
   // closely resembles encoding of ivars.
@@ -8767,85 +8795,70 @@ void ASTContext::getObjCEncodingForPropertyType(QualType T,
 
 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
                                             const BuiltinType *BT) {
-  BuiltinType::Kind kind = BT->getKind();
-  switch (kind) {
-  case BuiltinType::Void:
-    return 'v';
-  case BuiltinType::Bool:
-    return 'B';
-  case BuiltinType::Char8:
-  case BuiltinType::Char_U:
-  case BuiltinType::UChar:
-    return 'C';
-  case BuiltinType::Char16:
-  case BuiltinType::UShort:
-    return 'S';
-  case BuiltinType::Char32:
-  case BuiltinType::UInt:
-    return 'I';
-  case BuiltinType::ULong:
-    return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
-  case BuiltinType::UInt128:
-    return 'T';
-  case BuiltinType::ULongLong:
-    return 'Q';
-  case BuiltinType::Char_S:
-  case BuiltinType::SChar:
-    return 'c';
-  case BuiltinType::Short:
-    return 's';
-  case BuiltinType::WChar_S:
-  case BuiltinType::WChar_U:
-  case BuiltinType::Int:
-    return 'i';
-  case BuiltinType::Long:
-    return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
-  case BuiltinType::LongLong:
-    return 'q';
-  case BuiltinType::Int128:
-    return 't';
-  case BuiltinType::Float:
-    return 'f';
-  case BuiltinType::Double:
-    return 'd';
-  case BuiltinType::LongDouble:
-    return 'D';
-  case BuiltinType::NullPtr:
-    return '*'; // like char*
+    BuiltinType::Kind kind = BT->getKind();
+    switch (kind) {
+    case BuiltinType::Void:       return 'v';
+    case BuiltinType::Bool:       return 'B';
+    case BuiltinType::Char8:
+    case BuiltinType::Char_U:
+    case BuiltinType::UChar:      return 'C';
+    case BuiltinType::Char16:
+    case BuiltinType::UShort:     return 'S';
+    case BuiltinType::Char32:
+    case BuiltinType::UInt:       return 'I';
+    case BuiltinType::ULong:
+        return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
+    case BuiltinType::UInt128:    return 'T';
+    case BuiltinType::ULongLong:  return 'Q';
+    case BuiltinType::Char_S:
+    case BuiltinType::SChar:      return 'c';
+    case BuiltinType::Short:      return 's';
+    case BuiltinType::WChar_S:
+    case BuiltinType::WChar_U:
+    case BuiltinType::Int:        return 'i';
+    case BuiltinType::Long:
+      return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
+    case BuiltinType::LongLong:   return 'q';
+    case BuiltinType::Int128:     return 't';
+    case BuiltinType::Float:      return 'f';
+    case BuiltinType::Double:     return 'd';
+    case BuiltinType::LongDouble: return 'D';
+    case BuiltinType::NullPtr:    return '*'; // like char*
 
-  case BuiltinType::BFloat16:
-  case BuiltinType::Float16:
-  case BuiltinType::Float128:
-  case BuiltinType::Ibm128:
-  case BuiltinType::Half:
-  case BuiltinType::ShortAccum:
-  case BuiltinType::Accum:
-  case BuiltinType::LongAccum:
-  case BuiltinType::UShortAccum:
-  case BuiltinType::UAccum:
-  case BuiltinType::ULongAccum:
-  case BuiltinType::ShortFract:
-  case BuiltinType::Fract:
-  case BuiltinType::LongFract:
-  case BuiltinType::UShortFract:
-  case BuiltinType::UFract:
-  case BuiltinType::ULongFract:
-  case BuiltinType::SatShortAccum:
-  case BuiltinType::SatAccum:
-  case BuiltinType::SatLongAccum:
-  case BuiltinType::SatUShortAccum:
-  case BuiltinType::SatUAccum:
-  case BuiltinType::SatULongAccum:
-  case BuiltinType::SatShortFract:
-  case BuiltinType::SatFract:
-  case BuiltinType::SatLongFract:
-  case BuiltinType::SatUShortFract:
-  case BuiltinType::SatUFract:
-  case BuiltinType::SatULongFract:
-    // FIXME: potentially need @encodes for these!
-    return ' ';
+    case BuiltinType::BFloat16:
+    case BuiltinType::Float16:
+    case BuiltinType::Float128:
+    case BuiltinType::Ibm128:
+    case BuiltinType::Half:
+    case BuiltinType::ShortAccum:
+    case BuiltinType::Accum:
+    case BuiltinType::LongAccum:
+    case BuiltinType::UShortAccum:
+    case BuiltinType::UAccum:
+    case BuiltinType::ULongAccum:
+    case BuiltinType::ShortFract:
+    case BuiltinType::Fract:
+    case BuiltinType::LongFract:
+    case BuiltinType::UShortFract:
+    case BuiltinType::UFract:
+    case BuiltinType::ULongFract:
+    case BuiltinType::SatShortAccum:
+    case BuiltinType::SatAccum:
+    case BuiltinType::SatLongAccum:
+    case BuiltinType::SatUShortAccum:
+    case BuiltinType::SatUAccum:
+    case BuiltinType::SatULongAccum:
+    case BuiltinType::SatShortFract:
+    case BuiltinType::SatFract:
+    case BuiltinType::SatLongFract:
+    case BuiltinType::SatUShortFract:
+    case BuiltinType::SatUFract:
+    case BuiltinType::SatULongFract:
+      // FIXME: potentially need @encodes for these!
+      return ' ';
 
-#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
+#define SVE_TYPE(Name, Id, SingletonId) \
+    case BuiltinType::Id:
 #include "clang/Basic/AArch64SVEACLETypes.def"
 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
 #include "clang/Basic/RISCVVTypes.def"
@@ -8853,41 +8866,44 @@ static char getObjCEncodingForPrimitiveType(const ASTContext *C,
 #include "clang/Basic/WebAssemblyReferenceTypes.def"
 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
 #include "clang/Basic/AMDGPUTypes.def"
-    {
-      DiagnosticsEngine &Diags = C->getDiagnostics();
-      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
-                                              "cannot yet @encode type %0");
-      Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
-      return ' ';
-    }
+      {
+        DiagnosticsEngine &Diags = C->getDiagnostics();
+        unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+                                                "cannot yet @encode type %0");
+        Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
+        return ' ';
+      }
 
-  case BuiltinType::ObjCId:
-  case BuiltinType::ObjCClass:
-  case BuiltinType::ObjCSel:
-    llvm_unreachable("@encoding ObjC primitive type");
+    case BuiltinType::ObjCId:
+    case BuiltinType::ObjCClass:
+    case BuiltinType::ObjCSel:
+      llvm_unreachable("@encoding ObjC primitive type");
 
     // OpenCL and placeholder types don't need @encodings.
-#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
-  case BuiltinType::Id:
+#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
+    case BuiltinType::Id:
 #include "clang/Basic/OpenCLImageTypes.def"
-#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
+#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
+    case BuiltinType::Id:
 #include "clang/Basic/OpenCLExtensionTypes.def"
-  case BuiltinType::OCLEvent:
-  case BuiltinType::OCLClkEvent:
-  case BuiltinType::OCLQueue:
-  case BuiltinType::OCLReserveID:
-  case BuiltinType::OCLSampler:
-  case BuiltinType::Dependent:
-#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
+    case BuiltinType::OCLEvent:
+    case BuiltinType::OCLClkEvent:
+    case BuiltinType::OCLQueue:
+    case BuiltinType::OCLReserveID:
+    case BuiltinType::OCLSampler:
+    case BuiltinType::Dependent:
+#define PPC_VECTOR_TYPE(Name, Id, Size) \
+    case BuiltinType::Id:
 #include "clang/Basic/PPCTypes.def"
 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
 #include "clang/Basic/HLSLIntangibleTypes.def"
 #define BUILTIN_TYPE(KIND, ID)
-#define PLACEHOLDER_TYPE(KIND, ID) case BuiltinType::KIND:
+#define PLACEHOLDER_TYPE(KIND, ID) \
+    case BuiltinType::KIND:
 #include "clang/AST/BuiltinTypes.def"
-    llvm_unreachable("invalid builtin type for @encode");
-  }
-  llvm_unreachable("invalid BuiltinType::Kind value");
+      llvm_unreachable("invalid builtin type for @encode");
+    }
+    llvm_unreachable("invalid BuiltinType::Kind value");
 }
 
 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
@@ -8902,8 +8918,8 @@ static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
   return getObjCEncodingForPrimitiveType(C, BT);
 }
 
-static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T,
-                           const FieldDecl *FD) {
+static void EncodeBitField(const ASTContext *Ctx, std::string& S,
+                           QualType T, const FieldDecl *FD) {
   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
   S += 'b';
   // The NeXT runtime encodes bit fields as b followed by the number of bits.
@@ -9049,7 +9065,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
       // combinations need to be rearranged.
       // Rewrite "in const" from "nr" to "rn"
       if (StringRef(S).ends_with("nr"))
-        S.replace(S.end() - 2, S.end(), "rn");
+        S.replace(S.end()-2, S.end(), "rn");
     }
 
     if (PointeeTy->isCharType()) {
@@ -9110,8 +9126,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
         S += llvm::utostr(CAT->getZExtSize());
       else {
-        // Variable length arrays are encoded as a regular array with 0
-        // elements.
+        //Variable length arrays are encoded as a regular array with 0 elements.
         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
                "Unknown array type!");
         S += '0';
@@ -9207,7 +9222,8 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
     if (Ty->isObjCIdType()) {
       S += "{objc_object=}";
       return;
-    } else if (Ty->isObjCClassType()) {
+    }
+    else if (Ty->isObjCClassType()) {
       S += "{objc_class=}";
       return;
     }
@@ -9223,7 +9239,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
     S += OI->getObjCRuntimeNameAsString();
     if (Options.ExpandStructures()) {
       S += '=';
-      SmallVector<const ObjCIvarDecl *, 32> Ivars;
+      SmallVector<const ObjCIvarDecl*, 32> Ivars;
       DeepCollectObjCIvars(OI, true, Ivars);
       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
         const FieldDecl *Field = Ivars[i];
@@ -9296,10 +9312,10 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
   // FIXME: we should do better than that.  'M' is available.
   case Type::MemberPointer:
   // This matches gcc's encoding, even though technically it is insufficient.
-  // FIXME. We should do a better job than gcc.
+  //FIXME. We should do a better job than gcc.
   case Type::Vector:
   case Type::ExtVector:
-    // Until we have a coherent encoding of these three types, issue warning.
+  // Until we have a coherent encoding of these three types, issue warning.
     if (NotEncodedT)
       *NotEncodedT = T;
     return;
@@ -9327,9 +9343,12 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
   case Type::Pipe:
 #define ABSTRACT_TYPE(KIND, BASE)
 #define TYPE(KIND, BASE)
-#define DEPENDENT_TYPE(KIND, BASE) case Type::KIND:
-#define NON_CANONICAL_TYPE(KIND, BASE) case Type::KIND:
-#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) case Type::KIND:
+#define DEPENDENT_TYPE(KIND, BASE) \
+  case Type::KIND:
+#define NON_CANONICAL_TYPE(KIND, BASE) \
+  case Type::KIND:
+#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
+  case Type::KIND:
 #include "clang/AST/TypeNodes.inc"
     llvm_unreachable("@encode for dependent type!");
   }
@@ -9394,16 +9413,15 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
 #ifndef NDEBUG
   uint64_t CurOffs = 0;
 #endif
-  std::multimap<uint64_t, NamedDecl *>::iterator CurLayObj =
-      FieldOrBaseOffsets.begin();
+  std::multimap<uint64_t, NamedDecl *>::iterator
+    CurLayObj = FieldOrBaseOffsets.begin();
 
   if (CXXRec && CXXRec->isDynamicClass() &&
       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
     if (FD) {
       S += "\"_vptr$";
       std::string recname = CXXRec->getNameAsString();
-      if (recname.empty())
-        recname = "?";
+      if (recname.empty()) recname = "?";
       S += recname;
       S += '"';
     }
@@ -9445,7 +9463,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
       // in the initial structure. Note that this differs from gcc which
       // expands virtual bases each time one is encountered in the hierarchy,
       // making the encoding type bigger than it really is.
-      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/ false,
+      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
                                       NotEncodedT);
       assert(!base->isEmpty());
 #ifndef NDEBUG
@@ -9479,7 +9497,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
 }
 
 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
-                                                 std::string &S) const {
+                                                 std::string& S) const {
   if (QT & Decl::OBJC_TQ_In)
     S += 'n';
   if (QT & Decl::OBJC_TQ_Inout)
@@ -9522,11 +9540,13 @@ TypedefDecl *ASTContext::getObjCClassDecl() const {
 
 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
   if (!ObjCProtocolClassDecl) {
-    ObjCProtocolClassDecl =
-        ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
-                                  SourceLocation(), &Idents.get("Protocol"),
+    ObjCProtocolClassDecl
+      = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
+                                  SourceLocation(),
+                                  &Idents.get("Protocol"),
                                   /*typeParamList=*/nullptr,
-                                  /*PrevDecl=*/nullptr, SourceLocation(), true);
+                                  /*PrevDecl=*/nullptr,
+                                  SourceLocation(), true);
   }
 
   return ObjCProtocolClassDecl;
@@ -9600,12 +9620,15 @@ CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
 
   // Create fields
   for (unsigned i = 0; i < NumFields; ++i) {
-    FieldDecl *Field = FieldDecl::Create(
-        const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
-        SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
-        /*TInfo=*/nullptr,
-        /*BitWidth=*/nullptr,
-        /*Mutable=*/false, ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
+                                         VaListTagDecl,
+                                         SourceLocation(),
+                                         SourceLocation(),
+                                         &Context->Idents.get(FieldNames[i]),
+                                         FieldTypes[i], /*TInfo=*/nullptr,
+                                         /*BitWidth=*/nullptr,
+                                         /*Mutable=*/false,
+                                         ICIS_NoInit);
     Field->setAccess(AS_public);
     VaListTagDecl->addDecl(Field);
   }
@@ -9650,11 +9673,14 @@ static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
 
   // Create fields
   for (unsigned i = 0; i < NumFields; ++i) {
-    FieldDecl *Field = FieldDecl::Create(
-        *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
-        &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
-        /*BitWidth=*/nullptr,
-        /*Mutable=*/false, ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
+                                         SourceLocation(),
+                                         SourceLocation(),
+                                         &Context->Idents.get(FieldNames[i]),
+                                         FieldTypes[i], /*TInfo=*/nullptr,
+                                         /*BitWidth=*/nullptr,
+                                         /*Mutable=*/false,
+                                         ICIS_NoInit);
     Field->setAccess(AS_public);
     VaListTagDecl->addDecl(Field);
   }
@@ -9666,7 +9692,8 @@ static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
   TypedefDecl *VaListTagTypedefDecl =
       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
 
-  QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
+  QualType VaListTagTypedefType =
+    Context->getTypedefType(VaListTagTypedefDecl);
 
   // typedef __va_list_tag __builtin_va_list[1];
   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
@@ -9704,12 +9731,15 @@ CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
 
   // Create fields
   for (unsigned i = 0; i < NumFields; ++i) {
-    FieldDecl *Field = FieldDecl::Create(
-        const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
-        SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
-        /*TInfo=*/nullptr,
-        /*BitWidth=*/nullptr,
-        /*Mutable=*/false, ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
+                                         VaListTagDecl,
+                                         SourceLocation(),
+                                         SourceLocation(),
+                                         &Context->Idents.get(FieldNames[i]),
+                                         FieldTypes[i], /*TInfo=*/nullptr,
+                                         /*BitWidth=*/nullptr,
+                                         /*Mutable=*/false,
+                                         ICIS_NoInit);
     Field->setAccess(AS_public);
     VaListTagDecl->addDecl(Field);
   }
@@ -9734,7 +9764,8 @@ static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
 }
 
-static TypedefDecl *CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
+static TypedefDecl *
+CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
   // struct __va_list
   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
   if (Context->getLangOpts().CPlusPlus) {
@@ -9752,13 +9783,16 @@ static TypedefDecl *CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
   VaListDecl->startDefinition();
 
   // void * __ap;
-  FieldDecl *Field = FieldDecl::Create(
-      const_cast<ASTContext &>(*Context), VaListDecl, SourceLocation(),
-      SourceLocation(), &Context->Idents.get("__ap"),
-      Context->getPointerType(Context->VoidTy),
-      /*TInfo=*/nullptr,
-      /*BitWidth=*/nullptr,
-      /*Mutable=*/false, ICIS_NoInit);
+  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
+                                       VaListDecl,
+                                       SourceLocation(),
+                                       SourceLocation(),
+                                       &Context->Idents.get("__ap"),
+                                       Context->getPointerType(Context->VoidTy),
+                                       /*TInfo=*/nullptr,
+                                       /*BitWidth=*/nullptr,
+                                       /*Mutable=*/false,
+                                       ICIS_NoInit);
   Field->setAccess(AS_public);
   VaListDecl->addDecl(Field);
 
@@ -9771,7 +9805,8 @@ static TypedefDecl *CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
   return Context->buildImplicitTypedef(T, "__builtin_va_list");
 }
 
-static TypedefDecl *CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
+static TypedefDecl *
+CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
   // struct __va_list_tag {
   RecordDecl *VaListTagDecl;
   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
@@ -9799,12 +9834,15 @@ static TypedefDecl *CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
 
   // Create fields
   for (unsigned i = 0; i < NumFields; ++i) {
-    FieldDecl *Field = FieldDecl::Create(
-        const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
-        SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
-        /*TInfo=*/nullptr,
-        /*BitWidth=*/nullptr,
-        /*Mutable=*/false, ICIS_NoInit);
+    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
+                                         VaListTagDecl,
+                                         SourceLocation(),
+                                         SourceLocation(),
+                                         &Context->Idents.get(FieldNames[i]),
+                                         FieldTypes[i], /*TInfo=*/nullptr,
+                                         /*BitWidth=*/nullptr,
+                                         /*Mutable=*/false,
+                                         ICIS_NoInit);
     Field->setAccess(AS_public);
     VaListTagDecl->addDecl(Field);
   }
@@ -9987,13 +10025,14 @@ ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
   assert(size > 1 && "set is not overloaded!");
 
   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
-                          size * sizeof(FunctionTemplateDecl *));
+                          size * sizeof(FunctionTemplateDecl*));
   auto *OT = new (memory) OverloadedTemplateStorage(size);
 
   NamedDecl **Storage = OT->getStorage();
   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
     NamedDecl *D = *I;
-    assert(isa<FunctionTemplateDecl>(D) || isa<UnresolvedUsingValueDecl>(D) ||
+    assert(isa<FunctionTemplateDecl>(D) ||
+           isa<UnresolvedUsingValueDecl>(D) ||
            (isa<UsingShadowDecl>(D) &&
             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
     *Storage++ = D;
@@ -10023,7 +10062,7 @@ TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
 
   void *InsertPos = nullptr;
   QualifiedTemplateName *QTN =
-      QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
   if (!QTN) {
     QTN = new (*this, alignof(QualifiedTemplateName))
         QualifiedTemplateName(NNS, TemplateKeyword, Template);
@@ -10046,7 +10085,7 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
 
   void *InsertPos = nullptr;
   DependentTemplateName *QTN =
-      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
 
   if (QTN)
     return TemplateName(QTN);
@@ -10060,7 +10099,7 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
     QTN = new (*this, alignof(DependentTemplateName))
         DependentTemplateName(NNS, Name, Canon);
     DependentTemplateName *CheckQTN =
-        DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
     assert(!CheckQTN && "Dependent type name canonicalization broken");
     (void)CheckQTN;
   }
@@ -10081,8 +10120,8 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
   DependentTemplateName::Profile(ID, NNS, Operator);
 
   void *InsertPos = nullptr;
-  DependentTemplateName *QTN =
-      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+  DependentTemplateName *QTN
+    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
 
   if (QTN)
     return TemplateName(QTN);
@@ -10096,8 +10135,8 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
     QTN = new (*this, alignof(DependentTemplateName))
         DependentTemplateName(NNS, Operator, Canon);
 
-    DependentTemplateName *CheckQTN =
-        DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
+    DependentTemplateName *CheckQTN
+      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
     assert(!CheckQTN && "Dependent template name canonicalization broken");
     (void)CheckQTN;
   }
@@ -10114,8 +10153,8 @@ TemplateName ASTContext::getSubstTemplateTemplateParm(
                                             Index, PackIndex);
 
   void *insertPos = nullptr;
-  SubstTemplateTemplateParmStorage *subst =
-      SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
+  SubstTemplateTemplateParmStorage *subst
+    = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
 
   if (!subst) {
     subst = new (*this) SubstTemplateTemplateParmStorage(
@@ -10136,8 +10175,8 @@ ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
                                                 AssociatedDecl, Index, Final);
 
   void *InsertPos = nullptr;
-  SubstTemplateTemplateParmPackStorage *Subst =
-      SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
+  SubstTemplateTemplateParmPackStorage *Subst
+    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
 
   if (!Subst) {
     Subst = new (*this) SubstTemplateTemplateParmPackStorage(
@@ -10177,28 +10216,17 @@ ASTContext::getDeducedTemplateName(TemplateName Underlying,
 /// is actually a value of type @c TargetInfo::IntType.
 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
   switch (Type) {
-  case TargetInfo::NoInt:
-    return {};
-  case TargetInfo::SignedChar:
-    return SignedCharTy;
-  case TargetInfo::UnsignedChar:
-    return UnsignedCharTy;
-  case TargetInfo::SignedShort:
-    return ShortTy;
-  case TargetInfo::UnsignedShort:
-    return UnsignedShortTy;
-  case TargetInfo::SignedInt:
-    return IntTy;
-  case TargetInfo::UnsignedInt:
-    return UnsignedIntTy;
-  case TargetInfo::SignedLong:
-    return LongTy;
-  case TargetInfo::UnsignedLong:
-    return UnsignedLongTy;
-  case TargetInfo::SignedLongLong:
-    return LongLongTy;
-  case TargetInfo::UnsignedLongLong:
-    return UnsignedLongLongTy;
+  case TargetInfo::NoInt: return {};
+  case TargetInfo::SignedChar: return SignedCharTy;
+  case TargetInfo::UnsignedChar: return UnsignedCharTy;
+  case TargetInfo::SignedShort: return ShortTy;
+  case TargetInfo::UnsignedShort: return UnsignedShortTy;
+  case TargetInfo::SignedInt: return IntTy;
+  case TargetInfo::UnsignedInt: return UnsignedIntTy;
+  case TargetInfo::SignedLong: return LongTy;
+  case TargetInfo::UnsignedLong: return UnsignedLongTy;
+  case TargetInfo::SignedLongLong: return LongLongTy;
+  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
   }
 
   llvm_unreachable("Unhandled TargetInfo::IntType value");
@@ -10245,7 +10273,8 @@ Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
 
 /// areCompatVectorTypes - Return true if the two specified vector types are
 /// compatible.
-static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS) {
+static bool areCompatVectorTypes(const VectorType *LHS,
+                                 const VectorType *RHS) {
   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
   return LHS->getElementType() == RHS->getElementType() &&
          LHS->getNumElements() == RHS->getNumElements();
@@ -10498,13 +10527,13 @@ bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
 
       Ty = Attr->getModifiedType();
 
-      // X *__strong (...)
+    // X *__strong (...)
     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
       Ty = Paren->getInnerType();
 
-      // We do not want to look through typedefs, typeof(expr),
-      // typeof(type), or any other way that the type is somehow
-      // abstracted.
+    // We do not want to look through typedefs, typeof(expr),
+    // typeof(type), or any other way that the type is somehow
+    // abstracted.
     } else {
       return false;
     }
@@ -10517,8 +10546,9 @@ bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
 
 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
 /// inheritance hierarchy of 'rProto'.
-bool ASTContext::ProtocolCompatibleWithProtocol(
-    ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const {
+bool
+ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
+                                           ObjCProtocolDecl *rProto) const {
   if (declaresSameEntity(lProto, rProto))
     return true;
   for (auto *PI : rProto->protocols())
@@ -10633,8 +10663,7 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
     }
 
     // Static class's protocols, or its super class or category protocols
-    // must be found, direct or indirect in rhs's qualifier list or it is a
-    // mismatch.
+    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
@@ -10666,8 +10695,8 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
 /// protocol qualifiers on the LHS or RHS.
 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
                                          const ObjCObjectPointerType *RHSOPT) {
-  const ObjCObjectType *LHS = LHSOPT->getObjectType();
-  const ObjCObjectType *RHS = RHSOPT->getObjectType();
+  const ObjCObjectType* LHS = LHSOPT->getObjectType();
+  const ObjCObjectType* RHS = RHSOPT->getObjectType();
 
   // If either type represents the built-in 'id' type, return true.
   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
@@ -10718,8 +10747,9 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
 /// not OK. For the return type, the opposite is not OK.
 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
-    const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT,
-    bool BlockReturnType) {
+                                         const ObjCObjectPointerType *LHSOPT,
+                                         const ObjCObjectPointerType *RHSOPT,
+                                         bool BlockReturnType) {
 
   // Function object that propagates a successful result or handles
   // __kindof types.
@@ -10734,8 +10764,9 @@ bool ASTContext::canAssignObjCInterfacesInBlockPointer(
     // Strip off __kindof and protocol qualifiers, then check whether
     // we can assign the other way.
     return canAssignObjCInterfacesInBlockPointer(
-        RHSOPT->stripObjCKindOfTypeAndQuals(*this),
-        LHSOPT->stripObjCKindOfTypeAndQuals(*this), BlockReturnType);
+             RHSOPT->stripObjCKindOfTypeAndQuals(*this),
+             LHSOPT->stripObjCKindOfTypeAndQuals(*this),
+             BlockReturnType);
   };
 
   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
@@ -10759,15 +10790,16 @@ bool ASTContext::canAssignObjCInterfacesInBlockPointer(
           (BlockReturnType ? RHSOPT : LHSOPT), false));
   }
 
-  const ObjCInterfaceType *LHS = LHSOPT->getInterfaceType();
-  const ObjCInterfaceType *RHS = RHSOPT->getInterfaceType();
-  if (LHS && RHS) { // We have 2 user-defined types.
+  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
+  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
+  if (LHS && RHS)  { // We have 2 user-defined types.
     if (LHS != RHS) {
       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
         return finish(BlockReturnType);
       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
         return finish(!BlockReturnType);
-    } else
+    }
+    else
       return true;
   }
   return false;
@@ -10775,8 +10807,8 @@ bool ASTContext::canAssignObjCInterfacesInBlockPointer(
 
 /// Comparison routine for Objective-C protocols to be used with
 /// llvm::array_pod_sort.
-static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs,
-                                      ObjCProtocolDecl *const *rhs) {
+static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
+                                      ObjCProtocolDecl * const *rhs) {
   return (*lhs)->getName().compare((*rhs)->getName());
 }
 
@@ -10785,13 +10817,15 @@ static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs,
 /// the given common base.
 /// It is used to build composite qualifier list of the composite type of
 /// the conditional expression involving two objective-c pointer objects.
-static void getIntersectionOfProtocols(
-    ASTContext &Context, const ObjCInterfaceDecl *CommonBase,
-    const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT,
-    SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
-
-  const ObjCObjectType *LHS = LHSOPT->getObjectType();
-  const ObjCObjectType *RHS = RHSOPT->getObjectType();
+static
+void getIntersectionOfProtocols(ASTContext &Context,
+                                const ObjCInterfaceDecl *CommonBase,
+                                const ObjCObjectPointerType *LHSOPT,
+                                const ObjCObjectPointerType *RHSOPT,
+      SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
+
+  const ObjCObjectType* LHS = LHSOPT->getObjectType();
+  const ObjCObjectType* RHS = RHSOPT->getObjectType();
   assert(LHS->getInterface() && "LHS must have an interface base");
   assert(RHS->getInterface() && "RHS must have an interface base");
 
@@ -10865,9 +10899,11 @@ static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
 }
 
 // Check that the given Objective-C type argument lists are equivalent.
-static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface,
+static bool sameObjCTypeArgs(ASTContext &ctx,
+                             const ObjCInterfaceDecl *iface,
                              ArrayRef<QualType> lhsArgs,
-                             ArrayRef<QualType> rhsArgs, bool stripKindOf) {
+                             ArrayRef<QualType> rhsArgs,
+                             bool stripKindOf) {
   if (lhsArgs.size() != rhsArgs.size())
     return false;
 
@@ -10903,13 +10939,13 @@ static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface,
   return true;
 }
 
-QualType
-ASTContext::areCommonBaseCompatible(const ObjCObjectPointerType *Lptr,
-                                    const ObjCObjectPointerType *Rptr) {
+QualType ASTContext::areCommonBaseCompatible(
+           const ObjCObjectPointerType *Lptr,
+           const ObjCObjectPointerType *Rptr) {
   const ObjCObjectType *LHS = Lptr->getObjectType();
   const ObjCObjectType *RHS = Rptr->getObjectType();
-  const ObjCInterfaceDecl *LDecl = LHS->getInterface();
-  const ObjCInterfaceDecl *RDecl = RHS->getInterface();
+  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
+  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
 
   if (!LDecl || !RDecl)
     return {};
@@ -10922,7 +10958,7 @@ ASTContext::areCommonBaseCompatible(const ObjCObjectPointerType *Lptr,
   // Follow the left-hand side up the class hierarchy until we either hit a
   // root or find the RHS. Record the ancestors in case we don't find it.
   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
-      LHSAncestors;
+    LHSAncestors;
   while (true) {
     // Record this ancestor. We'll need this if the common type isn't in the
     // path from the LHS to the root.
@@ -10934,8 +10970,8 @@ ASTContext::areCommonBaseCompatible(const ObjCObjectPointerType *Lptr,
       bool anyChanges = false;
       if (LHS->isSpecialized() && RHS->isSpecialized()) {
         // Both have type arguments, compare them.
-        if (!sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(),
-                              RHS->getTypeArgs(),
+        if (!sameObjCTypeArgs(*this, LHS->getInterface(),
+                              LHS->getTypeArgs(), RHS->getTypeArgs(),
                               /*stripKindOf=*/true))
           return {};
       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
@@ -10985,8 +11021,8 @@ ASTContext::areCommonBaseCompatible(const ObjCObjectPointerType *Lptr,
       bool anyChanges = false;
       if (LHS->isSpecialized() && RHS->isSpecialized()) {
         // Both have type arguments, compare them.
-        if (!sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(),
-                              RHS->getTypeArgs(),
+        if (!sameObjCTypeArgs(*this, LHS->getInterface(),
+                              LHS->getTypeArgs(), RHS->getTypeArgs(),
                               /*stripKindOf=*/true))
           return {};
       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
@@ -11047,10 +11083,9 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
-    CollectInheritedProtocols(RHS->getInterface(),
-                              SuperClassInheritedProtocols);
-    // Also, if RHS has explicit quelifiers, include them for comparing with
-    // LHS's qualifiers.
+    CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
+    // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
+    // qualifiers.
     for (auto *RHSPI : RHS->quals())
       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
     // If there is no protocols associated with RHS, it is not a match.
@@ -11079,8 +11114,8 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
 
     // If the RHS is specializd, compare type arguments.
     if (RHSSuper->isSpecialized() &&
-        !sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(),
-                          RHSSuper->getTypeArgs(),
+        !sameObjCTypeArgs(*this, LHS->getInterface(),
+                          LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
                           /*stripKindOf=*/true)) {
       return false;
     }
@@ -11156,13 +11191,13 @@ QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
   // GNU extension: two types are compatible if they appear as a function
   // argument, one of the types is a transparent union type and the other
   // type is compatible with a union member
-  QualType lmerge =
-      mergeTransparentUnionType(lhs, rhs, OfBlockPointer, Unqualified);
+  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
+                                              Unqualified);
   if (!lmerge.isNull())
     return lmerge;
 
-  QualType rmerge =
-      mergeTransparentUnionType(rhs, lhs, OfBlockPointer, Unqualified);
+  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
+                                              Unqualified);
   if (!rmerge.isNull())
     return rmerge;
 
@@ -11189,7 +11224,8 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
     if (!UnqualifiedResult)
       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
-  } else
+  }
+  else
     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
                          Unqualified);
   if (retType.isNull())
@@ -11213,8 +11249,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
   // FIXME: double check this
   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
   //                           rbase->getRegParmAttr() != 0 &&
-  //                           lbase->getRegParmAttr() !=
-  //                           rbase->getRegParmAttr()?
+  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
 
@@ -11335,10 +11370,8 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
         allRTypes = false;
     }
 
-    if (allLTypes)
-      return lhs;
-    if (allRTypes)
-      return rhs;
+    if (allLTypes) return lhs;
+    if (allRTypes) return rhs;
 
     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
     EPI.ExtInfo = einfo;
@@ -11349,10 +11382,8 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
     return getFunctionType(retType, types, EPI);
   }
 
-  if (lproto)
-    allRTypes = false;
-  if (rproto)
-    allLTypes = false;
+  if (lproto) allRTypes = false;
+  if (rproto) allLTypes = false;
 
   const FunctionProtoType *proto = lproto ? lproto : rproto;
   if (proto) {
@@ -11380,10 +11411,8 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
         return {};
     }
 
-    if (allLTypes)
-      return lhs;
-    if (allRTypes)
-      return rhs;
+    if (allLTypes) return lhs;
+    if (allRTypes) return rhs;
 
     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
     EPI.ExtInfo = einfo;
@@ -11392,10 +11421,8 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
     return getFunctionType(retType, proto->getParamTypes(), EPI);
   }
 
-  if (allLTypes)
-    return lhs;
-  if (allRTypes)
-    return rhs;
+  if (allLTypes) return lhs;
+  if (allRTypes) return rhs;
   return getFunctionNoProtoType(retType, einfo);
 }
 
@@ -11446,7 +11473,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
     RHS = RHS.getUnqualifiedType();
   }
 
-  QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS);
+  QualType LHSCan = getCanonicalType(LHS),
+           RHSCan = getCanonicalType(RHS);
 
   // If two types are identical, they are compatible.
   if (LHSCan == RHSCan)
@@ -11492,10 +11520,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
 
   // We want to consider the two function types to be the same for these
   // comparisons, just force one to the other.
-  if (LHSClass == Type::FunctionProto)
-    LHSClass = Type::FunctionNoProto;
-  if (RHSClass == Type::FunctionProto)
-    RHSClass = Type::FunctionNoProto;
+  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
+  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
 
   // Same as above for arrays
   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
@@ -11504,16 +11530,12 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
     RHSClass = Type::ConstantArray;
 
   // ObjCInterfaces are just specialized ObjCObjects.
-  if (LHSClass == Type::ObjCInterface)
-    LHSClass = Type::ObjCObject;
-  if (RHSClass == Type::ObjCInterface)
-    RHSClass = Type::ObjCObject;
+  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
+  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
 
   // Canonicalize ExtVector -> Vector.
-  if (LHSClass == Type::ExtVector)
-    LHSClass = Type::Vector;
-  if (RHSClass == Type::ExtVector)
-    RHSClass = Type::Vector;
+  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
+  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
 
   // If the canonical type classes don't match.
   if (LHSClass != RHSClass) {
@@ -11522,13 +11544,13 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
     if (const auto *ETy = LHS->getAs<EnumType>()) {
       return mergeEnumWithInteger(*this, ETy, RHS, false);
     }
-    if (const EnumType *ETy = RHS->getAs<EnumType>()) {
+    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
     }
     // allow block pointer type to match an 'id' type.
     if (OfBlockPointer && !BlockReturnType) {
-      if (LHS->isObjCIdType() && RHS->isBlockPointerType())
-        return LHS;
+       if (LHS->isObjCIdType() && RHS->isBlockPointerType())
+         return LHS;
       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
         return RHS;
     }
@@ -11569,7 +11591,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
   case Type::ExtVector:
     llvm_unreachable("Types are eliminated above");
 
-  case Type::Pointer: {
+  case Type::Pointer:
+  {
     // Merge two pointer types, while trying to preserve typedef info
     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
@@ -11577,8 +11600,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       LHSPointee = LHSPointee.getUnqualifiedType();
       RHSPointee = RHSPointee.getUnqualifiedType();
     }
-    QualType ResultType =
-        mergeTypes(LHSPointee, RHSPointee, false, Unqualified);
+    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
+                                     Unqualified);
     if (ResultType.isNull())
       return {};
     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
@@ -11587,7 +11610,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       return RHS;
     return getPointerType(ResultType);
   }
-  case Type::BlockPointer: {
+  case Type::BlockPointer:
+  {
     // Merge two block pointer types, while trying to preserve typedef info
     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
@@ -11609,8 +11633,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       RHSPointee =
           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
     }
-    QualType ResultType =
-        mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, Unqualified);
+    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
+                                     Unqualified);
     if (ResultType.isNull())
       return {};
     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
@@ -11619,7 +11643,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       return RHS;
     return getBlockPointerType(ResultType);
   }
-  case Type::Atomic: {
+  case Type::Atomic:
+  {
     // Merge two pointer types, while trying to preserve typedef info
     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
@@ -11627,7 +11652,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       LHSValue = LHSValue.getUnqualifiedType();
       RHSValue = RHSValue.getUnqualifiedType();
     }
-    QualType ResultType = mergeTypes(LHSValue, RHSValue, false, Unqualified);
+    QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
+                                     Unqualified);
     if (ResultType.isNull())
       return {};
     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
@@ -11636,9 +11662,10 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       return RHS;
     return getAtomicType(ResultType);
   }
-  case Type::ConstantArray: {
-    const ConstantArrayType *LCAT = getAsConstantArrayType(LHS);
-    const ConstantArrayType *RCAT = getAsConstantArrayType(RHS);
+  case Type::ConstantArray:
+  {
+    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
+    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
     if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
       return {};
 
@@ -11653,15 +11680,15 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
     if (ResultType.isNull())
       return {};
 
-    const VariableArrayType *LVAT = getAsVariableArrayType(LHS);
-    const VariableArrayType *RVAT = getAsVariableArrayType(RHS);
+    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
+    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
 
     // If either side is a variable array, and both are complete, check whether
     // the current dimension is definite.
     if (LVAT || RVAT) {
-      auto SizeFetch =
-          [this](const VariableArrayType *VAT,
-                 const ConstantArrayType *CAT) -> std::pair<bool, llvm::APInt> {
+      auto SizeFetch = [this](const VariableArrayType* VAT,
+          const ConstantArrayType* CAT)
+          -> std::pair<bool,llvm::APInt> {
         if (VAT) {
           std::optional<llvm::APSInt> TheInt;
           Expr *E = VAT->getSizeExpr();
@@ -11708,10 +11735,8 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
       // has to be different.
       return RHS;
     }
-    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType))
-      return LHS;
-    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType))
-      return RHS;
+    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
+    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
     return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
   }
   case Type::FunctionNoProto:
@@ -11859,7 +11884,8 @@ void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
 /// 'RHS' attributes and returns the merged version; including for function
 /// return types.
 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
-  QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS);
+  QualType LHSCan = getCanonicalType(LHS),
+  RHSCan = getCanonicalType(RHS);
   // If two types are identical, they are compatible.
   if (LHSCan == RHSCan)
     return LHS;
@@ -11871,7 +11897,7 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
     QualType NewReturnType =
         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
     QualType ResReturnType =
-        mergeObjCGCQualifiers(NewReturnType, OldReturnType);
+      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
     if (ResReturnType.isNull())
       return {};
     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
@@ -12111,7 +12137,8 @@ void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
 /// to be an Integer Constant Expression.
 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
                                   ASTContext::GetBuiltinTypeError &Error,
-                                  bool &RequiresICE, bool AllowTypeModifiers) {
+                                  bool &RequiresICE,
+                                  bool AllowTypeModifiers) {
   // Modifiers.
   int HowLong = 0;
   bool Signed = false, Unsigned = false;
@@ -12119,15 +12146,12 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
 
   // Read the prefixed modifiers first.
   bool Done = false;
-#ifndef NDEBUG
+  #ifndef NDEBUG
   bool IsSpecial = false;
-#endif
+  #endif
   while (!Done) {
     switch (*Str++) {
-    default:
-      Done = true;
-      --Str;
-      break;
+    default: Done = true; --Str; break;
     case 'I':
       RequiresICE = true;
       break;
@@ -12150,9 +12174,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
-#ifndef NDEBUG
+      #ifndef NDEBUG
       IsSpecial = true;
-#endif
+      #endif
       if (Context.getTargetInfo().getLongWidth() == 32)
         ++HowLong;
       break;
@@ -12160,9 +12184,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
       // This modifier represents int64 type.
       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
-#ifndef NDEBUG
+      #ifndef NDEBUG
       IsSpecial = true;
-#endif
+      #endif
       switch (Context.getTargetInfo().getInt64Type()) {
       default:
         llvm_unreachable("Unexpected integer type");
@@ -12178,9 +12202,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
       // This modifier represents int32 type.
       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
-#ifndef NDEBUG
+      #ifndef NDEBUG
       IsSpecial = true;
-#endif
+      #endif
       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
       default:
         llvm_unreachable("Unexpected integer type");
@@ -12198,9 +12222,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
     case 'O':
       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
-#ifndef NDEBUG
+      #ifndef NDEBUG
       IsSpecial = true;
-#endif
+      #endif
       if (Context.getLangOpts().OpenCL)
         HowLong = 1;
       else
@@ -12213,8 +12237,7 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
 
   // Read the base type.
   switch (*Str++) {
-  default:
-    llvm_unreachable("Unknown builtin type letter!");
+  default: llvm_unreachable("Unknown builtin type letter!");
   case 'x':
     assert(HowLong == 0 && !Signed && !Unsigned &&
            "Bad modifiers used with 'x'!");
@@ -12280,11 +12303,11 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
     Type = Context.BoolTy;
     break;
-  case 'z': // size_t.
+  case 'z':  // size_t.
     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
     Type = Context.getSizeType();
     break;
-  case 'w': // wchar_t.
+  case 'w':  // wchar_t.
     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
     Type = Context.getWideCharType();
     break;
@@ -12326,8 +12349,8 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
     assert(End != Str && "Missing vector size");
     Str = End;
 
-    QualType ElementType =
-        DecodeTypeFromStr(Str, Context, Error, RequiresICE, false);
+    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
+                                             RequiresICE, false);
     assert(!RequiresICE && "Can't require vector ICE");
 
     Type = Context.getScalableVectorType(ElementType, NumElements);
@@ -12354,8 +12377,8 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
     assert(End != Str && "Missing vector size");
     Str = End;
 
-    QualType ElementType =
-        DecodeTypeFromStr(Str, Context, Error, RequiresICE, false);
+    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
+                                             RequiresICE, false);
     assert(!RequiresICE && "Can't require vector ICE");
 
     // TODO: No way to make AltiVec vectors in builtins yet.
@@ -12370,14 +12393,14 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
 
     Str = End;
 
-    QualType ElementType =
-        DecodeTypeFromStr(Str, Context, Error, RequiresICE, false);
+    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
+                                             false);
     Type = Context.getExtVectorType(ElementType, NumElements);
     break;
   }
   case 'X': {
-    QualType ElementType =
-        DecodeTypeFromStr(Str, Context, Error, RequiresICE, false);
+    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
+                                             false);
     assert(!RequiresICE && "Can't require complex ICE");
     Type = Context.getComplexType(ElementType);
     break;
@@ -12424,10 +12447,7 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
   Done = !AllowTypeModifiers;
   while (!Done) {
     switch (char c = *Str++) {
-    default:
-      Done = true;
-      --Str;
-      break;
+    default: Done = true; --Str; break;
     case '*':
     case '&': {
       // Both pointers and references can have their pointee types
@@ -12437,7 +12457,8 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
       if (End != Str) {
         // Note AddrSpace == 0 is not the same as an unspecified address space.
         Type = Context.getAddrSpaceQualType(
-            Type, Context.getLangASForBuiltinAddressSpace(AddrSpace));
+          Type,
+          Context.getLangASForBuiltinAddressSpace(AddrSpace));
         Str = End;
       }
       if (c == '*')
@@ -12478,7 +12499,8 @@ QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
 }
 
 /// GetBuiltinType - Return the type for the specified builtin.
-QualType ASTContext::GetBuiltinType(unsigned Id, GetBuiltinTypeError &Error,
+QualType ASTContext::GetBuiltinType(unsigned Id,
+                                    GetBuiltinTypeError &Error,
                                     unsigned *IntegerConstantArgs) const {
   const char *TypeStr = BuiltinInfo.getTypeString(Id);
   if (TypeStr[0] == '\0') {
@@ -12490,8 +12512,8 @@ QualType ASTContext::GetBuiltinType(unsigned Id, GetBuiltinTypeError &Error,
 
   bool RequiresICE = false;
   Error = GE_None;
-  QualType ResType =
-      DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
+  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
+                                       RequiresICE, true);
   if (Error != GE_None)
     return {};
 
@@ -12524,8 +12546,8 @@ QualType ASTContext::GetBuiltinType(unsigned Id, GetBuiltinTypeError &Error,
 
   FunctionType::ExtInfo EI(getDefaultCallingConvention(
       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
-  if (BuiltinInfo.isNoReturn(Id))
-    EI = EI.withNoReturn(true);
+  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
+
 
   // We really shouldn't be making a no-proto type here.
   if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
@@ -12664,10 +12686,9 @@ adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
 }
 
 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
-  return adjustGVALinkageForExternalDefinitionKind(
-      *this, FD,
-      adjustGVALinkageForAttributes(*this, FD,
-                                    basicGVALinkageForFunction(*this, FD)));
+  return adjustGVALinkageForExternalDefinitionKind(*this, FD,
+           adjustGVALinkageForAttributes(*this, FD,
+             basicGVALinkageForFunction(*this, FD)));
 }
 
 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
@@ -12758,10 +12779,9 @@ static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
 }
 
 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
-  return adjustGVALinkageForExternalDefinitionKind(
-      *this, VD,
-      adjustGVALinkageForAttributes(*this, VD,
-                                    basicGVALinkageForVariable(*this, VD)));
+  return adjustGVALinkageForExternalDefinitionKind(*this, VD,
+           adjustGVALinkageForAttributes(*this, VD,
+             basicGVALinkageForVariable(*this, VD)));
 }
 
 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
@@ -12888,7 +12908,7 @@ void ASTContext::forEachMultiversionedFunctionVersion(
     const FunctionDecl *FD,
     llvm::function_ref<void(FunctionDecl *)> Pred) const {
   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
-  llvm::SmallDenseSet<const FunctionDecl *, 4> SeenDecls;
+  llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
   FD = FD->getMostRecentDecl();
   // FIXME: The order of traversal here matters and depends on the order of
   // lookup results, which happens to be (mostly) oldest-to-newest, but we
@@ -13115,7 +13135,7 @@ unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
 
 MangleNumberingContext &
 ASTContext::getManglingNumberContext(const DeclContext *DC) {
-  assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
+  assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
   if (!MCtx)
     MCtx = createMangleNumberingContext();
@@ -13205,7 +13225,8 @@ ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
   return Result;
 }
 
-MSGuidDecl *ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
+MSGuidDecl *
+ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
 
   llvm::FoldingSetNodeID ID;
@@ -13277,13 +13298,15 @@ bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
 }
 
-bool ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
-                                     const ObjCMethodDecl *MethodImpl) {
+bool
+ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
+                                const ObjCMethodDecl *MethodImpl) {
   // No point trying to match an unavailable/deprecated mothod.
-  if (MethodDecl->hasAttr<UnavailableAttr>() ||
-      MethodDecl->hasAttr<DeprecatedAttr>())
+  if (MethodDecl->hasAttr<UnavailableAttr>()
+      || MethodDecl->hasAttr<DeprecatedAttr>())
     return false;
-  if (MethodDecl->getObjCDeclQualifier() != MethodImpl->getObjCDeclQualifier())
+  if (MethodDecl->getObjCDeclQualifier() !=
+      MethodImpl->getObjCDeclQualifier())
     return false;
   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
     return false;
@@ -13292,9 +13315,8 @@ bool ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
     return false;
 
   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
-                                            IF = MethodDecl->param_begin(),
-                                            EM = MethodImpl->param_end(),
-                                            EF = MethodDecl->param_end();
+       IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
+       EF = MethodDecl->param_end();
        IM != EM && IF != EF; ++IM, ++IF) {
     const ParmVarDecl *DeclVar = (*IF);
     const ParmVarDecl *ImplVar = (*IM);
@@ -14448,36 +14470,35 @@ QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
   assert(Ty->isFixedPointType());
 
-  if (Ty->isSaturatedFixedPointType())
-    return Ty;
+  if (Ty->isSaturatedFixedPointType()) return Ty;
 
   switch (Ty->castAs<BuiltinType>()->getKind()) {
-  default:
-    llvm_unreachable("Not a fixed point type!");
-  case BuiltinType::ShortAccum:
-    return SatShortAccumTy;
-  case BuiltinType::Accum:
-    return SatAccumTy;
-  case BuiltinType::LongAccum:
-    return SatLongAccumTy;
-  case BuiltinType::UShortAccum:
-    return SatUnsignedShortAccumTy;
-  case BuiltinType::UAccum:
-    return SatUnsignedAccumTy;
-  case BuiltinType::ULongAccum:
-    return SatUnsignedLongAccumTy;
-  case BuiltinType::ShortFract:
-    return SatShortFractTy;
-  case BuiltinType::Fract:
-    return SatFractTy;
-  case BuiltinType::LongFract:
-    return SatLongFractTy;
-  case BuiltinType::UShortFract:
-    return SatUnsignedShortFractTy;
-  case BuiltinType::UFract:
-    return SatUnsignedFractTy;
-  case BuiltinType::ULongFract:
-    return SatUnsignedLongFractTy;
+    default:
+      llvm_unreachable("Not a fixed point type!");
+    case BuiltinType::ShortAccum:
+      return SatShortAccumTy;
+    case BuiltinType::Accum:
+      return SatAccumTy;
+    case BuiltinType::LongAccum:
+      return SatLongAccumTy;
+    case BuiltinType::UShortAccum:
+      return SatUnsignedShortAccumTy;
+    case BuiltinType::UAccum:
+      return SatUnsignedAccumTy;
+    case BuiltinType::ULongAccum:
+      return SatUnsignedLongAccumTy;
+    case BuiltinType::ShortFract:
+      return SatShortFractTy;
+    case BuiltinType::Fract:
+      return SatFractTy;
+    case BuiltinType::LongFract:
+      return SatLongFractTy;
+    case BuiltinType::UShortFract:
+      return SatUnsignedShortFractTy;
+    case BuiltinType::UFract:
+      return SatUnsignedFractTy;
+    case BuiltinType::ULongFract:
+      return SatUnsignedLongFractTy;
   }
 }
 
@@ -14493,55 +14514,56 @@ LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
 
 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
 // doesn't include ASTContext.h
-template clang::LazyGenerationalUpdatePtr<
+template
+clang::LazyGenerationalUpdatePtr<
     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
-clang::LazyGenerationalUpdatePtr<const Decl *, Decl *,
-                                 &ExternalASTSource::CompleteRedeclChain>::
-    makeValue(const clang::ASTContext &Ctx, Decl *Value);
+clang::LazyGenerationalUpdatePtr<
+    const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
+        const clang::ASTContext &Ctx, Decl *Value);
 
 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
   assert(Ty->isFixedPointType());
 
   const TargetInfo &Target = getTargetInfo();
   switch (Ty->castAs<BuiltinType>()->getKind()) {
-  default:
-    llvm_unreachable("Not a fixed point type!");
-  case BuiltinType::ShortAccum:
-  case BuiltinType::SatShortAccum:
-    return Target.getShortAccumScale();
-  case BuiltinType::Accum:
-  case BuiltinType::SatAccum:
-    return Target.getAccumScale();
-  case BuiltinType::LongAccum:
-  case BuiltinType::SatLongAccum:
-    return Target.getLongAccumScale();
-  case BuiltinType::UShortAccum:
-  case BuiltinType::SatUShortAccum:
-    return Target.getUnsignedShortAccumScale();
-  case BuiltinType::UAccum:
-  case BuiltinType::SatUAccum:
-    return Target.getUnsignedAccumScale();
-  case BuiltinType::ULongAccum:
-  case BuiltinType::SatULongAccum:
-    return Target.getUnsignedLongAccumScale();
-  case BuiltinType::ShortFract:
-  case BuiltinType::SatShortFract:
-    return Target.getShortFractScale();
-  case BuiltinType::Fract:
-  case BuiltinType::SatFract:
-    return Target.getFractScale();
-  case BuiltinType::LongFract:
-  case BuiltinType::SatLongFract:
-    return Target.getLongFractScale();
-  case BuiltinType::UShortFract:
-  case BuiltinType::SatUShortFract:
-    return Target.getUnsignedShortFractScale();
-  case BuiltinType::UFract:
-  case BuiltinType::SatUFract:
-    return Target.getUnsignedFractScale();
-  case BuiltinType::ULongFract:
-  case BuiltinType::SatULongFract:
-    return Target.getUnsignedLongFractScale();
+    default:
+      llvm_unreachable("Not a fixed point type!");
+    case BuiltinType::ShortAccum:
+    case BuiltinType::SatShortAccum:
+      return Target.getShortAccumScale();
+    case BuiltinType::Accum:
+    case BuiltinType::SatAccum:
+      return Target.getAccumScale();
+    case BuiltinType::LongAccum:
+    case BuiltinType::SatLongAccum:
+      return Target.getLongAccumScale();
+    case BuiltinType::UShortAccum:
+    case BuiltinType::SatUShortAccum:
+      return Target.getUnsignedShortAccumScale();
+    case BuiltinType::UAccum:
+    case BuiltinType::SatUAccum:
+      return Target.getUnsignedAccumScale();
+    case BuiltinType::ULongAccum:
+    case BuiltinType::SatULongAccum:
+      return Target.getUnsignedLongAccumScale();
+    case BuiltinType::ShortFract:
+    case BuiltinType::SatShortFract:
+      return Target.getShortFractScale();
+    case BuiltinType::Fract:
+    case BuiltinType::SatFract:
+      return Target.getFractScale();
+    case BuiltinType::LongFract:
+    case BuiltinType::SatLongFract:
+      return Target.getLongFractScale();
+    case BuiltinType::UShortFract:
+    case BuiltinType::SatUShortFract:
+      return Target.getUnsignedShortFractScale();
+    case BuiltinType::UFract:
+    case BuiltinType::SatUFract:
+      return Target.getUnsignedFractScale();
+    case BuiltinType::ULongFract:
+    case BuiltinType::SatULongFract:
+      return Target.getUnsignedLongFractScale();
   }
 }
 
@@ -14550,39 +14572,39 @@ unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
 
   const TargetInfo &Target = getTargetInfo();
   switch (Ty->castAs<BuiltinType>()->getKind()) {
-  default:
-    llvm_unreachable("Not a fixed point type!");
-  case BuiltinType::ShortAccum:
-  case BuiltinType::SatShortAccum:
-    return Target.getShortAccumIBits();
-  case BuiltinType::Accum:
-  case BuiltinType::SatAccum:
-    return Target.getAccumIBits();
-  case BuiltinType::LongAccum:
-  case BuiltinType::SatLongAccum:
-    return Target.getLongAccumIBits();
-  case BuiltinType::UShortAccum:
-  case BuiltinType::SatUShortAccum:
-    return Target.getUnsignedShortAccumIBits();
-  case BuiltinType::UAccum:
-  case BuiltinType::SatUAccum:
-    return Target.getUnsignedAccumIBits();
-  case BuiltinType::ULongAccum:
-  case BuiltinType::SatULongAccum:
-    return Target.getUnsignedLongAccumIBits();
-  case BuiltinType::ShortFract:
-  case BuiltinType::SatShortFract:
-  case BuiltinType::Fract:
-  case BuiltinType::SatFract:
-  case BuiltinType::LongFract:
-  case BuiltinType::SatLongFract:
-  case BuiltinType::UShortFract:
-  case BuiltinType::SatUShortFract:
-  case BuiltinType::UFract:
-  case BuiltinType::SatUFract:
-  case BuiltinType::ULongFract:
-  case BuiltinType::SatULongFract:
-    return 0;
+    default:
+      llvm_unreachable("Not a fixed point type!");
+    case BuiltinType::ShortAccum:
+    case BuiltinType::SatShortAccum:
+      return Target.getShortAccumIBits();
+    case BuiltinType::Accum:
+    case BuiltinType::SatAccum:
+      return Target.getAccumIBits();
+    case BuiltinType::LongAccum:
+    case BuiltinType::SatLongAccum:
+      return Target.getLongAccumIBits();
+    case BuiltinType::UShortAccum:
+    case BuiltinType::SatUShortAccum:
+      return Target.getUnsignedShortAccumIBits();
+    case BuiltinType::UAccum:
+    case BuiltinType::SatUAccum:
+      return Target.getUnsignedAccumIBits();
+    case BuiltinType::ULongAccum:
+    case BuiltinType::SatULongAccum:
+      return Target.getUnsignedLongAccumIBits();
+    case BuiltinType::ShortFract:
+    case BuiltinType::SatShortFract:
+    case BuiltinType::Fract:
+    case BuiltinType::SatFract:
+    case BuiltinType::LongFract:
+    case BuiltinType::SatLongFract:
+    case BuiltinType::UShortFract:
+    case BuiltinType::SatUShortFract:
+    case BuiltinType::UFract:
+    case BuiltinType::SatUFract:
+    case BuiltinType::ULongFract:
+    case BuiltinType::SatULongFract:
+      return 0;
   }
 }
 
@@ -14813,9 +14835,9 @@ OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
   return *OMPTraitInfoVector.back();
 }
 
-const StreamingDiagnostic &
-clang::operator<<(const StreamingDiagnostic &DB,
-                  const ASTContext::SectionInfo &Section) {
+const StreamingDiagnostic &clang::
+operator<<(const StreamingDiagnostic &DB,
+           const ASTContext::SectionInfo &Section) {
   if (Section.Decl)
     return DB << Section.Decl;
   return DB << "a prior #pragma section";
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.h b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
index 9aaf63a1e0adc..5decc9b420290 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuilder.h
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
@@ -10,7 +10,6 @@
 #define LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENBUILDER_H
 
 #include "CIRGenTypeCache.h"
-#include "mlir/IR/Location.h"
 #include "clang/CIR/MissingFeatures.h"
 
 #include "clang/CIR/Dialect/Builder/CIRBaseBuilder.h"

>From 56fbcba68c38c77c8a7b867abb0f3406807d772d Mon Sep 17 00:00:00 2001
From: Morris Hafner <mhafner at nvidia.com>
Date: Tue, 25 Mar 2025 15:06:36 +0000
Subject: [PATCH 09/11] Remove BinOpOverflowOp and pointer arithmetic

---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |  59 ---------
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp    | 115 +-----------------
 clang/lib/CIR/CodeGen/CIRGenFunction.h        |  10 --
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 113 -----------------
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.h   |  22 ----
 5 files changed, 2 insertions(+), 317 deletions(-)

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 3d49f88b032cb..455cc2b8b0277 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -889,65 +889,6 @@ def BinOp : CIR_Op<"binop", [Pure,
   let hasVerifier = 1;
 }
 
-
-//===----------------------------------------------------------------------===//
-// BinOpOverflowOp
-//===----------------------------------------------------------------------===//
-
-def BinOpOverflowKind : I32EnumAttr<
-    "BinOpOverflowKind",
-    "checked binary arithmetic operation kind",
-    [BinOpKind_Add, BinOpKind_Sub, BinOpKind_Mul]> {
-  let cppNamespace = "::cir";
-}
-
-def BinOpOverflowOp : CIR_Op<"binop.overflow", [Pure, SameTypeOperands]> {
-  let summary = "Perform binary integral arithmetic with overflow checking";
-  let description = [{
-    `cir.binop.overflow` performs binary arithmetic operations with overflow
-    checking on integral operands.
-
-    The `kind` argument specifies the kind of arithmetic operation to perform.
-    It can be either `add`, `sub`, or `mul`. The `lhs` and `rhs` arguments
-    specify the input operands of the arithmetic operation. The types of `lhs`
-    and `rhs` must be the same.
-
-    `cir.binop.overflow` produces two SSA values. `result` is the result of the
-    arithmetic operation truncated to its specified type. `overflow` is a
-    boolean value indicating whether overflow happens during the operation.
-
-    The exact semantic of this operation is as follows:
-
-      - `lhs` and `rhs` are promoted to an imaginary integral type that has
-        infinite precision.
-      - The arithmetic operation is performed on the promoted operands.
-      - The infinite-precision result is truncated to the type of `result`. The
-        truncated result is assigned to `result`.
-      - If the truncated result is equal to the un-truncated result, `overflow`
-        is assigned to false. Otherwise, `overflow` is assigned to true.
-  }];
-
-  let arguments = (ins Arg<BinOpOverflowKind, "arithmetic kind">:$kind,
-                       CIR_IntType:$lhs, CIR_IntType:$rhs);
-  let results = (outs CIR_IntType:$result, CIR_BoolType:$overflow);
-
-  let assemblyFormat = [{
-    `(` $kind `,` $lhs `,` $rhs `)` `:` type($lhs) `,`
-    `(` type($result) `,` type($overflow) `)`
-    attr-dict
-  }];
-
-  let builders = [
-    OpBuilder<(ins "cir::IntType":$resultTy,
-                   "cir::BinOpOverflowKind":$kind,
-                   "mlir::Value":$lhs,
-                   "mlir::Value":$rhs), [{
-      auto overflowTy = cir::BoolType::get($_builder.getContext());
-      build($_builder, $_state, resultTy, overflowTy, kind, lhs, rhs);
-    }]>
-  ];
-}
-
 //===----------------------------------------------------------------------===//
 // GlobalOp
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index 0a6ab62d6a141..d8c553275eb38 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -921,102 +921,8 @@ mlir::Value CIRGenFunction::emitPromotedScalarExpr(const Expr *e,
 static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf,
                                          const BinOpInfo &op,
                                          bool isSubtraction) {
-  // Must have binary (not unary) expr here.  Unary pointer
-  // increment/decrement doesn't use this path.
-  const BinaryOperator *expr = cast<BinaryOperator>(op.e);
-
-  mlir::Value pointer = op.lhs;
-  Expr *pointerOperand = expr->getLHS();
-  mlir::Value index = op.rhs;
-  Expr *indexOperand = expr->getRHS();
-
-  // In a subtraction, the LHS is always the pointer.
-  if (!isSubtraction && !mlir::isa<cir::PointerType>(pointer.getType())) {
-    std::swap(pointer, index);
-    std::swap(pointerOperand, indexOperand);
-  }
-
-  bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
-
-  // Some versions of glibc and gcc use idioms (particularly in their malloc
-  // routines) that add a pointer-sized integer (known to be a pointer value)
-  // to a null pointer in order to cast the value back to an integer or as
-  // part of a pointer alignment algorithm.  This is undefined behavior, but
-  // we'd like to be able to compile programs that use it.
-  //
-  // Normally, we'd generate a GEP with a null-pointer base here in response
-  // to that code, but it's also UB to dereference a pointer created that
-  // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
-  // generate a direct cast of the integer value to a pointer.
-  //
-  // The idiom (p = nullptr + N) is not met if any of the following are true:
-  //
-  //   The operation is subtraction.
-  //   The index is not pointer-sized.
-  //   The pointer type is not byte-sized.
-  //
-  if (BinaryOperator::isNullPointerArithmeticExtension(
-          cgf.getContext(), op.opcode, expr->getLHS(), expr->getRHS()))
-    return cgf.getBuilder().createIntToPtr(index, pointer.getType());
-
-  // Differently from LLVM codegen, ABI bits for index sizes is handled during
-  // LLVM lowering.
-
-  // If this is subtraction, negate the index.
-  if (isSubtraction)
-    index = cgf.getBuilder().createNeg(index);
-
-  if (cgf.sanOpts.has(SanitizerKind::ArrayBounds))
-    cgf.cgm.errorNYI("array bounds sanitizer");
-
-  const PointerType *pointerType =
-      pointerOperand->getType()->getAs<PointerType>();
-  if (!pointerType)
-    cgf.cgm.errorNYI("ObjC");
-
-  QualType elementType = pointerType->getPointeeType();
-  if (const VariableArrayType *vla =
-          cgf.getContext().getAsVariableArrayType(elementType)) {
-
-    // The element count here is the total number of non-VLA elements.
-    mlir::Value numElements = nullptr; // cgf.getVLASize(vla).NumElts;
-
-    // GEP indexes are signed, and scaling an index isn't permitted to
-    // signed-overflow, so we use the same semantics for our explicit
-    // multiply.  We suppress this if overflow is not undefined behavior.
-    mlir::Type elemTy = cgf.convertTypeForMem(vla->getElementType());
-
-    index = cgf.getBuilder().createCast(cir::CastKind::integral, index,
-                                        numElements.getType());
-    index = cgf.getBuilder().createMul(index.getLoc(), index, numElements);
-
-    if (cgf.getLangOpts().isSignedOverflowDefined()) {
-      assert(!cir::MissingFeatures::ptrStrideOp());
-      cgf.cgm.errorNYI("pointer stride");
-    } else {
-      pointer = cgf.emitCheckedInBoundsGEP(elemTy, pointer, index, isSigned,
-                                           isSubtraction, op.e->getExprLoc());
-    }
-
-    return pointer;
-  }
-  // Explicitly handle GNU void* and function pointer arithmetic extensions. The
-  // GNU void* casts amount to no-ops since our void* type is i8*, but this is
-  // future proof.
-  mlir::Type elemTy;
-  if (elementType->isVoidType() || elementType->isFunctionType())
-    elemTy = cgf.UInt8Ty;
-  else
-    elemTy = cgf.convertTypeForMem(elementType);
-
-  if (cgf.getLangOpts().isSignedOverflowDefined()) {
-    assert(!cir::MissingFeatures::ptrStrideOp());
-    cgf.cgm.errorNYI("pointer stride");
-    return pointer;
-  }
-
-  return cgf.emitCheckedInBoundsGEP(elemTy, pointer, index, isSigned,
-                                    isSubtraction, op.e->getExprLoc());
+  cgf.cgm.errorNYI(op.loc, "pointer arithmetic");
+  return {};
 }
 
 mlir::Value ScalarExprEmitter::emitMul(const BinOpInfo &ops) {
@@ -1481,20 +1387,3 @@ mlir::Value CIRGenFunction::emitScalarPrePostIncDec(const UnaryOperator *e,
   return ScalarExprEmitter(*this, builder)
       .emitScalarPrePostIncDec(e, lv, isInc, isPre);
 }
-
-mlir::Value CIRGenFunction::emitCheckedInBoundsGEP(
-    mlir::Type elemTy, mlir::Value ptr, ArrayRef<mlir::Value> idxList,
-    bool signedIndices, bool isSubtraction, SourceLocation loc) {
-  assert(!cir::MissingFeatures::ptrStrideOp());
-  if (idxList.size() != 1)
-    cgm.errorNYI("multi-index ptr arithmetic");
-  mlir::Value gepVal = nullptr;
-
-  // If the pointer overflow sanitizer isn't enabled, do nothing.
-  if (!sanOpts.has(SanitizerKind::PointerOverflow))
-    return gepVal;
-
-  assert(!cir::MissingFeatures::pointerOverflowSanitizer());
-  cgm.errorNYI("pointer overflow sanitizer");
-  return nullptr;
-}
diff --git a/clang/lib/CIR/CodeGen/CIRGenFunction.h b/clang/lib/CIR/CodeGen/CIRGenFunction.h
index aaf70603f7782..7d1fa0712c7ac 100644
--- a/clang/lib/CIR/CodeGen/CIRGenFunction.h
+++ b/clang/lib/CIR/CodeGen/CIRGenFunction.h
@@ -217,16 +217,6 @@ class CIRGenFunction : public CIRGenTypeCache {
 
   void emitDecl(const clang::Decl &d);
 
-  /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
-  /// detect undefined behavior when the pointer overflow sanitizer is enabled.
-  /// \p SignedIndices indicates whether any of the GEP indices are signed.
-  /// \p IsSubtraction indicates whether the expression used to form the GEP
-  /// is a subtraction.
-  mlir::Value emitCheckedInBoundsGEP(mlir::Type elemTy, mlir::Value ptr,
-                                     llvm::ArrayRef<mlir::Value> idxList,
-                                     bool signedIndices, bool isSubtraction,
-                                     SourceLocation loc);
-
   void emitScalarInit(const clang::Expr *init, mlir::Location loc,
                       LValue lvalue, bool capturedByInit = false);
 
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index c0588ed906d95..1a20e22dd07c5 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -1113,118 +1113,6 @@ mlir::LogicalResult CIRToLLVMBinOpLowering::matchAndRewrite(
   return mlir::LogicalResult::success();
 }
 
-mlir::LogicalResult CIRToLLVMBinOpOverflowOpLowering::matchAndRewrite(
-    cir::BinOpOverflowOp op, OpAdaptor adaptor,
-    mlir::ConversionPatternRewriter &rewriter) const {
-  auto loc = op.getLoc();
-  auto arithKind = op.getKind();
-  auto operandTy = op.getLhs().getType();
-  auto resultTy = op.getResult().getType();
-
-  auto encompassedTyInfo = computeEncompassedTypeWidth(operandTy, resultTy);
-  auto encompassedLLVMTy = rewriter.getIntegerType(encompassedTyInfo.width);
-
-  auto lhs = adaptor.getLhs();
-  auto rhs = adaptor.getRhs();
-  if (operandTy.getWidth() < encompassedTyInfo.width) {
-    if (operandTy.isSigned()) {
-      lhs = rewriter.create<mlir::LLVM::SExtOp>(loc, encompassedLLVMTy, lhs);
-      rhs = rewriter.create<mlir::LLVM::SExtOp>(loc, encompassedLLVMTy, rhs);
-    } else {
-      lhs = rewriter.create<mlir::LLVM::ZExtOp>(loc, encompassedLLVMTy, lhs);
-      rhs = rewriter.create<mlir::LLVM::ZExtOp>(loc, encompassedLLVMTy, rhs);
-    }
-  }
-
-  auto intrinName = getLLVMIntrinName(arithKind, encompassedTyInfo.sign,
-                                      encompassedTyInfo.width);
-  auto intrinNameAttr = mlir::StringAttr::get(op.getContext(), intrinName);
-
-  auto overflowLLVMTy = rewriter.getI1Type();
-  auto intrinRetTy = mlir::LLVM::LLVMStructType::getLiteral(
-      rewriter.getContext(), {encompassedLLVMTy, overflowLLVMTy});
-
-  auto callLLVMIntrinOp = rewriter.create<mlir::LLVM::CallIntrinsicOp>(
-      loc, intrinRetTy, intrinNameAttr, mlir::ValueRange{lhs, rhs});
-  auto intrinRet = callLLVMIntrinOp.getResult(0);
-
-  auto result = rewriter
-                    .create<mlir::LLVM::ExtractValueOp>(loc, intrinRet,
-                                                        ArrayRef<int64_t>{0})
-                    .getResult();
-  auto overflow = rewriter
-                      .create<mlir::LLVM::ExtractValueOp>(loc, intrinRet,
-                                                          ArrayRef<int64_t>{1})
-                      .getResult();
-
-  if (resultTy.getWidth() < encompassedTyInfo.width) {
-    auto resultLLVMTy = getTypeConverter()->convertType(resultTy);
-    auto truncResult =
-        rewriter.create<mlir::LLVM::TruncOp>(loc, resultLLVMTy, result);
-
-    // Extend the truncated result back to the encompassing type to check for
-    // any overflows during the truncation.
-    mlir::Value truncResultExt;
-    if (resultTy.isSigned())
-      truncResultExt = rewriter.create<mlir::LLVM::SExtOp>(
-          loc, encompassedLLVMTy, truncResult);
-    else
-      truncResultExt = rewriter.create<mlir::LLVM::ZExtOp>(
-          loc, encompassedLLVMTy, truncResult);
-    auto truncOverflow = rewriter.create<mlir::LLVM::ICmpOp>(
-        loc, mlir::LLVM::ICmpPredicate::ne, truncResultExt, result);
-
-    result = truncResult;
-    overflow = rewriter.create<mlir::LLVM::OrOp>(loc, overflow, truncOverflow);
-  }
-
-  auto boolLLVMTy = getTypeConverter()->convertType(op.getOverflow().getType());
-  if (boolLLVMTy != rewriter.getI1Type())
-    overflow = rewriter.create<mlir::LLVM::ZExtOp>(loc, boolLLVMTy, overflow);
-
-  rewriter.replaceOp(op, mlir::ValueRange{result, overflow});
-
-  return mlir::success();
-}
-
-std::string CIRToLLVMBinOpOverflowOpLowering::getLLVMIntrinName(
-    cir::BinOpOverflowKind opKind, bool isSigned, unsigned width) {
-  // The intrinsic name is `@llvm.{s|u}{opKind}.with.overflow.i{width}`
-
-  std::string name = "llvm.";
-
-  if (isSigned)
-    name.push_back('s');
-  else
-    name.push_back('u');
-
-  switch (opKind) {
-  case cir::BinOpOverflowKind::Add:
-    name.append("add.");
-    break;
-  case cir::BinOpOverflowKind::Sub:
-    name.append("sub.");
-    break;
-  case cir::BinOpOverflowKind::Mul:
-    name.append("mul.");
-    break;
-  }
-
-  name.append("with.overflow.i");
-  name.append(std::to_string(width));
-
-  return name;
-}
-
-CIRToLLVMBinOpOverflowOpLowering::EncompassedTypeInfo
-CIRToLLVMBinOpOverflowOpLowering::computeEncompassedTypeWidth(
-    cir::IntType operandTy, cir::IntType resultTy) {
-  auto sign = operandTy.getIsSigned() || resultTy.getIsSigned();
-  auto width = std::max(operandTy.getWidth() + (sign && operandTy.isUnsigned()),
-                        resultTy.getWidth() + (sign && resultTy.isUnsigned()));
-  return {sign, width};
-}
-
 static void prepareTypeConverter(mlir::LLVMTypeConverter &converter,
                                  mlir::DataLayout &dataLayout) {
   converter.addConversion([&](cir::PointerType type) -> mlir::Type {
@@ -1365,7 +1253,6 @@ void ConvertCIRToLLVMPass::runOnOperation() {
       // clang-format off
                CIRToLLVMBrCondOpLowering,
                CIRToLLVMBinOpLowering,
-               CIRToLLVMBinOpOverflowOpLowering,
                CIRToLLVMBrOpLowering,
                CIRToLLVMFuncOpLowering,
                CIRToLLVMTrapOpLowering,
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
index 9fb8babe3dd6c..ef0bb2deaccdf 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h
@@ -189,28 +189,6 @@ class CIRToLLVMBinOpLowering : public mlir::OpConversionPattern<cir::BinOp> {
                   mlir::ConversionPatternRewriter &) const override;
 };
 
-class CIRToLLVMBinOpOverflowOpLowering
-    : public mlir::OpConversionPattern<cir::BinOpOverflowOp> {
-public:
-  using mlir::OpConversionPattern<cir::BinOpOverflowOp>::OpConversionPattern;
-
-  mlir::LogicalResult
-  matchAndRewrite(cir::BinOpOverflowOp op, OpAdaptor,
-                  mlir::ConversionPatternRewriter &) const override;
-
-private:
-  static std::string getLLVMIntrinName(cir::BinOpOverflowKind opKind,
-                                       bool isSigned, unsigned width);
-
-  struct EncompassedTypeInfo {
-    bool sign;
-    unsigned width;
-  };
-
-  static EncompassedTypeInfo computeEncompassedTypeWidth(cir::IntType operandTy,
-                                                         cir::IntType resultTy);
-};
-
 class CIRToLLVMBrOpLowering : public mlir::OpConversionPattern<cir::BrOp> {
 public:
   using mlir::OpConversionPattern<cir::BrOp>::OpConversionPattern;

>From 455edf232b7ab3fad25ebdbabe171599a6894b01 Mon Sep 17 00:00:00 2001
From: Morris Hafner <mhafner at nvidia.com>
Date: Tue, 25 Mar 2025 15:09:30 +0000
Subject: [PATCH 10/11] foldBinOpFMF -> fastMathFlags

---
 clang/include/clang/CIR/MissingFeatures.h | 2 +-
 clang/lib/CIR/CodeGen/CIRGenBuilder.h     | 8 ++++----
 2 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/CIR/MissingFeatures.h b/clang/include/clang/CIR/MissingFeatures.h
index 3adca513b1c2d..795f5e707fbb5 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -108,7 +108,7 @@ struct MissingFeatures {
   static bool pgoUse() { return false; }
   static bool cgFPOptionsRAII() { return false; }
   static bool metaDataNode() { return false; }
-  static bool foldBinOpFMF() { return false; }
+  static bool fastMathFlags() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.h b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
index 5decc9b420290..03fb227a464a1 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuilder.h
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
@@ -163,7 +163,7 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
   mlir::Value createFSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     assert(!cir::MissingFeatures::metaDataNode());
     assert(!cir::MissingFeatures::fpConstraints());
-    assert(!cir::MissingFeatures::foldBinOpFMF());
+    assert(!cir::MissingFeatures::fastMathFlags());
 
     return create<cir::BinOp>(loc, cir::BinOpKind::Sub, lhs, rhs);
   }
@@ -171,21 +171,21 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
   mlir::Value createFAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     assert(!cir::MissingFeatures::metaDataNode());
     assert(!cir::MissingFeatures::fpConstraints());
-    assert(!cir::MissingFeatures::foldBinOpFMF());
+    assert(!cir::MissingFeatures::fastMathFlags());
 
     return create<cir::BinOp>(loc, cir::BinOpKind::Add, lhs, rhs);
   }
   mlir::Value createFMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     assert(!cir::MissingFeatures::metaDataNode());
     assert(!cir::MissingFeatures::fpConstraints());
-    assert(!cir::MissingFeatures::foldBinOpFMF());
+    assert(!cir::MissingFeatures::fastMathFlags());
 
     return create<cir::BinOp>(loc, cir::BinOpKind::Mul, lhs, rhs);
   }
   mlir::Value createFDiv(mlir::Location loc, mlir::Value lhs, mlir::Value rhs) {
     assert(!cir::MissingFeatures::metaDataNode());
     assert(!cir::MissingFeatures::fpConstraints());
-    assert(!cir::MissingFeatures::foldBinOpFMF());
+    assert(!cir::MissingFeatures::fastMathFlags());
 
     return create<cir::BinOp>(loc, cir::BinOpKind::Div, lhs, rhs);
   }

>From 4428f8b7ec208e52443ffd76aac759507c0996e1 Mon Sep 17 00:00:00 2001
From: Morris Hafner <mhafner at nvidia.com>
Date: Tue, 25 Mar 2025 19:20:28 +0000
Subject: [PATCH 11/11] - Revert ASTContecxt refactor - return nullptr -> {} -
 Add braces after else

---
 clang/include/clang/AST/ASTContext.h          |  3 ---
 clang/lib/AST/ASTContext.cpp                  | 16 ------------
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp    | 25 +++++++++++++++----
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 14 +++++++----
 clang/lib/CodeGen/CGExprScalar.cpp            | 21 +++++++++++++---
 5 files changed, 47 insertions(+), 32 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h
index a6b1ae66a4a39..af8c49e99a7ce 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2999,9 +2999,6 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
   QualType getPromotedIntegerType(QualType PromotableType) const;
 
-  /// If \p E is a widened promoted integer, get its base (unpromoted) type.
-  std::optional<QualType> getUnwidenedIntegerType(const Expr *E) const;
-
   /// Recurses in pointer/array types until it finds an Objective-C
   /// retainable type and returns its ownership.
   Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 5b882b10d423b..de868ac821745 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -7998,22 +7998,6 @@ QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
 }
 
-/// getUnwidenedIntegerType - If \p E is a widened promoted integer, get its
-/// base (unpromoted) type.
-std::optional<QualType>
-ASTContext::getUnwidenedIntegerType(const Expr *E) const {
-  const Expr *Base = E->IgnoreImpCasts();
-  if (E == Base)
-    return std::nullopt;
-
-  QualType BaseTy = Base->getType();
-  if (!isPromotableIntegerType(BaseTy) ||
-      getTypeSize(BaseTy) >= getTypeSize(E->getType()))
-    return std::nullopt;
-
-  return BaseTy;
-}
-
 /// Recurses in pointer/array types until it finds an objc retainable
 /// type and returns its ownership.
 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index d8c553275eb38..52bd3b2933744 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -89,12 +89,12 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
 
   mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType) {
     cgf.cgm.errorNYI(result.getLoc(), "floating cast for promoted value");
-    return nullptr;
+    return {};
   }
 
   mlir::Value emitUnPromotedValue(mlir::Value result, QualType exprType) {
     cgf.cgm.errorNYI(result.getLoc(), "floating cast for unpromoted value");
-    return nullptr;
+    return {};
   }
 
   mlir::Value emitPromoted(const Expr *e, QualType promotionType);
@@ -867,10 +867,25 @@ mlir::Value CIRGenFunction::emitPromotedScalarExpr(const Expr *e,
   return e->getType()->isNullPtrType();
 }
 
+/// If \p e is a widened promoted integer, get its base (unpromoted) type.
+static std::optional<QualType>
+getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e) {
+  const Expr *base = e->IgnoreImpCasts();
+  if (e == base)
+    return std::nullopt;
+
+  QualType baseTy = base->getType();
+  if (!astContext.isPromotableIntegerType(baseTy) ||
+      astContext.getTypeSize(baseTy) >= astContext.getTypeSize(e->getType()))
+    return std::nullopt;
+
+  return baseTy;
+}
+
 /// Check if \p e is a widened promoted integer.
 [[maybe_unused]] static bool isWidenedIntegerOp(const ASTContext &astContext,
                                                 const Expr *e) {
-  return astContext.getUnwidenedIntegerType(e).has_value();
+  return getUnwidenedIntegerType(astContext, e).has_value();
 }
 
 /// Check if we can skip the overflow check for \p Op.
@@ -892,12 +907,12 @@ mlir::Value CIRGenFunction::emitPromotedScalarExpr(const Expr *e,
   // Multiplication with promoted unsigned operands is a special case.
   const auto *bo = cast<BinaryOperator>(op.e);
   std::optional<QualType> optionalLHSTy =
-      astContext.getUnwidenedIntegerType(bo->getLHS());
+      getUnwidenedIntegerType(astContext, bo->getLHS());
   if (!optionalLHSTy)
     return false;
 
   std::optional<QualType> optionalRHSTy =
-      astContext.getUnwidenedIntegerType(bo->getRHS());
+      getUnwidenedIntegerType(astContext, bo->getRHS());
   if (!optionalRHSTy)
     return false;
 
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 1a20e22dd07c5..a16840cc6bfef 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -1045,8 +1045,9 @@ mlir::LogicalResult CIRToLLVMBinOpLowering::matchAndRewrite(
       }
       rewriter.replaceOpWithNewOp<mlir::LLVM::AddOp>(op, llvmTy, lhs, rhs,
                                                      getIntOverflowFlag(op));
-    } else
+    } else {
       rewriter.replaceOpWithNewOp<mlir::LLVM::FAddOp>(op, lhs, rhs);
+    }
     break;
   case cir::BinOpKind::Sub:
     if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
@@ -1060,8 +1061,9 @@ mlir::LogicalResult CIRToLLVMBinOpLowering::matchAndRewrite(
       }
       rewriter.replaceOpWithNewOp<mlir::LLVM::SubOp>(op, llvmTy, lhs, rhs,
                                                      getIntOverflowFlag(op));
-    } else
+    } else {
       rewriter.replaceOpWithNewOp<mlir::LLVM::FSubOp>(op, lhs, rhs);
+    }
     break;
   case cir::BinOpKind::Mul:
     if (mlir::isa<mlir::IntegerType>(llvmEltTy))
@@ -1077,8 +1079,9 @@ mlir::LogicalResult CIRToLLVMBinOpLowering::matchAndRewrite(
         rewriter.replaceOpWithNewOp<mlir::LLVM::UDivOp>(op, lhs, rhs);
       else
         rewriter.replaceOpWithNewOp<mlir::LLVM::SDivOp>(op, lhs, rhs);
-    } else
+    } else {
       rewriter.replaceOpWithNewOp<mlir::LLVM::FDivOp>(op, lhs, rhs);
+    }
     break;
   case cir::BinOpKind::Rem:
     if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
@@ -1087,8 +1090,9 @@ mlir::LogicalResult CIRToLLVMBinOpLowering::matchAndRewrite(
         rewriter.replaceOpWithNewOp<mlir::LLVM::URemOp>(op, lhs, rhs);
       else
         rewriter.replaceOpWithNewOp<mlir::LLVM::SRemOp>(op, lhs, rhs);
-    } else
+    } else {
       rewriter.replaceOpWithNewOp<mlir::LLVM::FRemOp>(op, lhs, rhs);
+    }
     break;
   case cir::BinOpKind::And:
     rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(op, lhs, rhs);
@@ -1251,8 +1255,8 @@ void ConvertCIRToLLVMPass::runOnOperation() {
                                             dl);
   patterns.add<
       // clang-format off
-               CIRToLLVMBrCondOpLowering,
                CIRToLLVMBinOpLowering,
+               CIRToLLVMBrCondOpLowering,
                CIRToLLVMBrOpLowering,
                CIRToLLVMFuncOpLowering,
                CIRToLLVMTrapOpLowering,
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp
index ba14391657720..eccdcdb497f84 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -168,9 +168,24 @@ static bool MustVisitNullValue(const Expr *E) {
   return E->getType()->isNullPtrType();
 }
 
+/// If \p E is a widened promoted integer, get its base (unpromoted) type.
+static std::optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
+                                                       const Expr *E) {
+  const Expr *Base = E->IgnoreImpCasts();
+  if (E == Base)
+    return std::nullopt;
+
+  QualType BaseTy = Base->getType();
+  if (!Ctx.isPromotableIntegerType(BaseTy) ||
+      Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
+    return std::nullopt;
+
+  return BaseTy;
+}
+
 /// Check if \p E is a widened promoted integer.
 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
-  return Ctx.getUnwidenedIntegerType(E).has_value();
+  return getUnwidenedIntegerType(Ctx, E).has_value();
 }
 
 /// Check if we can skip the overflow check for \p Op.
@@ -213,11 +228,11 @@ static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
   if (BO->hasExcludedOverflowPattern())
     return true;
 
-  auto OptionalLHSTy = Ctx.getUnwidenedIntegerType(BO->getLHS());
+  auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
   if (!OptionalLHSTy)
     return false;
 
-  auto OptionalRHSTy = Ctx.getUnwidenedIntegerType(BO->getRHS());
+  auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
   if (!OptionalRHSTy)
     return false;
 



More information about the cfe-commits mailing list