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