Coverage Report

Created: 2021-06-15 06:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/AST/ASTDiagnostic.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ASTDiagnostic.cpp - Diagnostic Printing Hooks for AST Nodes ------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements a diagnostic formatting hook for AST elements.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTDiagnostic.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTLambda.h"
16
#include "clang/AST/Attr.h"
17
#include "clang/AST/DeclObjC.h"
18
#include "clang/AST/DeclTemplate.h"
19
#include "clang/AST/ExprCXX.h"
20
#include "clang/AST/TemplateBase.h"
21
#include "clang/AST/Type.h"
22
#include "llvm/ADT/StringExtras.h"
23
#include "llvm/Support/raw_ostream.h"
24
25
using namespace clang;
26
27
// Returns a desugared version of the QualType, and marks ShouldAKA as true
28
// whenever we remove significant sugar from the type.
29
167k
static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA) {
30
167k
  QualifierCollector QC;
31
32
211k
  while (true) {
33
211k
    const Type *Ty = QC.strip(QT);
34
35
    // Don't aka just because we saw an elaborated type...
36
211k
    if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty)) {
37
5.12k
      QT = ET->desugar();
38
5.12k
      continue;
39
5.12k
    }
40
    // ... or a paren type ...
41
206k
    if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
42
1.73k
      QT = PT->desugar();
43
1.73k
      continue;
44
1.73k
    }
45
    // ... or a macro defined type ...
46
204k
    if (const MacroQualifiedType *MDT = dyn_cast<MacroQualifiedType>(Ty)) {
47
42
      QT = MDT->desugar();
48
42
      continue;
49
42
    }
50
    // ...or a substituted template type parameter ...
51
204k
    if (const SubstTemplateTypeParmType *ST =
52
204k
          dyn_cast<SubstTemplateTypeParmType>(Ty)) {
53
7.86k
      QT = ST->desugar();
54
7.86k
      continue;
55
7.86k
    }
56
    // ...or an attributed type...
57
196k
    if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
58
1.28k
      QT = AT->desugar();
59
1.28k
      continue;
60
1.28k
    }
61
    // ...or an adjusted type...
62
195k
    if (const AdjustedType *AT = dyn_cast<AdjustedType>(Ty)) {
63
95
      QT = AT->desugar();
64
95
      continue;
65
95
    }
66
    // ... or an auto type.
67
195k
    if (const AutoType *AT = dyn_cast<AutoType>(Ty)) {
68
919
      if (!AT->isSugared())
69
311
        break;
70
608
      QT = AT->desugar();
71
608
      continue;
72
919
    }
73
74
    // Desugar FunctionType if return type or any parameter type should be
75
    // desugared. Preserve nullability attribute on desugared types.
76
194k
    if (const FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
77
2.74k
      bool DesugarReturn = false;
78
2.74k
      QualType SugarRT = FT->getReturnType();
79
2.74k
      QualType RT = Desugar(Context, SugarRT, DesugarReturn);
80
2.74k
      if (auto nullability = AttributedType::stripOuterNullability(SugarRT)) {
81
4
        RT = Context.getAttributedType(
82
4
            AttributedType::getNullabilityAttrKind(*nullability), RT, RT);
83
4
      }
84
85
2.74k
      bool DesugarArgument = false;
86
2.74k
      SmallVector<QualType, 4> Args;
87
2.74k
      const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT);
88
2.74k
      if (FPT) {
89
2.71k
        for (QualType SugarPT : FPT->param_types()) {
90
2.71k
          QualType PT = Desugar(Context, SugarPT, DesugarArgument);
91
2.71k
          if (auto nullability =
92
2.71k
                  AttributedType::stripOuterNullability(SugarPT)) {
93
4
            PT = Context.getAttributedType(
94
4
                AttributedType::getNullabilityAttrKind(*nullability), PT, PT);
95
4
          }
96
2.71k
          Args.push_back(PT);
97
2.71k
        }
98
2.70k
      }
99
100
2.74k
      if (DesugarReturn || 
DesugarArgument2.72k
) {
101
58
        ShouldAKA = true;
102
58
        QT = FPT ? Context.getFunctionType(RT, Args, FPT->getExtProtoInfo())
103
58
                 : 
Context.getFunctionNoProtoType(RT, FT->getExtInfo())0
;
104
58
        break;
105
58
      }
106
2.74k
    }
107
108
    // Desugar template specializations if any template argument should be
109
    // desugared.
110
194k
    if (const TemplateSpecializationType *TST =
111
194k
            dyn_cast<TemplateSpecializationType>(Ty)) {
112
2.31k
      if (!TST->isTypeAlias()) {
113
2.25k
        bool DesugarArgument = false;
114
2.25k
        SmallVector<TemplateArgument, 4> Args;
115
8.34k
        for (unsigned I = 0, N = TST->getNumArgs(); I != N; 
++I6.08k
) {
116
6.08k
          const TemplateArgument &Arg = TST->getArg(I);
117
6.08k
          if (Arg.getKind() == TemplateArgument::Type)
118
4.95k
            Args.push_back(Desugar(Context, Arg.getAsType(), DesugarArgument));
119
1.13k
          else
120
1.13k
            Args.push_back(Arg);
121
6.08k
        }
122
123
2.25k
        if (DesugarArgument) {
124
91
          ShouldAKA = true;
125
91
          QT = Context.getTemplateSpecializationType(
126
91
              TST->getTemplateName(), Args, QT);
127
91
        }
128
2.25k
        break;
129
2.25k
      }
130
2.31k
    }
131
132
    // Don't desugar magic Objective-C types.
133
192k
    if (QualType(Ty,0) == Context.getObjCIdType() ||
134
192k
        
QualType(Ty,0) == Context.getObjCClassType()191k
||
135
192k
        
QualType(Ty,0) == Context.getObjCSelType()190k
||
136
192k
        
QualType(Ty,0) == Context.getObjCProtoType()190k
)
137
1.34k
      break;
138
139
    // Don't desugar va_list.
140
190k
    if (QualType(Ty, 0) == Context.getBuiltinVaListType() ||
141
190k
        
QualType(Ty, 0) == Context.getBuiltinMSVaListType()190k
)
142
11
      break;
143
144
    // Otherwise, do a single-step desugar.
145
190k
    QualType Underlying;
146
190k
    bool IsSugar = false;
147
190k
    switch (Ty->getTypeClass()) {
148
0
#define ABSTRACT_TYPE(Class, Base)
149
190k
#define TYPE(Class, Base) \
150
190k
case Type::Class: { \
151
190k
const Class##Type *CTy = cast<Class##Type>(Ty); \
152
190k
if (CTy->isSugared()) { \
153
30.0k
IsSugar = true; \
154
30.0k
Underlying = CTy->desugar(); \
155
30.0k
} \
156
190k
break; \
157
190k
}
158
190k
#include 
"clang/AST/TypeNodes.inc"0
159
190k
    }
160
161
    // If it wasn't sugared, we're done.
162
190k
    if (!IsSugar)
163
160k
      break;
164
165
    // If the desugared type is a vector type, we don't want to expand
166
    // it, it will turn into an attribute mess. People want their "vec4".
167
30.0k
    if (isa<VectorType>(Underlying))
168
2.42k
      break;
169
170
    // Don't desugar through the primary typedef of an anonymous type.
171
27.5k
    if (const TagType *UTT = Underlying->getAs<TagType>())
172
2.81k
      if (const TypedefType *QTT = dyn_cast<TypedefType>(QT))
173
2.74k
        if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl())
174
283
          break;
175
176
    // Record that we actually looked through an opaque type here.
177
27.3k
    ShouldAKA = true;
178
27.3k
    QT = Underlying;
179
27.3k
  }
180
181
  // If we have a pointer-like type, desugar the pointee as well.
182
  // FIXME: Handle other pointer-like types.
183
167k
  if (const PointerType *Ty = QT->getAs<PointerType>()) {
184
16.4k
    QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(),
185
16.4k
                                        ShouldAKA));
186
151k
  } else if (const auto *Ty = QT->getAs<ObjCObjectPointerType>()) {
187
4.00k
    QT = Context.getObjCObjectPointerType(Desugar(Context, Ty->getPointeeType(),
188
4.00k
                                                  ShouldAKA));
189
147k
  } else if (const LValueReferenceType *Ty = QT->getAs<LValueReferenceType>()) {
190
2.51k
    QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(),
191
2.51k
                                                ShouldAKA));
192
144k
  } else if (const RValueReferenceType *Ty = QT->getAs<RValueReferenceType>()) {
193
991
    QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(),
194
991
                                                ShouldAKA));
195
143k
  } else if (const auto *Ty = QT->getAs<ObjCObjectType>()) {
196
4.51k
    if (Ty->getBaseType().getTypePtr() != Ty && 
!ShouldAKA2.26k
) {
197
2.20k
      QualType BaseType = Desugar(Context, Ty->getBaseType(), ShouldAKA);
198
2.20k
      QT = Context.getObjCObjectType(BaseType, Ty->getTypeArgsAsWritten(),
199
2.20k
                                     llvm::makeArrayRef(Ty->qual_begin(),
200
2.20k
                                                        Ty->getNumProtocols()),
201
2.20k
                                     Ty->isKindOfTypeAsWritten());
202
2.20k
    }
203
4.51k
  }
204
205
167k
  return QC.apply(Context, QT);
206
167k
}
207
208
/// Convert the given type to a string suitable for printing as part of
209
/// a diagnostic.
210
///
211
/// There are four main criteria when determining whether we should have an
212
/// a.k.a. clause when pretty-printing a type:
213
///
214
/// 1) Some types provide very minimal sugar that doesn't impede the
215
///    user's understanding --- for example, elaborated type
216
///    specifiers.  If this is all the sugar we see, we don't want an
217
///    a.k.a. clause.
218
/// 2) Some types are technically sugared but are much more familiar
219
///    when seen in their sugared form --- for example, va_list,
220
///    vector types, and the magic Objective C types.  We don't
221
///    want to desugar these, even if we do produce an a.k.a. clause.
222
/// 3) Some types may have already been desugared previously in this diagnostic.
223
///    if this is the case, doing another "aka" would just be clutter.
224
/// 4) Two different types within the same diagnostic have the same output
225
///    string.  In this case, force an a.k.a with the desugared type when
226
///    doing so will provide additional information.
227
///
228
/// \param Context the context in which the type was allocated
229
/// \param Ty the type to print
230
/// \param QualTypeVals pointer values to QualTypes which are used in the
231
/// diagnostic message
232
static std::string
233
ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
234
                            ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
235
85.4k
                            ArrayRef<intptr_t> QualTypeVals) {
236
  // FIXME: Playing with std::string is really slow.
237
85.4k
  bool ForceAKA = false;
238
85.4k
  QualType CanTy = Ty.getCanonicalType();
239
85.4k
  std::string S = Ty.getAsString(Context.getPrintingPolicy());
240
85.4k
  std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
241
242
229k
  for (unsigned I = 0, E = QualTypeVals.size(); I != E; 
++I143k
) {
243
143k
    QualType CompareTy =
244
143k
        QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]));
245
143k
    if (CompareTy.isNull())
246
24
      continue;
247
143k
    if (CompareTy == Ty)
248
94.6k
      continue;  // Same types
249
48.9k
    QualType CompareCanTy = CompareTy.getCanonicalType();
250
48.9k
    if (CompareCanTy == CanTy)
251
315
      continue;  // Same canonical types
252
48.6k
    std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy());
253
48.6k
    bool ShouldAKA = false;
254
48.6k
    QualType CompareDesugar = Desugar(Context, CompareTy, ShouldAKA);
255
48.6k
    std::string CompareDesugarStr =
256
48.6k
        CompareDesugar.getAsString(Context.getPrintingPolicy());
257
48.6k
    if (CompareS != S && 
CompareDesugarStr != S48.5k
)
258
48.5k
      continue;  // The type string is different than the comparison string
259
                 // and the desugared comparison string.
260
61
    std::string CompareCanS =
261
61
        CompareCanTy.getAsString(Context.getPrintingPolicy());
262
263
61
    if (CompareCanS == CanS)
264
54
      continue;  // No new info from canonical type
265
266
7
    ForceAKA = true;
267
7
    break;
268
61
  }
269
270
  // Check to see if we already desugared this type in this
271
  // diagnostic.  If so, don't do it again.
272
85.4k
  bool Repeated = false;
273
165k
  for (unsigned i = 0, e = PrevArgs.size(); i != e; 
++i80.1k
) {
274
    // TODO: Handle ak_declcontext case.
275
83.2k
    if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
276
26.7k
      void *Ptr = (void*)PrevArgs[i].second;
277
26.7k
      QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
278
26.7k
      if (PrevTy == Ty) {
279
3.08k
        Repeated = true;
280
3.08k
        break;
281
3.08k
      }
282
26.7k
    }
283
83.2k
  }
284
285
  // Consider producing an a.k.a. clause if removing all the direct
286
  // sugar gives us something "significantly different".
287
85.4k
  if (!Repeated) {
288
82.3k
    bool ShouldAKA = false;
289
82.3k
    QualType DesugaredTy = Desugar(Context, Ty, ShouldAKA);
290
82.3k
    if (ShouldAKA || 
ForceAKA74.0k
) {
291
8.30k
      if (DesugaredTy == Ty) {
292
3
        DesugaredTy = Ty.getCanonicalType();
293
3
      }
294
8.30k
      std::string akaStr = DesugaredTy.getAsString(Context.getPrintingPolicy());
295
8.30k
      if (akaStr != S) {
296
8.04k
        S = "'" + S + "' (aka '" + akaStr + "')";
297
8.04k
        return S;
298
8.04k
      }
299
8.30k
    }
300
301
    // Give some additional info on vector types. These are either not desugared
302
    // or displaying complex __attribute__ expressions so add details of the
303
    // type and element count.
304
74.3k
    if (const auto *VTy = Ty->getAs<VectorType>()) {
305
4.93k
      std::string DecoratedString;
306
4.93k
      llvm::raw_string_ostream OS(DecoratedString);
307
4.93k
      const char *Values = VTy->getNumElements() > 1 ? 
"values"4.90k
:
"value"39
;
308
4.93k
      OS << "'" << S << "' (vector of " << VTy->getNumElements() << " '"
309
4.93k
         << VTy->getElementType().getAsString(Context.getPrintingPolicy())
310
4.93k
         << "' " << Values << ")";
311
4.93k
      return OS.str();
312
4.93k
    }
313
74.3k
  }
314
315
72.4k
  S = "'" + S + "'";
316
72.4k
  return S;
317
85.4k
}
318
319
static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
320
                                   QualType ToType, bool PrintTree,
321
                                   bool PrintFromType, bool ElideType,
322
                                   bool ShowColors, raw_ostream &OS);
323
324
void clang::FormatASTNodeDiagnosticArgument(
325
    DiagnosticsEngine::ArgumentKind Kind,
326
    intptr_t Val,
327
    StringRef Modifier,
328
    StringRef Argument,
329
    ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
330
    SmallVectorImpl<char> &Output,
331
    void *Cookie,
332
176k
    ArrayRef<intptr_t> QualTypeVals) {
333
176k
  ASTContext &Context = *static_cast<ASTContext*>(Cookie);
334
335
176k
  size_t OldEnd = Output.size();
336
176k
  llvm::raw_svector_ostream OS(Output);
337
176k
  bool NeedQuotes = true;
338
339
176k
  switch (Kind) {
340
0
    default: llvm_unreachable("unknown ArgumentKind");
341
82
    case DiagnosticsEngine::ak_addrspace: {
342
82
      assert(Modifier.empty() && Argument.empty() &&
343
82
             "Invalid modifier for Qualfiers argument");
344
345
0
      auto S = Qualifiers::getAddrSpaceAsString(static_cast<LangAS>(Val));
346
82
      if (S.empty()) {
347
10
        OS << (Context.getLangOpts().OpenCL ? 
"default"7
:
"generic"3
);
348
10
        OS << " address space";
349
72
      } else {
350
72
        OS << "address space";
351
72
        OS << " '" << S << "'";
352
72
      }
353
82
      NeedQuotes = false;
354
82
      break;
355
0
    }
356
141
    case DiagnosticsEngine::ak_qual: {
357
141
      assert(Modifier.empty() && Argument.empty() &&
358
141
             "Invalid modifier for Qualfiers argument");
359
360
0
      Qualifiers Q(Qualifiers::fromOpaqueValue(Val));
361
141
      auto S = Q.getAsString();
362
141
      if (S.empty()) {
363
29
        OS << "unqualified";
364
29
        NeedQuotes = false;
365
112
      } else {
366
112
        OS << S;
367
112
      }
368
141
      break;
369
0
    }
370
34.5k
    case DiagnosticsEngine::ak_qualtype_pair: {
371
34.5k
      TemplateDiffTypes &TDT = *reinterpret_cast<TemplateDiffTypes*>(Val);
372
34.5k
      QualType FromType =
373
34.5k
          QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.FromType));
374
34.5k
      QualType ToType =
375
34.5k
          QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.ToType));
376
377
34.5k
      if (FormatTemplateTypeDiff(Context, FromType, ToType, TDT.PrintTree,
378
34.5k
                                 TDT.PrintFromType, TDT.ElideType,
379
34.5k
                                 TDT.ShowColors, OS)) {
380
1.26k
        NeedQuotes = !TDT.PrintTree;
381
1.26k
        TDT.TemplateDiffUsed = true;
382
1.26k
        break;
383
1.26k
      }
384
385
      // Don't fall-back during tree printing.  The caller will handle
386
      // this case.
387
33.2k
      if (TDT.PrintTree)
388
230
        return;
389
390
      // Attempting to do a template diff on non-templates.  Set the variables
391
      // and continue with regular type printing of the appropriate type.
392
33.0k
      Val = TDT.PrintFromType ? 
TDT.FromType16.5k
:
TDT.ToType16.5k
;
393
33.0k
      Modifier = StringRef();
394
33.0k
      Argument = StringRef();
395
      // Fall through
396
33.0k
      LLVM_FALLTHROUGH;
397
33.0k
    }
398
84.3k
    case DiagnosticsEngine::ak_qualtype: {
399
84.3k
      assert(Modifier.empty() && Argument.empty() &&
400
84.3k
             "Invalid modifier for QualType argument");
401
402
0
      QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
403
84.3k
      OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, QualTypeVals);
404
84.3k
      NeedQuotes = false;
405
84.3k
      break;
406
33.0k
    }
407
30.1k
    case DiagnosticsEngine::ak_declarationname: {
408
30.1k
      if (Modifier == "objcclass" && 
Argument.empty()122
)
409
122
        OS << '+';
410
30.0k
      else if (Modifier == "objcinstance" && 
Argument.empty()585
)
411
585
        OS << '-';
412
29.4k
      else
413
29.4k
        assert(Modifier.empty() && Argument.empty() &&
414
30.1k
               "Invalid modifier for DeclarationName argument");
415
416
0
      OS << DeclarationName::getFromOpaqueInteger(Val);
417
30.1k
      break;
418
33.0k
    }
419
55.9k
    case DiagnosticsEngine::ak_nameddecl: {
420
55.9k
      bool Qualified;
421
55.9k
      if (Modifier == "q" && 
Argument.empty()8.61k
)
422
8.61k
        Qualified = true;
423
47.3k
      else {
424
47.3k
        assert(Modifier.empty() && Argument.empty() &&
425
47.3k
               "Invalid modifier for NamedDecl* argument");
426
0
        Qualified = false;
427
47.3k
      }
428
0
      const NamedDecl *ND = reinterpret_cast<const NamedDecl*>(Val);
429
55.9k
      ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), Qualified);
430
55.9k
      break;
431
33.0k
    }
432
370
    case DiagnosticsEngine::ak_nestednamespec: {
433
370
      NestedNameSpecifier *NNS = reinterpret_cast<NestedNameSpecifier*>(Val);
434
370
      NNS->print(OS, Context.getPrintingPolicy());
435
370
      NeedQuotes = false;
436
370
      break;
437
33.0k
    }
438
1.64k
    case DiagnosticsEngine::ak_declcontext: {
439
1.64k
      DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
440
1.64k
      assert(DC && "Should never have a null declaration context");
441
0
      NeedQuotes = false;
442
443
      // FIXME: Get the strings for DeclContext from some localized place
444
1.64k
      if (DC->isTranslationUnit()) {
445
58
        if (Context.getLangOpts().CPlusPlus)
446
53
          OS << "the global namespace";
447
5
        else
448
5
          OS << "the global scope";
449
1.58k
      } else if (DC->isClosure()) {
450
2
        OS << "block literal";
451
1.58k
      } else if (isLambdaCallOperator(DC)) {
452
2
        OS << "lambda expression";
453
1.58k
      } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
454
1.15k
        OS << ConvertTypeToDiagnosticString(Context,
455
1.15k
                                            Context.getTypeDeclType(Type),
456
1.15k
                                            PrevArgs, QualTypeVals);
457
1.15k
      } else {
458
429
        assert(isa<NamedDecl>(DC) && "Expected a NamedDecl");
459
0
        NamedDecl *ND = cast<NamedDecl>(DC);
460
429
        if (isa<NamespaceDecl>(ND))
461
238
          OS << "namespace ";
462
191
        else if (isa<ObjCMethodDecl>(ND))
463
0
          OS << "method ";
464
191
        else if (isa<FunctionDecl>(ND))
465
191
          OS << "function ";
466
467
429
        OS << '\'';
468
429
        ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
469
429
        OS << '\'';
470
429
      }
471
0
      break;
472
33.0k
    }
473
2.50k
    case DiagnosticsEngine::ak_attr: {
474
2.50k
      const Attr *At = reinterpret_cast<Attr *>(Val);
475
2.50k
      assert(At && "Received null Attr object!");
476
0
      OS << '\'' << At->getSpelling() << '\'';
477
2.50k
      NeedQuotes = false;
478
2.50k
      break;
479
33.0k
    }
480
176k
  }
481
482
176k
  if (NeedQuotes) {
483
87.2k
    Output.insert(Output.begin()+OldEnd, '\'');
484
87.2k
    Output.push_back('\'');
485
87.2k
  }
486
176k
}
487
488
/// TemplateDiff - A class that constructs a pretty string for a pair of
489
/// QualTypes.  For the pair of types, a diff tree will be created containing
490
/// all the information about the templates and template arguments.  Afterwards,
491
/// the tree is transformed to a string according to the options passed in.
492
namespace {
493
class TemplateDiff {
494
  /// Context - The ASTContext which is used for comparing template arguments.
495
  ASTContext &Context;
496
497
  /// Policy - Used during expression printing.
498
  PrintingPolicy Policy;
499
500
  /// ElideType - Option to elide identical types.
501
  bool ElideType;
502
503
  /// PrintTree - Format output string as a tree.
504
  bool PrintTree;
505
506
  /// ShowColor - Diagnostics support color, so bolding will be used.
507
  bool ShowColor;
508
509
  /// FromTemplateType - When single type printing is selected, this is the
510
  /// type to be be printed.  When tree printing is selected, this type will
511
  /// show up first in the tree.
512
  QualType FromTemplateType;
513
514
  /// ToTemplateType - The type that FromType is compared to.  Only in tree
515
  /// printing will this type be outputed.
516
  QualType ToTemplateType;
517
518
  /// OS - The stream used to construct the output strings.
519
  raw_ostream &OS;
520
521
  /// IsBold - Keeps track of the bold formatting for the output string.
522
  bool IsBold;
523
524
  /// DiffTree - A tree representation the differences between two types.
525
  class DiffTree {
526
  public:
527
    /// DiffKind - The difference in a DiffNode.  Fields of
528
    /// TemplateArgumentInfo needed by each difference can be found in the
529
    /// Set* and Get* functions.
530
    enum DiffKind {
531
      /// Incomplete or invalid node.
532
      Invalid,
533
      /// Another level of templates
534
      Template,
535
      /// Type difference, all type differences except those falling under
536
      /// the Template difference.
537
      Type,
538
      /// Expression difference, this is only when both arguments are
539
      /// expressions.  If one argument is an expression and the other is
540
      /// Integer or Declaration, then use that diff type instead.
541
      Expression,
542
      /// Template argument difference
543
      TemplateTemplate,
544
      /// Integer difference
545
      Integer,
546
      /// Declaration difference, nullptr arguments are included here
547
      Declaration,
548
      /// One argument being integer and the other being declaration
549
      FromIntegerAndToDeclaration,
550
      FromDeclarationAndToInteger
551
    };
552
553
  private:
554
    /// TemplateArgumentInfo - All the information needed to pretty print
555
    /// a template argument.  See the Set* and Get* functions to see which
556
    /// fields are used for each DiffKind.
557
    struct TemplateArgumentInfo {
558
      QualType ArgType;
559
      Qualifiers Qual;
560
      llvm::APSInt Val;
561
      bool IsValidInt = false;
562
      Expr *ArgExpr = nullptr;
563
      TemplateDecl *TD = nullptr;
564
      ValueDecl *VD = nullptr;
565
      bool NeedAddressOf = false;
566
      bool IsNullPtr = false;
567
      bool IsDefault = false;
568
    };
569
570
    /// DiffNode - The root node stores the original type.  Each child node
571
    /// stores template arguments of their parents.  For templated types, the
572
    /// template decl is also stored.
573
    struct DiffNode {
574
      DiffKind Kind = Invalid;
575
576
      /// NextNode - The index of the next sibling node or 0.
577
      unsigned NextNode = 0;
578
579
      /// ChildNode - The index of the first child node or 0.
580
      unsigned ChildNode = 0;
581
582
      /// ParentNode - The index of the parent node.
583
      unsigned ParentNode = 0;
584
585
      TemplateArgumentInfo FromArgInfo, ToArgInfo;
586
587
      /// Same - Whether the two arguments evaluate to the same value.
588
      bool Same = false;
589
590
38.2k
      DiffNode(unsigned ParentNode = 0) : ParentNode(ParentNode) {}
591
    };
592
593
    /// FlatTree - A flattened tree used to store the DiffNodes.
594
    SmallVector<DiffNode, 16> FlatTree;
595
596
    /// CurrentNode - The index of the current node being used.
597
    unsigned CurrentNode;
598
599
    /// NextFreeNode - The index of the next unused node.  Used when creating
600
    /// child nodes.
601
    unsigned NextFreeNode;
602
603
    /// ReadNode - The index of the current node being read.
604
    unsigned ReadNode;
605
606
  public:
607
34.5k
    DiffTree() : CurrentNode(0), NextFreeNode(1), ReadNode(0) {
608
34.5k
      FlatTree.push_back(DiffNode());
609
34.5k
    }
610
611
    // Node writing functions, one for each valid DiffKind element.
612
    void SetTemplateDiff(TemplateDecl *FromTD, TemplateDecl *ToTD,
613
                         Qualifiers FromQual, Qualifiers ToQual,
614
1.47k
                         bool FromDefault, bool ToDefault) {
615
1.47k
      assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty.");
616
0
      FlatTree[CurrentNode].Kind = Template;
617
1.47k
      FlatTree[CurrentNode].FromArgInfo.TD = FromTD;
618
1.47k
      FlatTree[CurrentNode].ToArgInfo.TD = ToTD;
619
1.47k
      FlatTree[CurrentNode].FromArgInfo.Qual = FromQual;
620
1.47k
      FlatTree[CurrentNode].ToArgInfo.Qual = ToQual;
621
1.47k
      SetDefault(FromDefault, ToDefault);
622
1.47k
    }
623
624
    void SetTypeDiff(QualType FromType, QualType ToType, bool FromDefault,
625
2.12k
                     bool ToDefault) {
626
2.12k
      assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty.");
627
0
      FlatTree[CurrentNode].Kind = Type;
628
2.12k
      FlatTree[CurrentNode].FromArgInfo.ArgType = FromType;
629
2.12k
      FlatTree[CurrentNode].ToArgInfo.ArgType = ToType;
630
2.12k
      SetDefault(FromDefault, ToDefault);
631
2.12k
    }
632
633
    void SetExpressionDiff(Expr *FromExpr, Expr *ToExpr, bool FromDefault,
634
104
                           bool ToDefault) {
635
104
      assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty.");
636
0
      FlatTree[CurrentNode].Kind = Expression;
637
104
      FlatTree[CurrentNode].FromArgInfo.ArgExpr = FromExpr;
638
104
      FlatTree[CurrentNode].ToArgInfo.ArgExpr = ToExpr;
639
104
      SetDefault(FromDefault, ToDefault);
640
104
    }
641
642
    void SetTemplateTemplateDiff(TemplateDecl *FromTD, TemplateDecl *ToTD,
643
110
                                 bool FromDefault, bool ToDefault) {
644
110
      assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty.");
645
0
      FlatTree[CurrentNode].Kind = TemplateTemplate;
646
110
      FlatTree[CurrentNode].FromArgInfo.TD = FromTD;
647
110
      FlatTree[CurrentNode].ToArgInfo.TD = ToTD;
648
110
      SetDefault(FromDefault, ToDefault);
649
110
    }
650
651
    void SetIntegerDiff(const llvm::APSInt &FromInt, const llvm::APSInt &ToInt,
652
                        bool IsValidFromInt, bool IsValidToInt,
653
                        QualType FromIntType, QualType ToIntType,
654
                        Expr *FromExpr, Expr *ToExpr, bool FromDefault,
655
548
                        bool ToDefault) {
656
548
      assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty.");
657
0
      FlatTree[CurrentNode].Kind = Integer;
658
548
      FlatTree[CurrentNode].FromArgInfo.Val = FromInt;
659
548
      FlatTree[CurrentNode].ToArgInfo.Val = ToInt;
660
548
      FlatTree[CurrentNode].FromArgInfo.IsValidInt = IsValidFromInt;
661
548
      FlatTree[CurrentNode].ToArgInfo.IsValidInt = IsValidToInt;
662
548
      FlatTree[CurrentNode].FromArgInfo.ArgType = FromIntType;
663
548
      FlatTree[CurrentNode].ToArgInfo.ArgType = ToIntType;
664
548
      FlatTree[CurrentNode].FromArgInfo.ArgExpr = FromExpr;
665
548
      FlatTree[CurrentNode].ToArgInfo.ArgExpr = ToExpr;
666
548
      SetDefault(FromDefault, ToDefault);
667
548
    }
668
669
    void SetDeclarationDiff(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
670
                            bool FromAddressOf, bool ToAddressOf,
671
                            bool FromNullPtr, bool ToNullPtr, Expr *FromExpr,
672
518
                            Expr *ToExpr, bool FromDefault, bool ToDefault) {
673
518
      assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty.");
674
0
      FlatTree[CurrentNode].Kind = Declaration;
675
518
      FlatTree[CurrentNode].FromArgInfo.VD = FromValueDecl;
676
518
      FlatTree[CurrentNode].ToArgInfo.VD = ToValueDecl;
677
518
      FlatTree[CurrentNode].FromArgInfo.NeedAddressOf = FromAddressOf;
678
518
      FlatTree[CurrentNode].ToArgInfo.NeedAddressOf = ToAddressOf;
679
518
      FlatTree[CurrentNode].FromArgInfo.IsNullPtr = FromNullPtr;
680
518
      FlatTree[CurrentNode].ToArgInfo.IsNullPtr = ToNullPtr;
681
518
      FlatTree[CurrentNode].FromArgInfo.ArgExpr = FromExpr;
682
518
      FlatTree[CurrentNode].ToArgInfo.ArgExpr = ToExpr;
683
518
      SetDefault(FromDefault, ToDefault);
684
518
    }
685
686
    void SetFromDeclarationAndToIntegerDiff(
687
        ValueDecl *FromValueDecl, bool FromAddressOf, bool FromNullPtr,
688
        Expr *FromExpr, const llvm::APSInt &ToInt, bool IsValidToInt,
689
39
        QualType ToIntType, Expr *ToExpr, bool FromDefault, bool ToDefault) {
690
39
      assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty.");
691
0
      FlatTree[CurrentNode].Kind = FromDeclarationAndToInteger;
692
39
      FlatTree[CurrentNode].FromArgInfo.VD = FromValueDecl;
693
39
      FlatTree[CurrentNode].FromArgInfo.NeedAddressOf = FromAddressOf;
694
39
      FlatTree[CurrentNode].FromArgInfo.IsNullPtr = FromNullPtr;
695
39
      FlatTree[CurrentNode].FromArgInfo.ArgExpr = FromExpr;
696
39
      FlatTree[CurrentNode].ToArgInfo.Val = ToInt;
697
39
      FlatTree[CurrentNode].ToArgInfo.IsValidInt = IsValidToInt;
698
39
      FlatTree[CurrentNode].ToArgInfo.ArgType = ToIntType;
699
39
      FlatTree[CurrentNode].ToArgInfo.ArgExpr = ToExpr;
700
39
      SetDefault(FromDefault, ToDefault);
701
39
    }
702
703
    void SetFromIntegerAndToDeclarationDiff(
704
        const llvm::APSInt &FromInt, bool IsValidFromInt, QualType FromIntType,
705
        Expr *FromExpr, ValueDecl *ToValueDecl, bool ToAddressOf,
706
39
        bool ToNullPtr, Expr *ToExpr, bool FromDefault, bool ToDefault) {
707
39
      assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty.");
708
0
      FlatTree[CurrentNode].Kind = FromIntegerAndToDeclaration;
709
39
      FlatTree[CurrentNode].FromArgInfo.Val = FromInt;
710
39
      FlatTree[CurrentNode].FromArgInfo.IsValidInt = IsValidFromInt;
711
39
      FlatTree[CurrentNode].FromArgInfo.ArgType = FromIntType;
712
39
      FlatTree[CurrentNode].FromArgInfo.ArgExpr = FromExpr;
713
39
      FlatTree[CurrentNode].ToArgInfo.VD = ToValueDecl;
714
39
      FlatTree[CurrentNode].ToArgInfo.NeedAddressOf = ToAddressOf;
715
39
      FlatTree[CurrentNode].ToArgInfo.IsNullPtr = ToNullPtr;
716
39
      FlatTree[CurrentNode].ToArgInfo.ArgExpr = ToExpr;
717
39
      SetDefault(FromDefault, ToDefault);
718
39
    }
719
720
    /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
721
4.95k
    void SetDefault(bool FromDefault, bool ToDefault) {
722
4.95k
      assert((!FromDefault || !ToDefault) && "Both arguments cannot be default.");
723
0
      FlatTree[CurrentNode].FromArgInfo.IsDefault = FromDefault;
724
4.95k
      FlatTree[CurrentNode].ToArgInfo.IsDefault = ToDefault;
725
4.95k
    }
726
727
    /// SetSame - Sets the same flag of the current node.
728
3.39k
    void SetSame(bool Same) {
729
3.39k
      FlatTree[CurrentNode].Same = Same;
730
3.39k
    }
731
732
    /// SetKind - Sets the current node's type.
733
0
    void SetKind(DiffKind Kind) {
734
0
      FlatTree[CurrentNode].Kind = Kind;
735
0
    }
736
737
    /// Up - Changes the node to the parent of the current node.
738
3.69k
    void Up() {
739
3.69k
      assert(FlatTree[CurrentNode].Kind != Invalid &&
740
3.69k
             "Cannot exit node before setting node information.");
741
0
      CurrentNode = FlatTree[CurrentNode].ParentNode;
742
3.69k
    }
743
744
    /// AddNode - Adds a child node to the current node, then sets that node
745
    /// node as the current node.
746
3.69k
    void AddNode() {
747
3.69k
      assert(FlatTree[CurrentNode].Kind == Template &&
748
3.69k
             "Only Template nodes can have children nodes.");
749
0
      FlatTree.push_back(DiffNode(CurrentNode));
750
3.69k
      DiffNode &Node = FlatTree[CurrentNode];
751
3.69k
      if (Node.ChildNode == 0) {
752
        // If a child node doesn't exist, add one.
753
1.46k
        Node.ChildNode = NextFreeNode;
754
2.22k
      } else {
755
        // If a child node exists, find the last child node and add a
756
        // next node to it.
757
2.22k
        unsigned i;
758
235k
        for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
759
233k
             i = FlatTree[i].NextNode) {
760
233k
        }
761
2.22k
        FlatTree[i].NextNode = NextFreeNode;
762
2.22k
      }
763
3.69k
      CurrentNode = NextFreeNode;
764
3.69k
      ++NextFreeNode;
765
3.69k
    }
766
767
    // Node reading functions.
768
    /// StartTraverse - Prepares the tree for recursive traversal.
769
34.5k
    void StartTraverse() {
770
34.5k
      ReadNode = 0;
771
34.5k
      CurrentNode = NextFreeNode;
772
34.5k
      NextFreeNode = 0;
773
34.5k
    }
774
775
    /// Parent - Move the current read node to its parent.
776
1.46k
    void Parent() {
777
1.46k
      ReadNode = FlatTree[ReadNode].ParentNode;
778
1.46k
    }
779
780
    void GetTemplateDiff(TemplateDecl *&FromTD, TemplateDecl *&ToTD,
781
1.47k
                         Qualifiers &FromQual, Qualifiers &ToQual) {
782
1.47k
      assert(FlatTree[ReadNode].Kind == Template && "Unexpected kind.");
783
0
      FromTD = FlatTree[ReadNode].FromArgInfo.TD;
784
1.47k
      ToTD = FlatTree[ReadNode].ToArgInfo.TD;
785
1.47k
      FromQual = FlatTree[ReadNode].FromArgInfo.Qual;
786
1.47k
      ToQual = FlatTree[ReadNode].ToArgInfo.Qual;
787
1.47k
    }
788
789
1.30k
    void GetTypeDiff(QualType &FromType, QualType &ToType) {
790
1.30k
      assert(FlatTree[ReadNode].Kind == Type && "Unexpected kind");
791
0
      FromType = FlatTree[ReadNode].FromArgInfo.ArgType;
792
1.30k
      ToType = FlatTree[ReadNode].ToArgInfo.ArgType;
793
1.30k
    }
794
795
98
    void GetExpressionDiff(Expr *&FromExpr, Expr *&ToExpr) {
796
98
      assert(FlatTree[ReadNode].Kind == Expression && "Unexpected kind");
797
0
      FromExpr = FlatTree[ReadNode].FromArgInfo.ArgExpr;
798
98
      ToExpr = FlatTree[ReadNode].ToArgInfo.ArgExpr;
799
98
    }
800
801
92
    void GetTemplateTemplateDiff(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
802
92
      assert(FlatTree[ReadNode].Kind == TemplateTemplate && "Unexpected kind.");
803
0
      FromTD = FlatTree[ReadNode].FromArgInfo.TD;
804
92
      ToTD = FlatTree[ReadNode].ToArgInfo.TD;
805
92
    }
806
807
    void GetIntegerDiff(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
808
                        bool &IsValidFromInt, bool &IsValidToInt,
809
                        QualType &FromIntType, QualType &ToIntType,
810
467
                        Expr *&FromExpr, Expr *&ToExpr) {
811
467
      assert(FlatTree[ReadNode].Kind == Integer && "Unexpected kind.");
812
0
      FromInt = FlatTree[ReadNode].FromArgInfo.Val;
813
467
      ToInt = FlatTree[ReadNode].ToArgInfo.Val;
814
467
      IsValidFromInt = FlatTree[ReadNode].FromArgInfo.IsValidInt;
815
467
      IsValidToInt = FlatTree[ReadNode].ToArgInfo.IsValidInt;
816
467
      FromIntType = FlatTree[ReadNode].FromArgInfo.ArgType;
817
467
      ToIntType = FlatTree[ReadNode].ToArgInfo.ArgType;
818
467
      FromExpr = FlatTree[ReadNode].FromArgInfo.ArgExpr;
819
467
      ToExpr = FlatTree[ReadNode].ToArgInfo.ArgExpr;
820
467
    }
821
822
    void GetDeclarationDiff(ValueDecl *&FromValueDecl, ValueDecl *&ToValueDecl,
823
                            bool &FromAddressOf, bool &ToAddressOf,
824
                            bool &FromNullPtr, bool &ToNullPtr, Expr *&FromExpr,
825
458
                            Expr *&ToExpr) {
826
458
      assert(FlatTree[ReadNode].Kind == Declaration && "Unexpected kind.");
827
0
      FromValueDecl = FlatTree[ReadNode].FromArgInfo.VD;
828
458
      ToValueDecl = FlatTree[ReadNode].ToArgInfo.VD;
829
458
      FromAddressOf = FlatTree[ReadNode].FromArgInfo.NeedAddressOf;
830
458
      ToAddressOf = FlatTree[ReadNode].ToArgInfo.NeedAddressOf;
831
458
      FromNullPtr = FlatTree[ReadNode].FromArgInfo.IsNullPtr;
832
458
      ToNullPtr = FlatTree[ReadNode].ToArgInfo.IsNullPtr;
833
458
      FromExpr = FlatTree[ReadNode].FromArgInfo.ArgExpr;
834
458
      ToExpr = FlatTree[ReadNode].ToArgInfo.ArgExpr;
835
458
    }
836
837
    void GetFromDeclarationAndToIntegerDiff(
838
        ValueDecl *&FromValueDecl, bool &FromAddressOf, bool &FromNullPtr,
839
        Expr *&FromExpr, llvm::APSInt &ToInt, bool &IsValidToInt,
840
39
        QualType &ToIntType, Expr *&ToExpr) {
841
39
      assert(FlatTree[ReadNode].Kind == FromDeclarationAndToInteger &&
842
39
             "Unexpected kind.");
843
0
      FromValueDecl = FlatTree[ReadNode].FromArgInfo.VD;
844
39
      FromAddressOf = FlatTree[ReadNode].FromArgInfo.NeedAddressOf;
845
39
      FromNullPtr = FlatTree[ReadNode].FromArgInfo.IsNullPtr;
846
39
      FromExpr = FlatTree[ReadNode].FromArgInfo.ArgExpr;
847
39
      ToInt = FlatTree[ReadNode].ToArgInfo.Val;
848
39
      IsValidToInt = FlatTree[ReadNode].ToArgInfo.IsValidInt;
849
39
      ToIntType = FlatTree[ReadNode].ToArgInfo.ArgType;
850
39
      ToExpr = FlatTree[ReadNode].ToArgInfo.ArgExpr;
851
39
    }
852
853
    void GetFromIntegerAndToDeclarationDiff(
854
        llvm::APSInt &FromInt, bool &IsValidFromInt, QualType &FromIntType,
855
        Expr *&FromExpr, ValueDecl *&ToValueDecl, bool &ToAddressOf,
856
39
        bool &ToNullPtr, Expr *&ToExpr) {
857
39
      assert(FlatTree[ReadNode].Kind == FromIntegerAndToDeclaration &&
858
39
             "Unexpected kind.");
859
0
      FromInt = FlatTree[ReadNode].FromArgInfo.Val;
860
39
      IsValidFromInt = FlatTree[ReadNode].FromArgInfo.IsValidInt;
861
39
      FromIntType = FlatTree[ReadNode].FromArgInfo.ArgType;
862
39
      FromExpr = FlatTree[ReadNode].FromArgInfo.ArgExpr;
863
39
      ToValueDecl = FlatTree[ReadNode].ToArgInfo.VD;
864
39
      ToAddressOf = FlatTree[ReadNode].ToArgInfo.NeedAddressOf;
865
39
      ToNullPtr = FlatTree[ReadNode].ToArgInfo.IsNullPtr;
866
39
      ToExpr = FlatTree[ReadNode].ToArgInfo.ArgExpr;
867
39
    }
868
869
    /// FromDefault - Return true if the from argument is the default.
870
2.49k
    bool FromDefault() {
871
2.49k
      return FlatTree[ReadNode].FromArgInfo.IsDefault;
872
2.49k
    }
873
874
    /// ToDefault - Return true if the to argument is the default.
875
2.49k
    bool ToDefault() {
876
2.49k
      return FlatTree[ReadNode].ToArgInfo.IsDefault;
877
2.49k
    }
878
879
    /// NodeIsSame - Returns true the arguments are the same.
880
5.12k
    bool NodeIsSame() {
881
5.12k
      return FlatTree[ReadNode].Same;
882
5.12k
    }
883
884
    /// HasChildrend - Returns true if the node has children.
885
1.47k
    bool HasChildren() {
886
1.47k
      return FlatTree[ReadNode].ChildNode != 0;
887
1.47k
    }
888
889
    /// MoveToChild - Moves from the current node to its child.
890
1.46k
    void MoveToChild() {
891
1.46k
      ReadNode = FlatTree[ReadNode].ChildNode;
892
1.46k
    }
893
894
    /// AdvanceSibling - If there is a next sibling, advance to it and return
895
    /// true.  Otherwise, return false.
896
3.69k
    bool AdvanceSibling() {
897
3.69k
      if (FlatTree[ReadNode].NextNode == 0)
898
1.46k
        return false;
899
900
2.22k
      ReadNode = FlatTree[ReadNode].NextNode;
901
2.22k
      return true;
902
3.69k
    }
903
904
    /// HasNextSibling - Return true if the node has a next sibling.
905
2.70k
    bool HasNextSibling() {
906
2.70k
      return FlatTree[ReadNode].NextNode != 0;
907
2.70k
    }
908
909
    /// Empty - Returns true if the tree has no information.
910
34.5k
    bool Empty() {
911
34.5k
      return GetKind() == Invalid;
912
34.5k
    }
913
914
    /// GetKind - Returns the current node's type.
915
38.4k
    DiffKind GetKind() {
916
38.4k
      return FlatTree[ReadNode].Kind;
917
38.4k
    }
918
  };
919
920
  DiffTree Tree;
921
922
  /// TSTiterator - a pair of iterators that walks the
923
  /// TemplateSpecializationType and the desugared TemplateSpecializationType.
924
  /// The deseguared TemplateArgument should provide the canonical argument
925
  /// for comparisons.
926
  class TSTiterator {
927
    typedef const TemplateArgument& reference;
928
    typedef const TemplateArgument* pointer;
929
930
    /// InternalIterator - an iterator that is used to enter a
931
    /// TemplateSpecializationType and read TemplateArguments inside template
932
    /// parameter packs in order with the rest of the TemplateArguments.
933
    struct InternalIterator {
934
      /// TST - the template specialization whose arguments this iterator
935
      /// traverse over.
936
      const TemplateSpecializationType *TST;
937
938
      /// Index - the index of the template argument in TST.
939
      unsigned Index;
940
941
      /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
942
      /// points to a TemplateArgument within a parameter pack.
943
      TemplateArgument::pack_iterator CurrentTA;
944
945
      /// EndTA - the end iterator of a parameter pack
946
      TemplateArgument::pack_iterator EndTA;
947
948
      /// InternalIterator - Constructs an iterator and sets it to the first
949
      /// template argument.
950
      InternalIterator(const TemplateSpecializationType *TST)
951
5.89k
          : TST(TST), Index(0), CurrentTA(nullptr), EndTA(nullptr) {
952
5.89k
        if (!TST) 
return240
;
953
954
5.65k
        if (isEnd()) 
return174
;
955
956
        // Set to first template argument.  If not a parameter pack, done.
957
5.48k
        TemplateArgument TA = TST->getArg(0);
958
5.48k
        if (TA.getKind() != TemplateArgument::Pack) 
return5.16k
;
959
960
        // Start looking into the parameter pack.
961
318
        CurrentTA = TA.pack_begin();
962
318
        EndTA = TA.pack_end();
963
964
        // Found a valid template argument.
965
318
        if (CurrentTA != EndTA) 
return306
;
966
967
        // Parameter pack is empty, use the increment to get to a valid
968
        // template argument.
969
12
        ++(*this);
970
12
      }
971
972
      /// Return true if the iterator is non-singular.
973
11.7k
      bool isValid() const { return TST; }
974
975
      /// isEnd - Returns true if the iterator is one past the end.
976
55.0k
      bool isEnd() const {
977
55.0k
        assert(TST && "InternalIterator is invalid with a null TST.");
978
0
        return Index >= TST->getNumArgs();
979
55.0k
      }
980
981
      /// &operator++ - Increment the iterator to the next template argument.
982
14.4k
      InternalIterator &operator++() {
983
14.4k
        assert(TST && "InternalIterator is invalid with a null TST.");
984
14.4k
        if (isEnd()) {
985
2.19k
          return *this;
986
2.19k
        }
987
988
        // If in a parameter pack, advance in the parameter pack.
989
12.2k
        if (CurrentTA != EndTA) {
990
2.97k
          ++CurrentTA;
991
2.97k
          if (CurrentTA != EndTA)
992
2.50k
            return *this;
993
2.97k
        }
994
995
        // Loop until a template argument is found, or the end is reached.
996
9.84k
        
while (9.76k
true) {
997
          // Advance to the next template argument.  Break if reached the end.
998
9.84k
          if (++Index == TST->getNumArgs())
999
5.47k
            break;
1000
1001
          // If the TemplateArgument is not a parameter pack, done.
1002
4.37k
          TemplateArgument TA = TST->getArg(Index);
1003
4.37k
          if (TA.getKind() != TemplateArgument::Pack)
1004
4.12k
            break;
1005
1006
          // Handle parameter packs.
1007
248
          CurrentTA = TA.pack_begin();
1008
248
          EndTA = TA.pack_end();
1009
1010
          // If the parameter pack is empty, try to advance again.
1011
248
          if (CurrentTA != EndTA)
1012
164
            break;
1013
248
        }
1014
9.76k
        return *this;
1015
12.2k
      }
1016
1017
      /// operator* - Returns the appropriate TemplateArgument.
1018
10.2k
      reference operator*() const {
1019
10.2k
        assert(TST && "InternalIterator is invalid with a null TST.");
1020
0
        assert(!isEnd() && "Index exceeds number of arguments.");
1021
10.2k
        if (CurrentTA == EndTA)
1022
9.48k
          return TST->getArg(Index);
1023
810
        else
1024
810
          return *CurrentTA;
1025
10.2k
      }
1026
1027
      /// operator-> - Allow access to the underlying TemplateArgument.
1028
0
      pointer operator->() const {
1029
0
        assert(TST && "InternalIterator is invalid with a null TST.");
1030
0
        return &operator*();
1031
0
      }
1032
    };
1033
1034
    InternalIterator SugaredIterator;
1035
    InternalIterator DesugaredIterator;
1036
1037
  public:
1038
    TSTiterator(ASTContext &Context, const TemplateSpecializationType *TST)
1039
        : SugaredIterator(TST),
1040
          DesugaredIterator(
1041
              (TST->isSugared() && !TST->isTypeAlias())
1042
                  ? GetTemplateSpecializationType(Context, TST->desugar())
1043
2.94k
                  : nullptr) {}
1044
1045
    /// &operator++ - Increment the iterator to the next template argument.
1046
7.38k
    TSTiterator &operator++() {
1047
7.38k
      ++SugaredIterator;
1048
7.38k
      if (DesugaredIterator.isValid())
1049
7.05k
        ++DesugaredIterator;
1050
7.38k
      return *this;
1051
7.38k
    }
1052
1053
    /// operator* - Returns the appropriate TemplateArgument.
1054
8.67k
    reference operator*() const {
1055
8.67k
      return *SugaredIterator;
1056
8.67k
    }
1057
1058
    /// operator-> - Allow access to the underlying TemplateArgument.
1059
8.67k
    pointer operator->() const {
1060
8.67k
      return &operator*();
1061
8.67k
    }
1062
1063
    /// isEnd - Returns true if no more TemplateArguments are available.
1064
22.1k
    bool isEnd() const {
1065
22.1k
      return SugaredIterator.isEnd();
1066
22.1k
    }
1067
1068
    /// hasDesugaredTA - Returns true if there is another TemplateArgument
1069
    /// available.
1070
2.75k
    bool hasDesugaredTA() const {
1071
2.75k
      return DesugaredIterator.isValid() && 
!DesugaredIterator.isEnd()2.53k
;
1072
2.75k
    }
1073
1074
    /// getDesugaredTA - Returns the desugared TemplateArgument.
1075
1.62k
    reference getDesugaredTA() const {
1076
1.62k
      assert(DesugaredIterator.isValid() &&
1077
1.62k
             "Desugared TemplateArgument should not be used.");
1078
0
      return *DesugaredIterator;
1079
1.62k
    }
1080
  };
1081
1082
  // These functions build up the template diff tree, including functions to
1083
  // retrieve and compare template arguments.
1084
1085
  static const TemplateSpecializationType *GetTemplateSpecializationType(
1086
73.1k
      ASTContext &Context, QualType Ty) {
1087
73.1k
    if (const TemplateSpecializationType *TST =
1088
73.1k
            Ty->getAs<TemplateSpecializationType>())
1089
4.21k
      return TST;
1090
1091
68.9k
    const RecordType *RT = Ty->getAs<RecordType>();
1092
1093
68.9k
    if (!RT)
1094
52.9k
      return nullptr;
1095
1096
15.9k
    const ClassTemplateSpecializationDecl *CTSD =
1097
15.9k
        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
1098
1099
15.9k
    if (!CTSD)
1100
12.4k
      return nullptr;
1101
1102
3.42k
    Ty = Context.getTemplateSpecializationType(
1103
3.42k
             TemplateName(CTSD->getSpecializedTemplate()),
1104
3.42k
             CTSD->getTemplateArgs().asArray(),
1105
3.42k
             Ty.getLocalUnqualifiedType().getCanonicalType());
1106
1107
3.42k
    return Ty->getAs<TemplateSpecializationType>();
1108
15.9k
  }
1109
1110
  /// Returns true if the DiffType is Type and false for Template.
1111
  static bool OnlyPerformTypeDiff(ASTContext &Context, QualType FromType,
1112
                                  QualType ToType,
1113
                                  const TemplateSpecializationType *&FromArgTST,
1114
2.33k
                                  const TemplateSpecializationType *&ToArgTST) {
1115
2.33k
    if (FromType.isNull() || 
ToType.isNull()1.96k
)
1116
724
      return true;
1117
1118
1.61k
    if (Context.hasSameType(FromType, ToType))
1119
928
      return true;
1120
1121
682
    FromArgTST = GetTemplateSpecializationType(Context, FromType);
1122
682
    ToArgTST = GetTemplateSpecializationType(Context, ToType);
1123
1124
682
    if (!FromArgTST || 
!ToArgTST225
)
1125
467
      return true;
1126
1127
215
    if (!hasSameTemplate(FromArgTST, ToArgTST))
1128
6
      return true;
1129
1130
209
    return false;
1131
215
  }
1132
1133
  /// DiffTypes - Fills a DiffNode with information about a type difference.
1134
2.33k
  void DiffTypes(const TSTiterator &FromIter, const TSTiterator &ToIter) {
1135
2.33k
    QualType FromType = GetType(FromIter);
1136
2.33k
    QualType ToType = GetType(ToIter);
1137
1138
2.33k
    bool FromDefault = FromIter.isEnd() && 
!FromType.isNull()429
;
1139
2.33k
    bool ToDefault = ToIter.isEnd() && 
!ToType.isNull()399
;
1140
1141
2.33k
    const TemplateSpecializationType *FromArgTST = nullptr;
1142
2.33k
    const TemplateSpecializationType *ToArgTST = nullptr;
1143
2.33k
    if (OnlyPerformTypeDiff(Context, FromType, ToType, FromArgTST, ToArgTST)) {
1144
2.12k
      Tree.SetTypeDiff(FromType, ToType, FromDefault, ToDefault);
1145
2.12k
      Tree.SetSame(!FromType.isNull() && 
!ToType.isNull()1.75k
&&
1146
2.12k
                   
Context.hasSameType(FromType, ToType)1.40k
);
1147
2.12k
    } else {
1148
209
      assert(FromArgTST && ToArgTST &&
1149
209
             "Both template specializations need to be valid.");
1150
0
      Qualifiers FromQual = FromType.getQualifiers(),
1151
209
                 ToQual = ToType.getQualifiers();
1152
209
      FromQual -= QualType(FromArgTST, 0).getQualifiers();
1153
209
      ToQual -= QualType(ToArgTST, 0).getQualifiers();
1154
209
      Tree.SetTemplateDiff(FromArgTST->getTemplateName().getAsTemplateDecl(),
1155
209
                           ToArgTST->getTemplateName().getAsTemplateDecl(),
1156
209
                           FromQual, ToQual, FromDefault, ToDefault);
1157
209
      DiffTemplate(FromArgTST, ToArgTST);
1158
209
    }
1159
2.33k
  }
1160
1161
  /// DiffTemplateTemplates - Fills a DiffNode with information about a
1162
  /// template template difference.
1163
  void DiffTemplateTemplates(const TSTiterator &FromIter,
1164
110
                             const TSTiterator &ToIter) {
1165
110
    TemplateDecl *FromDecl = GetTemplateDecl(FromIter);
1166
110
    TemplateDecl *ToDecl = GetTemplateDecl(ToIter);
1167
110
    Tree.SetTemplateTemplateDiff(FromDecl, ToDecl, FromIter.isEnd() && 
FromDecl18
,
1168
110
                                 ToIter.isEnd() && 
ToDecl18
);
1169
110
    Tree.SetSame(FromDecl && 
ToDecl104
&&
1170
110
                 
FromDecl->getCanonicalDecl() == ToDecl->getCanonicalDecl()98
);
1171
110
  }
1172
1173
  /// InitializeNonTypeDiffVariables - Helper function for DiffNonTypes
1174
  static void InitializeNonTypeDiffVariables(ASTContext &Context,
1175
                                             const TSTiterator &Iter,
1176
                                             NonTypeTemplateParmDecl *Default,
1177
                                             llvm::APSInt &Value, bool &HasInt,
1178
                                             QualType &IntType, bool &IsNullPtr,
1179
                                             Expr *&E, ValueDecl *&VD,
1180
2.49k
                                             bool &NeedAddressOf) {
1181
2.49k
    if (!Iter.isEnd()) {
1182
2.07k
      switch (Iter->getKind()) {
1183
0
        default:
1184
0
          llvm_unreachable("unknown ArgumentKind");
1185
218
        case TemplateArgument::Integral:
1186
218
          Value = Iter->getAsIntegral();
1187
218
          HasInt = true;
1188
218
          IntType = Iter->getIntegralType();
1189
218
          return;
1190
338
        case TemplateArgument::Declaration: {
1191
338
          VD = Iter->getAsDecl();
1192
338
          QualType ArgType = Iter->getParamTypeForDecl();
1193
338
          QualType VDType = VD->getType();
1194
338
          if (ArgType->isPointerType() &&
1195
338
              
Context.hasSameType(ArgType->getPointeeType(), VDType)194
)
1196
190
            NeedAddressOf = true;
1197
338
          return;
1198
0
        }
1199
54
        case TemplateArgument::NullPtr:
1200
54
          IsNullPtr = true;
1201
54
          return;
1202
1.46k
        case TemplateArgument::Expression:
1203
1.46k
          E = Iter->getAsExpr();
1204
2.07k
      }
1205
2.07k
    } else 
if (423
!Default->isParameterPack()423
) {
1206
255
      E = Default->getDefaultArgument();
1207
255
    }
1208
1209
1.88k
    if (!Iter.hasDesugaredTA()) 
return388
;
1210
1211
1.49k
    const TemplateArgument& TA = Iter.getDesugaredTA();
1212
1.49k
    switch (TA.getKind()) {
1213
0
      default:
1214
0
        llvm_unreachable("unknown ArgumentKind");
1215
866
      case TemplateArgument::Integral:
1216
866
        Value = TA.getAsIntegral();
1217
866
        HasInt = true;
1218
866
        IntType = TA.getIntegralType();
1219
866
        return;
1220
527
      case TemplateArgument::Declaration: {
1221
527
        VD = TA.getAsDecl();
1222
527
        QualType ArgType = TA.getParamTypeForDecl();
1223
527
        QualType VDType = VD->getType();
1224
527
        if (ArgType->isPointerType() &&
1225
527
            
Context.hasSameType(ArgType->getPointeeType(), VDType)330
)
1226
300
          NeedAddressOf = true;
1227
527
        return;
1228
0
      }
1229
105
      case TemplateArgument::NullPtr:
1230
105
        IsNullPtr = true;
1231
105
        return;
1232
0
      case TemplateArgument::Expression:
1233
        // TODO: Sometimes, the desugared template argument Expr differs from
1234
        // the sugared template argument Expr.  It may be useful in the future
1235
        // but for now, it is just discarded.
1236
0
        if (!E)
1237
0
          E = TA.getAsExpr();
1238
0
        return;
1239
1.49k
    }
1240
1.49k
  }
1241
1242
  /// DiffNonTypes - Handles any template parameters not handled by DiffTypes
1243
  /// of DiffTemplatesTemplates, such as integer and declaration parameters.
1244
  void DiffNonTypes(const TSTiterator &FromIter, const TSTiterator &ToIter,
1245
                    NonTypeTemplateParmDecl *FromDefaultNonTypeDecl,
1246
1.24k
                    NonTypeTemplateParmDecl *ToDefaultNonTypeDecl) {
1247
1.24k
    Expr *FromExpr = nullptr, *ToExpr = nullptr;
1248
1.24k
    llvm::APSInt FromInt, ToInt;
1249
1.24k
    QualType FromIntType, ToIntType;
1250
1.24k
    ValueDecl *FromValueDecl = nullptr, *ToValueDecl = nullptr;
1251
1.24k
    bool HasFromInt = false, HasToInt = false, FromNullPtr = false,
1252
1.24k
         ToNullPtr = false, NeedFromAddressOf = false, NeedToAddressOf = false;
1253
1.24k
    InitializeNonTypeDiffVariables(
1254
1.24k
        Context, FromIter, FromDefaultNonTypeDecl, FromInt, HasFromInt,
1255
1.24k
        FromIntType, FromNullPtr, FromExpr, FromValueDecl, NeedFromAddressOf);
1256
1.24k
    InitializeNonTypeDiffVariables(Context, ToIter, ToDefaultNonTypeDecl, ToInt,
1257
1.24k
                                   HasToInt, ToIntType, ToNullPtr, ToExpr,
1258
1.24k
                                   ToValueDecl, NeedToAddressOf);
1259
1260
1.24k
    bool FromDefault = FromIter.isEnd() &&
1261
1.24k
                       
(257
FromExpr257
||
FromValueDecl98
||
HasFromInt98
||
FromNullPtr98
);
1262
1.24k
    bool ToDefault = ToIter.isEnd() &&
1263
1.24k
                     
(166
ToExpr166
||
ToValueDecl70
||
HasToInt70
||
ToNullPtr70
);
1264
1265
1.24k
    bool FromDeclaration = FromValueDecl || 
FromNullPtr820
;
1266
1.24k
    bool ToDeclaration = ToValueDecl || 
ToNullPtr811
;
1267
1268
1.24k
    if (FromDeclaration && 
HasToInt503
) {
1269
39
      Tree.SetFromDeclarationAndToIntegerDiff(
1270
39
          FromValueDecl, NeedFromAddressOf, FromNullPtr, FromExpr, ToInt,
1271
39
          HasToInt, ToIntType, ToExpr, FromDefault, ToDefault);
1272
39
      Tree.SetSame(false);
1273
39
      return;
1274
1275
39
    }
1276
1277
1.20k
    if (HasFromInt && 
ToDeclaration539
) {
1278
39
      Tree.SetFromIntegerAndToDeclarationDiff(
1279
39
          FromInt, HasFromInt, FromIntType, FromExpr, ToValueDecl,
1280
39
          NeedToAddressOf, ToNullPtr, ToExpr, FromDefault, ToDefault);
1281
39
      Tree.SetSame(false);
1282
39
      return;
1283
39
    }
1284
1285
1.17k
    if (HasFromInt || 
HasToInt670
) {
1286
548
      Tree.SetIntegerDiff(FromInt, ToInt, HasFromInt, HasToInt, FromIntType,
1287
548
                          ToIntType, FromExpr, ToExpr, FromDefault, ToDefault);
1288
548
      if (HasFromInt && 
HasToInt500
) {
1289
458
        Tree.SetSame(Context.hasSameType(FromIntType, ToIntType) &&
1290
458
                     
FromInt == ToInt440
);
1291
458
      }
1292
548
      return;
1293
548
    }
1294
1295
622
    if (FromDeclaration || 
ToDeclaration158
) {
1296
518
      Tree.SetDeclarationDiff(FromValueDecl, ToValueDecl, NeedFromAddressOf,
1297
518
                              NeedToAddressOf, FromNullPtr, ToNullPtr, FromExpr,
1298
518
                              ToExpr, FromDefault, ToDefault);
1299
518
      bool BothNull = FromNullPtr && 
ToNullPtr68
;
1300
518
      bool SameValueDecl =
1301
518
          FromValueDecl && 
ToValueDecl396
&&
1302
518
          
NeedFromAddressOf == NeedToAddressOf332
&&
1303
518
          
FromValueDecl->getCanonicalDecl() == ToValueDecl->getCanonicalDecl()314
;
1304
518
      Tree.SetSame(BothNull || 
SameValueDecl470
);
1305
518
      return;
1306
518
    }
1307
1308
104
    assert((FromExpr || ToExpr) && "Both template arguments cannot be empty.");
1309
0
    Tree.SetExpressionDiff(FromExpr, ToExpr, FromDefault, ToDefault);
1310
104
    Tree.SetSame(IsEqualExpr(Context, FromExpr, ToExpr));
1311
104
  }
1312
1313
  /// DiffTemplate - recursively visits template arguments and stores the
1314
  /// argument info into a tree.
1315
  void DiffTemplate(const TemplateSpecializationType *FromTST,
1316
1.47k
                    const TemplateSpecializationType *ToTST) {
1317
    // Begin descent into diffing template tree.
1318
1.47k
    TemplateParameterList *ParamsFrom =
1319
1.47k
        FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
1320
1.47k
    TemplateParameterList *ParamsTo =
1321
1.47k
        ToTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
1322
1.47k
    unsigned TotalArgs = 0;
1323
1.47k
    for (TSTiterator FromIter(Context, FromTST), ToIter(Context, ToTST);
1324
5.16k
         !FromIter.isEnd() || 
!ToIter.isEnd()2.17k
;
++TotalArgs3.69k
) {
1325
3.69k
      Tree.AddNode();
1326
1327
      // Get the parameter at index TotalArgs.  If index is larger
1328
      // than the total number of parameters, then there is an
1329
      // argument pack, so re-use the last parameter.
1330
3.69k
      unsigned FromParamIndex = std::min(TotalArgs, ParamsFrom->size() - 1);
1331
3.69k
      unsigned ToParamIndex = std::min(TotalArgs, ParamsTo->size() - 1);
1332
3.69k
      NamedDecl *FromParamND = ParamsFrom->getParam(FromParamIndex);
1333
3.69k
      NamedDecl *ToParamND = ParamsTo->getParam(ToParamIndex);
1334
1335
3.69k
      assert(FromParamND->getKind() == ToParamND->getKind() &&
1336
3.69k
             "Parameter Decl are not the same kind.");
1337
1338
3.69k
      if (isa<TemplateTypeParmDecl>(FromParamND)) {
1339
2.33k
        DiffTypes(FromIter, ToIter);
1340
2.33k
      } else 
if (1.35k
isa<TemplateTemplateParmDecl>(FromParamND)1.35k
) {
1341
110
        DiffTemplateTemplates(FromIter, ToIter);
1342
1.24k
      } else if (isa<NonTypeTemplateParmDecl>(FromParamND)) {
1343
1.24k
        NonTypeTemplateParmDecl *FromDefaultNonTypeDecl =
1344
1.24k
            cast<NonTypeTemplateParmDecl>(FromParamND);
1345
1.24k
        NonTypeTemplateParmDecl *ToDefaultNonTypeDecl =
1346
1.24k
            cast<NonTypeTemplateParmDecl>(ToParamND);
1347
1.24k
        DiffNonTypes(FromIter, ToIter, FromDefaultNonTypeDecl,
1348
1.24k
                     ToDefaultNonTypeDecl);
1349
1.24k
      } else {
1350
0
        llvm_unreachable("Unexpected Decl type.");
1351
0
      }
1352
1353
3.69k
      ++FromIter;
1354
3.69k
      ++ToIter;
1355
3.69k
      Tree.Up();
1356
3.69k
    }
1357
1.47k
  }
1358
1359
  /// makeTemplateList - Dump every template alias into the vector.
1360
  static void makeTemplateList(
1361
      SmallVectorImpl<const TemplateSpecializationType *> &TemplateList,
1362
176
      const TemplateSpecializationType *TST) {
1363
248
    while (TST) {
1364
236
      TemplateList.push_back(TST);
1365
236
      if (!TST->isTypeAlias())
1366
164
        return;
1367
72
      TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1368
72
    }
1369
176
  }
1370
1371
  /// hasSameBaseTemplate - Returns true when the base templates are the same,
1372
  /// even if the template arguments are not.
1373
  static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
1374
1.65k
                                  const TemplateSpecializationType *ToTST) {
1375
1.65k
    return FromTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl() ==
1376
1.65k
           ToTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl();
1377
1.65k
  }
1378
1379
  /// hasSameTemplate - Returns true if both types are specialized from the
1380
  /// same template declaration.  If they come from different template aliases,
1381
  /// do a parallel ascension search to determine the highest template alias in
1382
  /// common and set the arguments to them.
1383
  static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
1384
1.52k
                              const TemplateSpecializationType *&ToTST) {
1385
    // Check the top templates if they are the same.
1386
1.52k
    if (hasSameBaseTemplate(FromTST, ToTST))
1387
1.43k
      return true;
1388
1389
    // Create vectors of template aliases.
1390
88
    SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
1391
88
                                                      ToTemplateList;
1392
1393
88
    makeTemplateList(FromTemplateList, FromTST);
1394
88
    makeTemplateList(ToTemplateList, ToTST);
1395
1396
88
    SmallVectorImpl<const TemplateSpecializationType *>::reverse_iterator
1397
88
        FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
1398
88
        ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
1399
1400
    // Check if the lowest template types are the same.  If not, return.
1401
88
    if (!hasSameBaseTemplate(*FromIter, *ToIter))
1402
52
      return false;
1403
1404
    // Begin searching up the template aliases.  The bottom most template
1405
    // matches so move up until one pair does not match.  Use the template
1406
    // right before that one.
1407
78
    
for (; 36
FromIter != FromEnd &&
ToIter != ToEnd60
;
++FromIter, ++ToIter42
) {
1408
42
      if (!hasSameBaseTemplate(*FromIter, *ToIter))
1409
0
        break;
1410
42
    }
1411
1412
36
    FromTST = FromIter[-1];
1413
36
    ToTST = ToIter[-1];
1414
1415
36
    return true;
1416
88
  }
1417
1418
  /// GetType - Retrieves the template type arguments, including default
1419
  /// arguments.
1420
4.66k
  static QualType GetType(const TSTiterator &Iter) {
1421
4.66k
    if (!Iter.isEnd())
1422
3.84k
      return Iter->getAsType();
1423
828
    if (Iter.hasDesugaredTA())
1424
104
      return Iter.getDesugaredTA().getAsType();
1425
724
    return QualType();
1426
828
  }
1427
1428
  /// GetTemplateDecl - Retrieves the template template arguments, including
1429
  /// default arguments.
1430
220
  static TemplateDecl *GetTemplateDecl(const TSTiterator &Iter) {
1431
220
    if (!Iter.isEnd())
1432
184
      return Iter->getAsTemplate().getAsTemplateDecl();
1433
36
    if (Iter.hasDesugaredTA())
1434
24
      return Iter.getDesugaredTA().getAsTemplate().getAsTemplateDecl();
1435
12
    return nullptr;
1436
36
  }
1437
1438
  /// IsEqualExpr - Returns true if the expressions are the same in regards to
1439
  /// template arguments.  These expressions are dependent, so profile them
1440
  /// instead of trying to evaluate them.
1441
104
  static bool IsEqualExpr(ASTContext &Context, Expr *FromExpr, Expr *ToExpr) {
1442
104
    if (FromExpr == ToExpr)
1443
0
      return true;
1444
1445
104
    if (!FromExpr || !ToExpr)
1446
0
      return false;
1447
1448
104
    llvm::FoldingSetNodeID FromID, ToID;
1449
104
    FromExpr->Profile(FromID, Context, true);
1450
104
    ToExpr->Profile(ToID, Context, true);
1451
104
    return FromID == ToID;
1452
104
  }
1453
1454
  // These functions converts the tree representation of the template
1455
  // differences into the internal character vector.
1456
1457
  /// TreeToString - Converts the Tree object into a character stream which
1458
  /// will later be turned into the output string.
1459
3.97k
  void TreeToString(int Indent = 1) {
1460
3.97k
    if (PrintTree) {
1461
938
      OS << '\n';
1462
938
      OS.indent(2 * Indent);
1463
938
      ++Indent;
1464
938
    }
1465
1466
    // Handle cases where the difference is not templates with different
1467
    // arguments.
1468
3.97k
    switch (Tree.GetKind()) {
1469
0
      case DiffTree::Invalid:
1470
0
        llvm_unreachable("Template diffing failed with bad DiffNode");
1471
1.30k
      case DiffTree::Type: {
1472
1.30k
        QualType FromType, ToType;
1473
1.30k
        Tree.GetTypeDiff(FromType, ToType);
1474
1.30k
        PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1475
1.30k
                       Tree.NodeIsSame());
1476
1.30k
        return;
1477
0
      }
1478
98
      case DiffTree::Expression: {
1479
98
        Expr *FromExpr, *ToExpr;
1480
98
        Tree.GetExpressionDiff(FromExpr, ToExpr);
1481
98
        PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1482
98
                  Tree.NodeIsSame());
1483
98
        return;
1484
0
      }
1485
92
      case DiffTree::TemplateTemplate: {
1486
92
        TemplateDecl *FromTD, *ToTD;
1487
92
        Tree.GetTemplateTemplateDiff(FromTD, ToTD);
1488
92
        PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1489
92
                              Tree.ToDefault(), Tree.NodeIsSame());
1490
92
        return;
1491
0
      }
1492
467
      case DiffTree::Integer: {
1493
467
        llvm::APSInt FromInt, ToInt;
1494
467
        Expr *FromExpr, *ToExpr;
1495
467
        bool IsValidFromInt, IsValidToInt;
1496
467
        QualType FromIntType, ToIntType;
1497
467
        Tree.GetIntegerDiff(FromInt, ToInt, IsValidFromInt, IsValidToInt,
1498
467
                            FromIntType, ToIntType, FromExpr, ToExpr);
1499
467
        PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt, FromIntType,
1500
467
                    ToIntType, FromExpr, ToExpr, Tree.FromDefault(),
1501
467
                    Tree.ToDefault(), Tree.NodeIsSame());
1502
467
        return;
1503
0
      }
1504
458
      case DiffTree::Declaration: {
1505
458
        ValueDecl *FromValueDecl, *ToValueDecl;
1506
458
        bool FromAddressOf, ToAddressOf;
1507
458
        bool FromNullPtr, ToNullPtr;
1508
458
        Expr *FromExpr, *ToExpr;
1509
458
        Tree.GetDeclarationDiff(FromValueDecl, ToValueDecl, FromAddressOf,
1510
458
                                ToAddressOf, FromNullPtr, ToNullPtr, FromExpr,
1511
458
                                ToExpr);
1512
458
        PrintValueDecl(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf,
1513
458
                       FromNullPtr, ToNullPtr, FromExpr, ToExpr,
1514
458
                       Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame());
1515
458
        return;
1516
0
      }
1517
39
      case DiffTree::FromDeclarationAndToInteger: {
1518
39
        ValueDecl *FromValueDecl;
1519
39
        bool FromAddressOf;
1520
39
        bool FromNullPtr;
1521
39
        Expr *FromExpr;
1522
39
        llvm::APSInt ToInt;
1523
39
        bool IsValidToInt;
1524
39
        QualType ToIntType;
1525
39
        Expr *ToExpr;
1526
39
        Tree.GetFromDeclarationAndToIntegerDiff(
1527
39
            FromValueDecl, FromAddressOf, FromNullPtr, FromExpr, ToInt,
1528
39
            IsValidToInt, ToIntType, ToExpr);
1529
39
        assert((FromValueDecl || FromNullPtr) && IsValidToInt);
1530
0
        PrintValueDeclAndInteger(FromValueDecl, FromAddressOf, FromNullPtr,
1531
39
                                 FromExpr, Tree.FromDefault(), ToInt, ToIntType,
1532
39
                                 ToExpr, Tree.ToDefault());
1533
39
        return;
1534
0
      }
1535
39
      case DiffTree::FromIntegerAndToDeclaration: {
1536
39
        llvm::APSInt FromInt;
1537
39
        bool IsValidFromInt;
1538
39
        QualType FromIntType;
1539
39
        Expr *FromExpr;
1540
39
        ValueDecl *ToValueDecl;
1541
39
        bool ToAddressOf;
1542
39
        bool ToNullPtr;
1543
39
        Expr *ToExpr;
1544
39
        Tree.GetFromIntegerAndToDeclarationDiff(
1545
39
            FromInt, IsValidFromInt, FromIntType, FromExpr, ToValueDecl,
1546
39
            ToAddressOf, ToNullPtr, ToExpr);
1547
39
        assert(IsValidFromInt && (ToValueDecl || ToNullPtr));
1548
0
        PrintIntegerAndValueDecl(FromInt, FromIntType, FromExpr,
1549
39
                                 Tree.FromDefault(), ToValueDecl, ToAddressOf,
1550
39
                                 ToNullPtr, ToExpr, Tree.ToDefault());
1551
39
        return;
1552
0
      }
1553
1.47k
      case DiffTree::Template: {
1554
        // Node is root of template.  Recurse on children.
1555
1.47k
        TemplateDecl *FromTD, *ToTD;
1556
1.47k
        Qualifiers FromQual, ToQual;
1557
1.47k
        Tree.GetTemplateDiff(FromTD, ToTD, FromQual, ToQual);
1558
1559
1.47k
        PrintQualifiers(FromQual, ToQual);
1560
1561
1.47k
        if (!Tree.HasChildren()) {
1562
          // If we're dealing with a template specialization with zero
1563
          // arguments, there are no children; special-case this.
1564
6
          OS << FromTD->getDeclName() << "<>";
1565
6
          return;
1566
6
        }
1567
1568
1.46k
        OS << FromTD->getDeclName() << '<';
1569
1.46k
        Tree.MoveToChild();
1570
1.46k
        unsigned NumElideArgs = 0;
1571
1.46k
        bool AllArgsElided = true;
1572
3.69k
        do {
1573
3.69k
          if (ElideType) {
1574
2.70k
            if (Tree.NodeIsSame()) {
1575
985
              ++NumElideArgs;
1576
985
              continue;
1577
985
            }
1578
1.71k
            AllArgsElided = false;
1579
1.71k
            if (NumElideArgs > 0) {
1580
147
              PrintElideArgs(NumElideArgs, Indent);
1581
147
              NumElideArgs = 0;
1582
147
              OS << ", ";
1583
147
            }
1584
1.71k
          }
1585
2.70k
          TreeToString(Indent);
1586
2.70k
          if (Tree.HasNextSibling())
1587
1.35k
            OS << ", ";
1588
3.69k
        } while (Tree.AdvanceSibling());
1589
1.46k
        if (NumElideArgs > 0) {
1590
114
          if (AllArgsElided)
1591
47
            OS << "...";
1592
67
          else
1593
67
            PrintElideArgs(NumElideArgs, Indent);
1594
114
        }
1595
1596
1.46k
        Tree.Parent();
1597
1.46k
        OS << ">";
1598
1.46k
        return;
1599
1.47k
      }
1600
3.97k
    }
1601
3.97k
  }
1602
1603
  // To signal to the text printer that a certain text needs to be bolded,
1604
  // a special character is injected into the character stream which the
1605
  // text printer will later strip out.
1606
1607
  /// Bold - Start bolding text.
1608
3.08k
  void Bold() {
1609
3.08k
    assert(!IsBold && "Attempting to bold text that is already bold.");
1610
0
    IsBold = true;
1611
3.08k
    if (ShowColor)
1612
55
      OS << ToggleHighlight;
1613
3.08k
  }
1614
1615
  /// Unbold - Stop bolding text.
1616
3.08k
  void Unbold() {
1617
3.08k
    assert(IsBold && "Attempting to remove bold from unbold text.");
1618
0
    IsBold = false;
1619
3.08k
    if (ShowColor)
1620
55
      OS << ToggleHighlight;
1621
3.08k
  }
1622
1623
  // Functions to print out the arguments and highlighting the difference.
1624
1625
  /// PrintTypeNames - prints the typenames, bolding differences.  Will detect
1626
  /// typenames that are the same and attempt to disambiguate them by using
1627
  /// canonical typenames.
1628
  void PrintTypeNames(QualType FromType, QualType ToType,
1629
1.30k
                      bool FromDefault, bool ToDefault, bool Same) {
1630
1.30k
    assert((!FromType.isNull() || !ToType.isNull()) &&
1631
1.30k
           "Only one template argument may be missing.");
1632
1633
1.30k
    if (Same) {
1634
108
      OS << FromType.getAsString(Policy);
1635
108
      return;
1636
108
    }
1637
1638
1.19k
    if (!FromType.isNull() && 
!ToType.isNull()831
&&
1639
1.19k
        FromType.getLocalUnqualifiedType() ==
1640
473
        ToType.getLocalUnqualifiedType()) {
1641
9
      Qualifiers FromQual = FromType.getLocalQualifiers(),
1642
9
                 ToQual = ToType.getLocalQualifiers();
1643
9
      PrintQualifiers(FromQual, ToQual);
1644
9
      FromType.getLocalUnqualifiedType().print(OS, Policy);
1645
9
      return;
1646
9
    }
1647
1648
1.18k
    std::string FromTypeStr = FromType.isNull() ? 
"(no argument)"366
1649
1.18k
                                                : 
FromType.getAsString(Policy)822
;
1650
1.18k
    std::string ToTypeStr = ToType.isNull() ? 
"(no argument)"358
1651
1.18k
                                            : 
ToType.getAsString(Policy)830
;
1652
    // Switch to canonical typename if it is better.
1653
    // TODO: merge this with other aka printing above.
1654
1.18k
    if (FromTypeStr == ToTypeStr) {
1655
0
      std::string FromCanTypeStr =
1656
0
          FromType.getCanonicalType().getAsString(Policy);
1657
0
      std::string ToCanTypeStr = ToType.getCanonicalType().getAsString(Policy);
1658
0
      if (FromCanTypeStr != ToCanTypeStr) {
1659
0
        FromTypeStr = FromCanTypeStr;
1660
0
        ToTypeStr = ToCanTypeStr;
1661
0
      }
1662
0
    }
1663
1664
1.18k
    if (PrintTree) 
OS << '['130
;
1665
1.18k
    OS << (FromDefault ? 
"(default) "25
:
""1.16k
);
1666
1.18k
    Bold();
1667
1.18k
    OS << FromTypeStr;
1668
1.18k
    Unbold();
1669
1.18k
    if (PrintTree) {
1670
130
      OS << " != " << (ToDefault ? 
"(default) "4
:
""126
);
1671
130
      Bold();
1672
130
      OS << ToTypeStr;
1673
130
      Unbold();
1674
130
      OS << "]";
1675
130
    }
1676
1.18k
  }
1677
1678
  /// PrintExpr - Prints out the expr template arguments, highlighting argument
1679
  /// differences.
1680
  void PrintExpr(const Expr *FromExpr, const Expr *ToExpr, bool FromDefault,
1681
98
                 bool ToDefault, bool Same) {
1682
98
    assert((FromExpr || ToExpr) &&
1683
98
            "Only one template argument may be missing.");
1684
98
    if (Same) {
1685
6
      PrintExpr(FromExpr);
1686
92
    } else if (!PrintTree) {
1687
68
      OS << (FromDefault ? 
"(default) "6
:
""62
);
1688
68
      Bold();
1689
68
      PrintExpr(FromExpr);
1690
68
      Unbold();
1691
68
    } else {
1692
24
      OS << (FromDefault ? 
"[(default) "6
:
"["18
);
1693
24
      Bold();
1694
24
      PrintExpr(FromExpr);
1695
24
      Unbold();
1696
24
      OS << " != " << (ToDefault ? 
"(default) "0
: "");
1697
24
      Bold();
1698
24
      PrintExpr(ToExpr);
1699
24
      Unbold();
1700
24
      OS << ']';
1701
24
    }
1702
98
  }
1703
1704
  /// PrintExpr - Actual formatting and printing of expressions.
1705
205
  void PrintExpr(const Expr *E) {
1706
205
    if (E) {
1707
205
      E->printPretty(OS, nullptr, Policy);
1708
205
      return;
1709
205
    }
1710
0
    OS << "(no argument)";
1711
0
  }
1712
1713
  /// PrintTemplateTemplate - Handles printing of template template arguments,
1714
  /// highlighting argument differences.
1715
  void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1716
92
                             bool FromDefault, bool ToDefault, bool Same) {
1717
92
    assert((FromTD || ToTD) && "Only one template argument may be missing.");
1718
1719
0
    std::string FromName =
1720
92
        std::string(FromTD ? 
FromTD->getName()86
:
"(no argument)"6
);
1721
92
    std::string ToName = std::string(ToTD ? 
ToTD->getName()86
:
"(no argument)"6
);
1722
92
    if (FromTD && 
ToTD86
&&
FromName == ToName80
) {
1723
30
      FromName = FromTD->getQualifiedNameAsString();
1724
30
      ToName = ToTD->getQualifiedNameAsString();
1725
30
    }
1726
1727
92
    if (Same) {
1728
18
      OS << "template " << FromTD->getDeclName();
1729
74
    } else if (!PrintTree) {
1730
50
      OS << (FromDefault ? 
"(default) template "4
:
"template "46
);
1731
50
      Bold();
1732
50
      OS << FromName;
1733
50
      Unbold();
1734
50
    } else {
1735
24
      OS << (FromDefault ? 
"[(default) template "2
:
"[template "22
);
1736
24
      Bold();
1737
24
      OS << FromName;
1738
24
      Unbold();
1739
24
      OS << " != " << (ToDefault ? 
"(default) template "2
:
"template "22
);
1740
24
      Bold();
1741
24
      OS << ToName;
1742
24
      Unbold();
1743
24
      OS << ']';
1744
24
    }
1745
92
  }
1746
1747
  /// PrintAPSInt - Handles printing of integral arguments, highlighting
1748
  /// argument differences.
1749
  void PrintAPSInt(const llvm::APSInt &FromInt, const llvm::APSInt &ToInt,
1750
                   bool IsValidFromInt, bool IsValidToInt, QualType FromIntType,
1751
                   QualType ToIntType, Expr *FromExpr, Expr *ToExpr,
1752
467
                   bool FromDefault, bool ToDefault, bool Same) {
1753
467
    assert((IsValidFromInt || IsValidToInt) &&
1754
467
           "Only one integral argument may be missing.");
1755
1756
467
    if (Same) {
1757
60
      if (FromIntType->isBooleanType()) {
1758
0
        OS << ((FromInt == 0) ? "false" : "true");
1759
60
      } else {
1760
60
        OS << toString(FromInt, 10);
1761
60
      }
1762
60
      return;
1763
60
    }
1764
1765
407
    bool PrintType = IsValidFromInt && 
IsValidToInt359
&&
1766
407
                     
!Context.hasSameType(FromIntType, ToIntType)317
;
1767
1768
407
    if (!PrintTree) {
1769
306
      OS << (FromDefault ? 
"(default) "29
:
""277
);
1770
306
      PrintAPSInt(FromInt, FromExpr, IsValidFromInt, FromIntType, PrintType);
1771
306
    } else {
1772
101
      OS << (FromDefault ? 
"[(default) "23
:
"["78
);
1773
101
      PrintAPSInt(FromInt, FromExpr, IsValidFromInt, FromIntType, PrintType);
1774
101
      OS << " != " << (ToDefault ? 
"(default) "2
:
""99
);
1775
101
      PrintAPSInt(ToInt, ToExpr, IsValidToInt, ToIntType, PrintType);
1776
101
      OS << ']';
1777
101
    }
1778
407
  }
1779
1780
  /// PrintAPSInt - If valid, print the APSInt.  If the expression is
1781
  /// gives more information, print it too.
1782
  void PrintAPSInt(const llvm::APSInt &Val, Expr *E, bool Valid,
1783
560
                   QualType IntType, bool PrintType) {
1784
560
    Bold();
1785
560
    if (Valid) {
1786
500
      if (HasExtraInfo(E)) {
1787
54
        PrintExpr(E);
1788
54
        Unbold();
1789
54
        OS << " aka ";
1790
54
        Bold();
1791
54
      }
1792
500
      if (PrintType) {
1793
24
        Unbold();
1794
24
        OS << "(";
1795
24
        Bold();
1796
24
        IntType.print(OS, Context.getPrintingPolicy());
1797
24
        Unbold();
1798
24
        OS << ") ";
1799
24
        Bold();
1800
24
      }
1801
500
      if (IntType->isBooleanType()) {
1802
20
        OS << ((Val == 0) ? 
"false"8
:
"true"12
);
1803
480
      } else {
1804
480
        OS << toString(Val, 10);
1805
480
      }
1806
500
    } else 
if (60
E60
) {
1807
8
      PrintExpr(E);
1808
52
    } else {
1809
52
      OS << "(no argument)";
1810
52
    }
1811
560
    Unbold();
1812
560
  }
1813
1814
  /// HasExtraInfo - Returns true if E is not an integer literal, the
1815
  /// negation of an integer literal, or a boolean literal.
1816
500
  bool HasExtraInfo(Expr *E) {
1817
500
    if (!E) 
return false117
;
1818
1819
383
    E = E->IgnoreImpCasts();
1820
1821
383
    if (isa<IntegerLiteral>(E)) 
return false313
;
1822
1823
70
    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
1824
0
      if (UO->getOpcode() == UO_Minus)
1825
0
        if (isa<IntegerLiteral>(UO->getSubExpr()))
1826
0
          return false;
1827
1828
70
    if (isa<CXXBoolLiteralExpr>(E))
1829
16
      return false;
1830
1831
54
    return true;
1832
70
  }
1833
1834
640
  void PrintValueDecl(ValueDecl *VD, bool AddressOf, Expr *E, bool NullPtr) {
1835
640
    if (VD) {
1836
514
      if (AddressOf)
1837
281
        OS << "&";
1838
233
      else if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(VD)) {
1839
        // FIXME: Diffing the APValue would be neat.
1840
        // FIXME: Suppress this and use the full name of the declaration if the
1841
        // parameter is a pointer or reference.
1842
4
        TPO->printAsInit(OS);
1843
4
        return;
1844
4
      }
1845
510
      VD->printName(OS);
1846
510
      return;
1847
514
    }
1848
1849
126
    if (NullPtr) {
1850
66
      if (E && 
!isa<CXXNullPtrLiteralExpr>(E)46
) {
1851
21
        PrintExpr(E);
1852
21
        if (IsBold) {
1853
16
          Unbold();
1854
16
          OS << " aka ";
1855
16
          Bold();
1856
16
        } else {
1857
5
          OS << " aka ";
1858
5
        }
1859
21
      }
1860
1861
66
      OS << "nullptr";
1862
66
      return;
1863
66
    }
1864
1865
60
    OS << "(no argument)";
1866
60
  }
1867
1868
  /// PrintDecl - Handles printing of Decl arguments, highlighting
1869
  /// argument differences.
1870
  void PrintValueDecl(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
1871
                      bool FromAddressOf, bool ToAddressOf, bool FromNullPtr,
1872
                      bool ToNullPtr, Expr *FromExpr, Expr *ToExpr,
1873
458
                      bool FromDefault, bool ToDefault, bool Same) {
1874
458
    assert((FromValueDecl || FromNullPtr || ToValueDecl || ToNullPtr) &&
1875
458
           "Only one Decl argument may be NULL");
1876
1877
458
    if (Same) {
1878
60
      PrintValueDecl(FromValueDecl, FromAddressOf, FromExpr, FromNullPtr);
1879
398
    } else if (!PrintTree) {
1880
268
      OS << (FromDefault ? 
"(default) "18
:
""250
);
1881
268
      Bold();
1882
268
      PrintValueDecl(FromValueDecl, FromAddressOf, FromExpr, FromNullPtr);
1883
268
      Unbold();
1884
268
    } else {
1885
130
      OS << (FromDefault ? 
"[(default) "18
:
"["112
);
1886
130
      Bold();
1887
130
      PrintValueDecl(FromValueDecl, FromAddressOf, FromExpr, FromNullPtr);
1888
130
      Unbold();
1889
130
      OS << " != " << (ToDefault ? 
"(default) "0
: "");
1890
130
      Bold();
1891
130
      PrintValueDecl(ToValueDecl, ToAddressOf, ToExpr, ToNullPtr);
1892
130
      Unbold();
1893
130
      OS << ']';
1894
130
    }
1895
458
  }
1896
1897
  /// PrintValueDeclAndInteger - Uses the print functions for ValueDecl and
1898
  /// APSInt to print a mixed difference.
1899
  void PrintValueDeclAndInteger(ValueDecl *VD, bool NeedAddressOf,
1900
                                bool IsNullPtr, Expr *VDExpr, bool DefaultDecl,
1901
                                const llvm::APSInt &Val, QualType IntType,
1902
39
                                Expr *IntExpr, bool DefaultInt) {
1903
39
    if (!PrintTree) {
1904
26
      OS << (DefaultDecl ? 
"(default) "4
:
""22
);
1905
26
      Bold();
1906
26
      PrintValueDecl(VD, NeedAddressOf, VDExpr, IsNullPtr);
1907
26
      Unbold();
1908
26
    } else {
1909
13
      OS << (DefaultDecl ? 
"[(default) "2
:
"["11
);
1910
13
      Bold();
1911
13
      PrintValueDecl(VD, NeedAddressOf, VDExpr, IsNullPtr);
1912
13
      Unbold();
1913
13
      OS << " != " << (DefaultInt ? 
"(default) "3
:
""10
);
1914
13
      PrintAPSInt(Val, IntExpr, true /*Valid*/, IntType, false /*PrintType*/);
1915
13
      OS << ']';
1916
13
    }
1917
39
  }
1918
1919
  /// PrintIntegerAndValueDecl - Uses the print functions for APSInt and
1920
  /// ValueDecl to print a mixed difference.
1921
  void PrintIntegerAndValueDecl(const llvm::APSInt &Val, QualType IntType,
1922
                                Expr *IntExpr, bool DefaultInt, ValueDecl *VD,
1923
                                bool NeedAddressOf, bool IsNullPtr,
1924
39
                                Expr *VDExpr, bool DefaultDecl) {
1925
39
    if (!PrintTree) {
1926
26
      OS << (DefaultInt ? 
"(default) "5
:
""21
);
1927
26
      PrintAPSInt(Val, IntExpr, true /*Valid*/, IntType, false /*PrintType*/);
1928
26
    } else {
1929
13
      OS << (DefaultInt ? 
"[(default) "2
:
"["11
);
1930
13
      PrintAPSInt(Val, IntExpr, true /*Valid*/, IntType, false /*PrintType*/);
1931
13
      OS << " != " << (DefaultDecl ? 
"(default) "2
:
""11
);
1932
13
      Bold();
1933
13
      PrintValueDecl(VD, NeedAddressOf, VDExpr, IsNullPtr);
1934
13
      Unbold();
1935
13
      OS << ']';
1936
13
    }
1937
39
  }
1938
1939
  // Prints the appropriate placeholder for elided template arguments.
1940
214
  void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1941
214
    if (PrintTree) {
1942
62
      OS << '\n';
1943
200
      for (unsigned i = 0; i < Indent; 
++i138
)
1944
138
        OS << "  ";
1945
62
    }
1946
214
    if (NumElideArgs == 0) 
return0
;
1947
214
    if (NumElideArgs == 1)
1948
178
      OS << "[...]";
1949
36
    else
1950
36
      OS << "[" << NumElideArgs << " * ...]";
1951
214
  }
1952
1953
  // Prints and highlights differences in Qualifiers.
1954
1.48k
  void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
1955
    // Both types have no qualifiers
1956
1.48k
    if (FromQual.empty() && 
ToQual.empty()1.34k
)
1957
1.16k
      return;
1958
1959
    // Both types have same qualifiers
1960
322
    if (FromQual == ToQual) {
1961
15
      PrintQualifier(FromQual, /*ApplyBold*/false);
1962
15
      return;
1963
15
    }
1964
1965
    // Find common qualifiers and strip them from FromQual and ToQual.
1966
307
    Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
1967
307
                                                               ToQual);
1968
1969
    // The qualifiers are printed before the template name.
1970
    // Inline printing:
1971
    // The common qualifiers are printed.  Then, qualifiers only in this type
1972
    // are printed and highlighted.  Finally, qualifiers only in the other
1973
    // type are printed and highlighted inside parentheses after "missing".
1974
    // Tree printing:
1975
    // Qualifiers are printed next to each other, inside brackets, and
1976
    // separated by "!=".  The printing order is:
1977
    // common qualifiers, highlighted from qualifiers, "!=",
1978
    // common qualifiers, highlighted to qualifiers
1979
307
    if (PrintTree) {
1980
93
      OS << "[";
1981
93
      if (CommonQual.empty() && 
FromQual.empty()90
) {
1982
79
        Bold();
1983
79
        OS << "(no qualifiers) ";
1984
79
        Unbold();
1985
79
      } else {
1986
14
        PrintQualifier(CommonQual, /*ApplyBold*/false);
1987
14
        PrintQualifier(FromQual, /*ApplyBold*/true);
1988
14
      }
1989
93
      OS << "!= ";
1990
93
      if (CommonQual.empty() && 
ToQual.empty()90
) {
1991
8
        Bold();
1992
8
        OS << "(no qualifiers)";
1993
8
        Unbold();
1994
85
      } else {
1995
85
        PrintQualifier(CommonQual, /*ApplyBold*/false,
1996
85
                       /*appendSpaceIfNonEmpty*/!ToQual.empty());
1997
85
        PrintQualifier(ToQual, /*ApplyBold*/true,
1998
85
                       /*appendSpaceIfNonEmpty*/false);
1999
85
      }
2000
93
      OS << "] ";
2001
214
    } else {
2002
214
      PrintQualifier(CommonQual, /*ApplyBold*/false);
2003
214
      PrintQualifier(FromQual, /*ApplyBold*/true);
2004
214
    }
2005
307
  }
2006
2007
  void PrintQualifier(Qualifiers Q, bool ApplyBold,
2008
641
                      bool AppendSpaceIfNonEmpty = true) {
2009
641
    if (Q.empty()) 
return407
;
2010
234
    if (ApplyBold) 
Bold()207
;
2011
234
    Q.print(OS, Policy, AppendSpaceIfNonEmpty);
2012
234
    if (ApplyBold) 
Unbold()207
;
2013
234
  }
2014
2015
public:
2016
2017
  TemplateDiff(raw_ostream &OS, ASTContext &Context, QualType FromType,
2018
               QualType ToType, bool PrintTree, bool PrintFromType,
2019
               bool ElideType, bool ShowColor)
2020
    : Context(Context),
2021
      Policy(Context.getLangOpts()),
2022
      ElideType(ElideType),
2023
      PrintTree(PrintTree),
2024
      ShowColor(ShowColor),
2025
      // When printing a single type, the FromType is the one printed.
2026
      FromTemplateType(PrintFromType ? FromType : ToType),
2027
      ToTemplateType(PrintFromType ? ToType : FromType),
2028
      OS(OS),
2029
34.5k
      IsBold(false) {
2030
34.5k
  }
2031
2032
  /// DiffTemplate - Start the template type diffing.
2033
34.5k
  void DiffTemplate() {
2034
34.5k
    Qualifiers FromQual = FromTemplateType.getQualifiers(),
2035
34.5k
               ToQual = ToTemplateType.getQualifiers();
2036
2037
34.5k
    const TemplateSpecializationType *FromOrigTST =
2038
34.5k
        GetTemplateSpecializationType(Context, FromTemplateType);
2039
34.5k
    const TemplateSpecializationType *ToOrigTST =
2040
34.5k
        GetTemplateSpecializationType(Context, ToTemplateType);
2041
2042
    // Only checking templates.
2043
34.5k
    if (!FromOrigTST || 
!ToOrigTST2.35k
)
2044
33.2k
      return;
2045
2046
    // Different base templates.
2047
1.31k
    if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
2048
46
      return;
2049
46
    }
2050
2051
1.26k
    FromQual -= QualType(FromOrigTST, 0).getQualifiers();
2052
1.26k
    ToQual -= QualType(ToOrigTST, 0).getQualifiers();
2053
2054
    // Same base template, but different arguments.
2055
1.26k
    Tree.SetTemplateDiff(FromOrigTST->getTemplateName().getAsTemplateDecl(),
2056
1.26k
                         ToOrigTST->getTemplateName().getAsTemplateDecl(),
2057
1.26k
                         FromQual, ToQual, false /*FromDefault*/,
2058
1.26k
                         false /*ToDefault*/);
2059
2060
1.26k
    DiffTemplate(FromOrigTST, ToOrigTST);
2061
1.26k
  }
2062
2063
  /// Emit - When the two types given are templated types with the same
2064
  /// base template, a string representation of the type difference will be
2065
  /// emitted to the stream and return true.  Otherwise, return false.
2066
34.5k
  bool Emit() {
2067
34.5k
    Tree.StartTraverse();
2068
34.5k
    if (Tree.Empty())
2069
33.2k
      return false;
2070
2071
1.26k
    TreeToString();
2072
1.26k
    assert(!IsBold && "Bold is applied to end of string.");
2073
0
    return true;
2074
34.5k
  }
2075
}; // end class TemplateDiff
2076
}  // end anonymous namespace
2077
2078
/// FormatTemplateTypeDiff - A helper static function to start the template
2079
/// diff and return the properly formatted string.  Returns true if the diff
2080
/// is successful.
2081
static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
2082
                                   QualType ToType, bool PrintTree,
2083
                                   bool PrintFromType, bool ElideType,
2084
34.5k
                                   bool ShowColors, raw_ostream &OS) {
2085
34.5k
  if (PrintTree)
2086
577
    PrintFromType = true;
2087
34.5k
  TemplateDiff TD(OS, Context, FromType, ToType, PrintTree, PrintFromType,
2088
34.5k
                  ElideType, ShowColors);
2089
34.5k
  TD.DiffTemplate();
2090
34.5k
  return TD.Emit();
2091
34.5k
}