xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaCodeComplete.cpp (revision 6580f5c38dd5b01aeeaed16b370f1a12423437f0)
1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
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 defines the code-completion semantic actions.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "clang/AST/ASTConcept.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclBase.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprConcepts.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/NestedNameSpecifier.h"
23 #include "clang/AST/QualTypeNames.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/AttributeCommonInfo.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/OperatorKinds.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Lex/HeaderSearch.h"
31 #include "clang/Lex/MacroInfo.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CodeCompleteConsumer.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Designator.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/Overload.h"
38 #include "clang/Sema/ParsedAttr.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/Sema.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/DenseSet.h"
46 #include "llvm/ADT/SmallBitVector.h"
47 #include "llvm/ADT/SmallPtrSet.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSwitch.h"
51 #include "llvm/ADT/Twine.h"
52 #include "llvm/ADT/iterator_range.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/Path.h"
55 #include "llvm/Support/raw_ostream.h"
56 
57 #include <list>
58 #include <map>
59 #include <optional>
60 #include <string>
61 #include <vector>
62 
63 using namespace clang;
64 using namespace sema;
65 
66 namespace {
67 /// A container of code-completion results.
68 class ResultBuilder {
69 public:
70   /// The type of a name-lookup filter, which can be provided to the
71   /// name-lookup routines to specify which declarations should be included in
72   /// the result set (when it returns true) and which declarations should be
73   /// filtered out (returns false).
74   typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
75 
76   typedef CodeCompletionResult Result;
77 
78 private:
79   /// The actual results we have found.
80   std::vector<Result> Results;
81 
82   /// A record of all of the declarations we have found and placed
83   /// into the result set, used to ensure that no declaration ever gets into
84   /// the result set twice.
85   llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
86 
87   typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
88 
89   /// An entry in the shadow map, which is optimized to store
90   /// a single (declaration, index) mapping (the common case) but
91   /// can also store a list of (declaration, index) mappings.
92   class ShadowMapEntry {
93     typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
94 
95     /// Contains either the solitary NamedDecl * or a vector
96     /// of (declaration, index) pairs.
97     llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
98 
99     /// When the entry contains a single declaration, this is
100     /// the index associated with that entry.
101     unsigned SingleDeclIndex = 0;
102 
103   public:
104     ShadowMapEntry() = default;
105     ShadowMapEntry(const ShadowMapEntry &) = delete;
106     ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
107     ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
108     ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
109       SingleDeclIndex = Move.SingleDeclIndex;
110       DeclOrVector = Move.DeclOrVector;
111       Move.DeclOrVector = nullptr;
112       return *this;
113     }
114 
115     void Add(const NamedDecl *ND, unsigned Index) {
116       if (DeclOrVector.isNull()) {
117         // 0 - > 1 elements: just set the single element information.
118         DeclOrVector = ND;
119         SingleDeclIndex = Index;
120         return;
121       }
122 
123       if (const NamedDecl *PrevND =
124               DeclOrVector.dyn_cast<const NamedDecl *>()) {
125         // 1 -> 2 elements: create the vector of results and push in the
126         // existing declaration.
127         DeclIndexPairVector *Vec = new DeclIndexPairVector;
128         Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
129         DeclOrVector = Vec;
130       }
131 
132       // Add the new element to the end of the vector.
133       DeclOrVector.get<DeclIndexPairVector *>()->push_back(
134           DeclIndexPair(ND, Index));
135     }
136 
137     ~ShadowMapEntry() {
138       if (DeclIndexPairVector *Vec =
139               DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
140         delete Vec;
141         DeclOrVector = ((NamedDecl *)nullptr);
142       }
143     }
144 
145     // Iteration.
146     class iterator;
147     iterator begin() const;
148     iterator end() const;
149   };
150 
151   /// A mapping from declaration names to the declarations that have
152   /// this name within a particular scope and their index within the list of
153   /// results.
154   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
155 
156   /// The semantic analysis object for which results are being
157   /// produced.
158   Sema &SemaRef;
159 
160   /// The allocator used to allocate new code-completion strings.
161   CodeCompletionAllocator &Allocator;
162 
163   CodeCompletionTUInfo &CCTUInfo;
164 
165   /// If non-NULL, a filter function used to remove any code-completion
166   /// results that are not desirable.
167   LookupFilter Filter;
168 
169   /// Whether we should allow declarations as
170   /// nested-name-specifiers that would otherwise be filtered out.
171   bool AllowNestedNameSpecifiers;
172 
173   /// If set, the type that we would prefer our resulting value
174   /// declarations to have.
175   ///
176   /// Closely matching the preferred type gives a boost to a result's
177   /// priority.
178   CanQualType PreferredType;
179 
180   /// A list of shadow maps, which is used to model name hiding at
181   /// different levels of, e.g., the inheritance hierarchy.
182   std::list<ShadowMap> ShadowMaps;
183 
184   /// Overloaded C++ member functions found by SemaLookup.
185   /// Used to determine when one overload is dominated by another.
186   llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
187       OverloadMap;
188 
189   /// If we're potentially referring to a C++ member function, the set
190   /// of qualifiers applied to the object type.
191   Qualifiers ObjectTypeQualifiers;
192   /// The kind of the object expression, for rvalue/lvalue overloads.
193   ExprValueKind ObjectKind;
194 
195   /// Whether the \p ObjectTypeQualifiers field is active.
196   bool HasObjectTypeQualifiers;
197 
198   /// The selector that we prefer.
199   Selector PreferredSelector;
200 
201   /// The completion context in which we are gathering results.
202   CodeCompletionContext CompletionContext;
203 
204   /// If we are in an instance method definition, the \@implementation
205   /// object.
206   ObjCImplementationDecl *ObjCImplementation;
207 
208   void AdjustResultPriorityForDecl(Result &R);
209 
210   void MaybeAddConstructorResults(Result R);
211 
212 public:
213   explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
214                          CodeCompletionTUInfo &CCTUInfo,
215                          const CodeCompletionContext &CompletionContext,
216                          LookupFilter Filter = nullptr)
217       : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
218         Filter(Filter), AllowNestedNameSpecifiers(false),
219         HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
220         ObjCImplementation(nullptr) {
221     // If this is an Objective-C instance method definition, dig out the
222     // corresponding implementation.
223     switch (CompletionContext.getKind()) {
224     case CodeCompletionContext::CCC_Expression:
225     case CodeCompletionContext::CCC_ObjCMessageReceiver:
226     case CodeCompletionContext::CCC_ParenthesizedExpression:
227     case CodeCompletionContext::CCC_Statement:
228     case CodeCompletionContext::CCC_TopLevelOrExpression:
229     case CodeCompletionContext::CCC_Recovery:
230       if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
231         if (Method->isInstanceMethod())
232           if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
233             ObjCImplementation = Interface->getImplementation();
234       break;
235 
236     default:
237       break;
238     }
239   }
240 
241   /// Determine the priority for a reference to the given declaration.
242   unsigned getBasePriority(const NamedDecl *D);
243 
244   /// Whether we should include code patterns in the completion
245   /// results.
246   bool includeCodePatterns() const {
247     return SemaRef.CodeCompleter &&
248            SemaRef.CodeCompleter->includeCodePatterns();
249   }
250 
251   /// Set the filter used for code-completion results.
252   void setFilter(LookupFilter Filter) { this->Filter = Filter; }
253 
254   Result *data() { return Results.empty() ? nullptr : &Results.front(); }
255   unsigned size() const { return Results.size(); }
256   bool empty() const { return Results.empty(); }
257 
258   /// Specify the preferred type.
259   void setPreferredType(QualType T) {
260     PreferredType = SemaRef.Context.getCanonicalType(T);
261   }
262 
263   /// Set the cv-qualifiers on the object type, for us in filtering
264   /// calls to member functions.
265   ///
266   /// When there are qualifiers in this set, they will be used to filter
267   /// out member functions that aren't available (because there will be a
268   /// cv-qualifier mismatch) or prefer functions with an exact qualifier
269   /// match.
270   void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
271     ObjectTypeQualifiers = Quals;
272     ObjectKind = Kind;
273     HasObjectTypeQualifiers = true;
274   }
275 
276   /// Set the preferred selector.
277   ///
278   /// When an Objective-C method declaration result is added, and that
279   /// method's selector matches this preferred selector, we give that method
280   /// a slight priority boost.
281   void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
282 
283   /// Retrieve the code-completion context for which results are
284   /// being collected.
285   const CodeCompletionContext &getCompletionContext() const {
286     return CompletionContext;
287   }
288 
289   /// Specify whether nested-name-specifiers are allowed.
290   void allowNestedNameSpecifiers(bool Allow = true) {
291     AllowNestedNameSpecifiers = Allow;
292   }
293 
294   /// Return the semantic analysis object for which we are collecting
295   /// code completion results.
296   Sema &getSema() const { return SemaRef; }
297 
298   /// Retrieve the allocator used to allocate code completion strings.
299   CodeCompletionAllocator &getAllocator() const { return Allocator; }
300 
301   CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
302 
303   /// Determine whether the given declaration is at all interesting
304   /// as a code-completion result.
305   ///
306   /// \param ND the declaration that we are inspecting.
307   ///
308   /// \param AsNestedNameSpecifier will be set true if this declaration is
309   /// only interesting when it is a nested-name-specifier.
310   bool isInterestingDecl(const NamedDecl *ND,
311                          bool &AsNestedNameSpecifier) const;
312 
313   /// Decide whether or not a use of function Decl can be a call.
314   ///
315   /// \param ND the function declaration.
316   ///
317   /// \param BaseExprType the object type in a member access expression,
318   /// if any.
319   bool canFunctionBeCalled(const NamedDecl *ND, QualType BaseExprType) const;
320 
321   /// Decide whether or not a use of member function Decl can be a call.
322   ///
323   /// \param Method the function declaration.
324   ///
325   /// \param BaseExprType the object type in a member access expression,
326   /// if any.
327   bool canCxxMethodBeCalled(const CXXMethodDecl *Method,
328                             QualType BaseExprType) const;
329 
330   /// Check whether the result is hidden by the Hiding declaration.
331   ///
332   /// \returns true if the result is hidden and cannot be found, false if
333   /// the hidden result could still be found. When false, \p R may be
334   /// modified to describe how the result can be found (e.g., via extra
335   /// qualification).
336   bool CheckHiddenResult(Result &R, DeclContext *CurContext,
337                          const NamedDecl *Hiding);
338 
339   /// Add a new result to this result set (if it isn't already in one
340   /// of the shadow maps), or replace an existing result (for, e.g., a
341   /// redeclaration).
342   ///
343   /// \param R the result to add (if it is unique).
344   ///
345   /// \param CurContext the context in which this result will be named.
346   void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
347 
348   /// Add a new result to this result set, where we already know
349   /// the hiding declaration (if any).
350   ///
351   /// \param R the result to add (if it is unique).
352   ///
353   /// \param CurContext the context in which this result will be named.
354   ///
355   /// \param Hiding the declaration that hides the result.
356   ///
357   /// \param InBaseClass whether the result was found in a base
358   /// class of the searched context.
359   ///
360   /// \param BaseExprType the type of expression that precedes the "." or "->"
361   /// in a member access expression.
362   void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
363                  bool InBaseClass, QualType BaseExprType);
364 
365   /// Add a new non-declaration result to this result set.
366   void AddResult(Result R);
367 
368   /// Enter into a new scope.
369   void EnterNewScope();
370 
371   /// Exit from the current scope.
372   void ExitScope();
373 
374   /// Ignore this declaration, if it is seen again.
375   void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
376 
377   /// Add a visited context.
378   void addVisitedContext(DeclContext *Ctx) {
379     CompletionContext.addVisitedContext(Ctx);
380   }
381 
382   /// \name Name lookup predicates
383   ///
384   /// These predicates can be passed to the name lookup functions to filter the
385   /// results of name lookup. All of the predicates have the same type, so that
386   ///
387   //@{
388   bool IsOrdinaryName(const NamedDecl *ND) const;
389   bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
390   bool IsIntegralConstantValue(const NamedDecl *ND) const;
391   bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
392   bool IsNestedNameSpecifier(const NamedDecl *ND) const;
393   bool IsEnum(const NamedDecl *ND) const;
394   bool IsClassOrStruct(const NamedDecl *ND) const;
395   bool IsUnion(const NamedDecl *ND) const;
396   bool IsNamespace(const NamedDecl *ND) const;
397   bool IsNamespaceOrAlias(const NamedDecl *ND) const;
398   bool IsType(const NamedDecl *ND) const;
399   bool IsMember(const NamedDecl *ND) const;
400   bool IsObjCIvar(const NamedDecl *ND) const;
401   bool IsObjCMessageReceiver(const NamedDecl *ND) const;
402   bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
403   bool IsObjCCollection(const NamedDecl *ND) const;
404   bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
405   //@}
406 };
407 } // namespace
408 
409 void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
410   if (!Enabled)
411     return;
412   if (isa<BlockDecl>(S.CurContext)) {
413     if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
414       ComputeType = nullptr;
415       Type = BSI->ReturnType;
416       ExpectedLoc = Tok;
417     }
418   } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
419     ComputeType = nullptr;
420     Type = Function->getReturnType();
421     ExpectedLoc = Tok;
422   } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
423     ComputeType = nullptr;
424     Type = Method->getReturnType();
425     ExpectedLoc = Tok;
426   }
427 }
428 
429 void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
430   if (!Enabled)
431     return;
432   auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
433   ComputeType = nullptr;
434   Type = VD ? VD->getType() : QualType();
435   ExpectedLoc = Tok;
436 }
437 
438 static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
439 
440 void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
441                                                       QualType BaseType,
442                                                       const Designation &D) {
443   if (!Enabled)
444     return;
445   ComputeType = nullptr;
446   Type = getDesignatedType(BaseType, D);
447   ExpectedLoc = Tok;
448 }
449 
450 void PreferredTypeBuilder::enterFunctionArgument(
451     SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
452   if (!Enabled)
453     return;
454   this->ComputeType = ComputeType;
455   Type = QualType();
456   ExpectedLoc = Tok;
457 }
458 
459 void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
460                                           SourceLocation LParLoc) {
461   if (!Enabled)
462     return;
463   // expected type for parenthesized expression does not change.
464   if (ExpectedLoc == LParLoc)
465     ExpectedLoc = Tok;
466 }
467 
468 static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
469                                             tok::TokenKind Op) {
470   if (!LHS)
471     return QualType();
472 
473   QualType LHSType = LHS->getType();
474   if (LHSType->isPointerType()) {
475     if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
476       return S.getASTContext().getPointerDiffType();
477     // Pointer difference is more common than subtracting an int from a pointer.
478     if (Op == tok::minus)
479       return LHSType;
480   }
481 
482   switch (Op) {
483   // No way to infer the type of RHS from LHS.
484   case tok::comma:
485     return QualType();
486   // Prefer the type of the left operand for all of these.
487   // Arithmetic operations.
488   case tok::plus:
489   case tok::plusequal:
490   case tok::minus:
491   case tok::minusequal:
492   case tok::percent:
493   case tok::percentequal:
494   case tok::slash:
495   case tok::slashequal:
496   case tok::star:
497   case tok::starequal:
498   // Assignment.
499   case tok::equal:
500   // Comparison operators.
501   case tok::equalequal:
502   case tok::exclaimequal:
503   case tok::less:
504   case tok::lessequal:
505   case tok::greater:
506   case tok::greaterequal:
507   case tok::spaceship:
508     return LHS->getType();
509   // Binary shifts are often overloaded, so don't try to guess those.
510   case tok::greatergreater:
511   case tok::greatergreaterequal:
512   case tok::lessless:
513   case tok::lesslessequal:
514     if (LHSType->isIntegralOrEnumerationType())
515       return S.getASTContext().IntTy;
516     return QualType();
517   // Logical operators, assume we want bool.
518   case tok::ampamp:
519   case tok::pipepipe:
520   case tok::caretcaret:
521     return S.getASTContext().BoolTy;
522   // Operators often used for bit manipulation are typically used with the type
523   // of the left argument.
524   case tok::pipe:
525   case tok::pipeequal:
526   case tok::caret:
527   case tok::caretequal:
528   case tok::amp:
529   case tok::ampequal:
530     if (LHSType->isIntegralOrEnumerationType())
531       return LHSType;
532     return QualType();
533   // RHS should be a pointer to a member of the 'LHS' type, but we can't give
534   // any particular type here.
535   case tok::periodstar:
536   case tok::arrowstar:
537     return QualType();
538   default:
539     // FIXME(ibiryukov): handle the missing op, re-add the assertion.
540     // assert(false && "unhandled binary op");
541     return QualType();
542   }
543 }
544 
545 /// Get preferred type for an argument of an unary expression. \p ContextType is
546 /// preferred type of the whole unary expression.
547 static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
548                                            tok::TokenKind Op) {
549   switch (Op) {
550   case tok::exclaim:
551     return S.getASTContext().BoolTy;
552   case tok::amp:
553     if (!ContextType.isNull() && ContextType->isPointerType())
554       return ContextType->getPointeeType();
555     return QualType();
556   case tok::star:
557     if (ContextType.isNull())
558       return QualType();
559     return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
560   case tok::plus:
561   case tok::minus:
562   case tok::tilde:
563   case tok::minusminus:
564   case tok::plusplus:
565     if (ContextType.isNull())
566       return S.getASTContext().IntTy;
567     // leave as is, these operators typically return the same type.
568     return ContextType;
569   case tok::kw___real:
570   case tok::kw___imag:
571     return QualType();
572   default:
573     assert(false && "unhandled unary op");
574     return QualType();
575   }
576 }
577 
578 void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
579                                        tok::TokenKind Op) {
580   if (!Enabled)
581     return;
582   ComputeType = nullptr;
583   Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
584   ExpectedLoc = Tok;
585 }
586 
587 void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
588                                           Expr *Base) {
589   if (!Enabled || !Base)
590     return;
591   // Do we have expected type for Base?
592   if (ExpectedLoc != Base->getBeginLoc())
593     return;
594   // Keep the expected type, only update the location.
595   ExpectedLoc = Tok;
596 }
597 
598 void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
599                                       tok::TokenKind OpKind,
600                                       SourceLocation OpLoc) {
601   if (!Enabled)
602     return;
603   ComputeType = nullptr;
604   Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
605   ExpectedLoc = Tok;
606 }
607 
608 void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
609                                           Expr *LHS) {
610   if (!Enabled)
611     return;
612   ComputeType = nullptr;
613   Type = S.getASTContext().IntTy;
614   ExpectedLoc = Tok;
615 }
616 
617 void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
618                                          QualType CastType) {
619   if (!Enabled)
620     return;
621   ComputeType = nullptr;
622   Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
623   ExpectedLoc = Tok;
624 }
625 
626 void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
627   if (!Enabled)
628     return;
629   ComputeType = nullptr;
630   Type = S.getASTContext().BoolTy;
631   ExpectedLoc = Tok;
632 }
633 
634 class ResultBuilder::ShadowMapEntry::iterator {
635   llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
636   unsigned SingleDeclIndex;
637 
638 public:
639   typedef DeclIndexPair value_type;
640   typedef value_type reference;
641   typedef std::ptrdiff_t difference_type;
642   typedef std::input_iterator_tag iterator_category;
643 
644   class pointer {
645     DeclIndexPair Value;
646 
647   public:
648     pointer(const DeclIndexPair &Value) : Value(Value) {}
649 
650     const DeclIndexPair *operator->() const { return &Value; }
651   };
652 
653   iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
654 
655   iterator(const NamedDecl *SingleDecl, unsigned Index)
656       : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
657 
658   iterator(const DeclIndexPair *Iterator)
659       : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
660 
661   iterator &operator++() {
662     if (DeclOrIterator.is<const NamedDecl *>()) {
663       DeclOrIterator = (NamedDecl *)nullptr;
664       SingleDeclIndex = 0;
665       return *this;
666     }
667 
668     const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
669     ++I;
670     DeclOrIterator = I;
671     return *this;
672   }
673 
674   /*iterator operator++(int) {
675     iterator tmp(*this);
676     ++(*this);
677     return tmp;
678   }*/
679 
680   reference operator*() const {
681     if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
682       return reference(ND, SingleDeclIndex);
683 
684     return *DeclOrIterator.get<const DeclIndexPair *>();
685   }
686 
687   pointer operator->() const { return pointer(**this); }
688 
689   friend bool operator==(const iterator &X, const iterator &Y) {
690     return X.DeclOrIterator.getOpaqueValue() ==
691                Y.DeclOrIterator.getOpaqueValue() &&
692            X.SingleDeclIndex == Y.SingleDeclIndex;
693   }
694 
695   friend bool operator!=(const iterator &X, const iterator &Y) {
696     return !(X == Y);
697   }
698 };
699 
700 ResultBuilder::ShadowMapEntry::iterator
701 ResultBuilder::ShadowMapEntry::begin() const {
702   if (DeclOrVector.isNull())
703     return iterator();
704 
705   if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
706     return iterator(ND, SingleDeclIndex);
707 
708   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
709 }
710 
711 ResultBuilder::ShadowMapEntry::iterator
712 ResultBuilder::ShadowMapEntry::end() const {
713   if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
714     return iterator();
715 
716   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
717 }
718 
719 /// Compute the qualification required to get from the current context
720 /// (\p CurContext) to the target context (\p TargetContext).
721 ///
722 /// \param Context the AST context in which the qualification will be used.
723 ///
724 /// \param CurContext the context where an entity is being named, which is
725 /// typically based on the current scope.
726 ///
727 /// \param TargetContext the context in which the named entity actually
728 /// resides.
729 ///
730 /// \returns a nested name specifier that refers into the target context, or
731 /// NULL if no qualification is needed.
732 static NestedNameSpecifier *
733 getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
734                          const DeclContext *TargetContext) {
735   SmallVector<const DeclContext *, 4> TargetParents;
736 
737   for (const DeclContext *CommonAncestor = TargetContext;
738        CommonAncestor && !CommonAncestor->Encloses(CurContext);
739        CommonAncestor = CommonAncestor->getLookupParent()) {
740     if (CommonAncestor->isTransparentContext() ||
741         CommonAncestor->isFunctionOrMethod())
742       continue;
743 
744     TargetParents.push_back(CommonAncestor);
745   }
746 
747   NestedNameSpecifier *Result = nullptr;
748   while (!TargetParents.empty()) {
749     const DeclContext *Parent = TargetParents.pop_back_val();
750 
751     if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
752       if (!Namespace->getIdentifier())
753         continue;
754 
755       Result = NestedNameSpecifier::Create(Context, Result, Namespace);
756     } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
757       Result = NestedNameSpecifier::Create(
758           Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
759   }
760   return Result;
761 }
762 
763 // Some declarations have reserved names that we don't want to ever show.
764 // Filter out names reserved for the implementation if they come from a
765 // system header.
766 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
767   ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
768   // Ignore reserved names for compiler provided decls.
769   if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
770     return true;
771 
772   // For system headers ignore only double-underscore names.
773   // This allows for system headers providing private symbols with a single
774   // underscore.
775   if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore &&
776       SemaRef.SourceMgr.isInSystemHeader(
777           SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
778     return true;
779 
780   return false;
781 }
782 
783 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
784                                       bool &AsNestedNameSpecifier) const {
785   AsNestedNameSpecifier = false;
786 
787   auto *Named = ND;
788   ND = ND->getUnderlyingDecl();
789 
790   // Skip unnamed entities.
791   if (!ND->getDeclName())
792     return false;
793 
794   // Friend declarations and declarations introduced due to friends are never
795   // added as results.
796   if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
797     return false;
798 
799   // Class template (partial) specializations are never added as results.
800   if (isa<ClassTemplateSpecializationDecl>(ND) ||
801       isa<ClassTemplatePartialSpecializationDecl>(ND))
802     return false;
803 
804   // Using declarations themselves are never added as results.
805   if (isa<UsingDecl>(ND))
806     return false;
807 
808   if (shouldIgnoreDueToReservedName(ND, SemaRef))
809     return false;
810 
811   if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
812       (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
813        Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
814     AsNestedNameSpecifier = true;
815 
816   // Filter out any unwanted results.
817   if (Filter && !(this->*Filter)(Named)) {
818     // Check whether it is interesting as a nested-name-specifier.
819     if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
820         IsNestedNameSpecifier(ND) &&
821         (Filter != &ResultBuilder::IsMember ||
822          (isa<CXXRecordDecl>(ND) &&
823           cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
824       AsNestedNameSpecifier = true;
825       return true;
826     }
827 
828     return false;
829   }
830   // ... then it must be interesting!
831   return true;
832 }
833 
834 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
835                                       const NamedDecl *Hiding) {
836   // In C, there is no way to refer to a hidden name.
837   // FIXME: This isn't true; we can find a tag name hidden by an ordinary
838   // name if we introduce the tag type.
839   if (!SemaRef.getLangOpts().CPlusPlus)
840     return true;
841 
842   const DeclContext *HiddenCtx =
843       R.Declaration->getDeclContext()->getRedeclContext();
844 
845   // There is no way to qualify a name declared in a function or method.
846   if (HiddenCtx->isFunctionOrMethod())
847     return true;
848 
849   if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
850     return true;
851 
852   // We can refer to the result with the appropriate qualification. Do it.
853   R.Hidden = true;
854   R.QualifierIsInformative = false;
855 
856   if (!R.Qualifier)
857     R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
858                                            R.Declaration->getDeclContext());
859   return false;
860 }
861 
862 /// A simplified classification of types used to determine whether two
863 /// types are "similar enough" when adjusting priorities.
864 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
865   switch (T->getTypeClass()) {
866   case Type::Builtin:
867     switch (cast<BuiltinType>(T)->getKind()) {
868     case BuiltinType::Void:
869       return STC_Void;
870 
871     case BuiltinType::NullPtr:
872       return STC_Pointer;
873 
874     case BuiltinType::Overload:
875     case BuiltinType::Dependent:
876       return STC_Other;
877 
878     case BuiltinType::ObjCId:
879     case BuiltinType::ObjCClass:
880     case BuiltinType::ObjCSel:
881       return STC_ObjectiveC;
882 
883     default:
884       return STC_Arithmetic;
885     }
886 
887   case Type::Complex:
888     return STC_Arithmetic;
889 
890   case Type::Pointer:
891     return STC_Pointer;
892 
893   case Type::BlockPointer:
894     return STC_Block;
895 
896   case Type::LValueReference:
897   case Type::RValueReference:
898     return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
899 
900   case Type::ConstantArray:
901   case Type::IncompleteArray:
902   case Type::VariableArray:
903   case Type::DependentSizedArray:
904     return STC_Array;
905 
906   case Type::DependentSizedExtVector:
907   case Type::Vector:
908   case Type::ExtVector:
909     return STC_Arithmetic;
910 
911   case Type::FunctionProto:
912   case Type::FunctionNoProto:
913     return STC_Function;
914 
915   case Type::Record:
916     return STC_Record;
917 
918   case Type::Enum:
919     return STC_Arithmetic;
920 
921   case Type::ObjCObject:
922   case Type::ObjCInterface:
923   case Type::ObjCObjectPointer:
924     return STC_ObjectiveC;
925 
926   default:
927     return STC_Other;
928   }
929 }
930 
931 /// Get the type that a given expression will have if this declaration
932 /// is used as an expression in its "typical" code-completion form.
933 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
934   ND = ND->getUnderlyingDecl();
935 
936   if (const auto *Type = dyn_cast<TypeDecl>(ND))
937     return C.getTypeDeclType(Type);
938   if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
939     return C.getObjCInterfaceType(Iface);
940 
941   QualType T;
942   if (const FunctionDecl *Function = ND->getAsFunction())
943     T = Function->getCallResultType();
944   else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
945     T = Method->getSendResultType();
946   else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
947     T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
948   else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
949     T = Property->getType();
950   else if (const auto *Value = dyn_cast<ValueDecl>(ND))
951     T = Value->getType();
952 
953   if (T.isNull())
954     return QualType();
955 
956   // Dig through references, function pointers, and block pointers to
957   // get down to the likely type of an expression when the entity is
958   // used.
959   do {
960     if (const auto *Ref = T->getAs<ReferenceType>()) {
961       T = Ref->getPointeeType();
962       continue;
963     }
964 
965     if (const auto *Pointer = T->getAs<PointerType>()) {
966       if (Pointer->getPointeeType()->isFunctionType()) {
967         T = Pointer->getPointeeType();
968         continue;
969       }
970 
971       break;
972     }
973 
974     if (const auto *Block = T->getAs<BlockPointerType>()) {
975       T = Block->getPointeeType();
976       continue;
977     }
978 
979     if (const auto *Function = T->getAs<FunctionType>()) {
980       T = Function->getReturnType();
981       continue;
982     }
983 
984     break;
985   } while (true);
986 
987   return T;
988 }
989 
990 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
991   if (!ND)
992     return CCP_Unlikely;
993 
994   // Context-based decisions.
995   const DeclContext *LexicalDC = ND->getLexicalDeclContext();
996   if (LexicalDC->isFunctionOrMethod()) {
997     // _cmd is relatively rare
998     if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
999       if (ImplicitParam->getIdentifier() &&
1000           ImplicitParam->getIdentifier()->isStr("_cmd"))
1001         return CCP_ObjC_cmd;
1002 
1003     return CCP_LocalDeclaration;
1004   }
1005 
1006   const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
1007   if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
1008     // Explicit destructor calls are very rare.
1009     if (isa<CXXDestructorDecl>(ND))
1010       return CCP_Unlikely;
1011     // Explicit operator and conversion function calls are also very rare.
1012     auto DeclNameKind = ND->getDeclName().getNameKind();
1013     if (DeclNameKind == DeclarationName::CXXOperatorName ||
1014         DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
1015         DeclNameKind == DeclarationName::CXXConversionFunctionName)
1016       return CCP_Unlikely;
1017     return CCP_MemberDeclaration;
1018   }
1019 
1020   // Content-based decisions.
1021   if (isa<EnumConstantDecl>(ND))
1022     return CCP_Constant;
1023 
1024   // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1025   // message receiver, or parenthesized expression context. There, it's as
1026   // likely that the user will want to write a type as other declarations.
1027   if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
1028       !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
1029         CompletionContext.getKind() ==
1030             CodeCompletionContext::CCC_ObjCMessageReceiver ||
1031         CompletionContext.getKind() ==
1032             CodeCompletionContext::CCC_ParenthesizedExpression))
1033     return CCP_Type;
1034 
1035   return CCP_Declaration;
1036 }
1037 
1038 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
1039   // If this is an Objective-C method declaration whose selector matches our
1040   // preferred selector, give it a priority boost.
1041   if (!PreferredSelector.isNull())
1042     if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
1043       if (PreferredSelector == Method->getSelector())
1044         R.Priority += CCD_SelectorMatch;
1045 
1046   // If we have a preferred type, adjust the priority for results with exactly-
1047   // matching or nearly-matching types.
1048   if (!PreferredType.isNull()) {
1049     QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
1050     if (!T.isNull()) {
1051       CanQualType TC = SemaRef.Context.getCanonicalType(T);
1052       // Check for exactly-matching types (modulo qualifiers).
1053       if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
1054         R.Priority /= CCF_ExactTypeMatch;
1055       // Check for nearly-matching types, based on classification of each.
1056       else if ((getSimplifiedTypeClass(PreferredType) ==
1057                 getSimplifiedTypeClass(TC)) &&
1058                !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
1059         R.Priority /= CCF_SimilarTypeMatch;
1060     }
1061   }
1062 }
1063 
1064 static DeclContext::lookup_result getConstructors(ASTContext &Context,
1065                                                   const CXXRecordDecl *Record) {
1066   QualType RecordTy = Context.getTypeDeclType(Record);
1067   DeclarationName ConstructorName =
1068       Context.DeclarationNames.getCXXConstructorName(
1069           Context.getCanonicalType(RecordTy));
1070   return Record->lookup(ConstructorName);
1071 }
1072 
1073 void ResultBuilder::MaybeAddConstructorResults(Result R) {
1074   if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
1075       !CompletionContext.wantConstructorResults())
1076     return;
1077 
1078   const NamedDecl *D = R.Declaration;
1079   const CXXRecordDecl *Record = nullptr;
1080   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1081     Record = ClassTemplate->getTemplatedDecl();
1082   else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1083     // Skip specializations and partial specializations.
1084     if (isa<ClassTemplateSpecializationDecl>(Record))
1085       return;
1086   } else {
1087     // There are no constructors here.
1088     return;
1089   }
1090 
1091   Record = Record->getDefinition();
1092   if (!Record)
1093     return;
1094 
1095   for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
1096     R.Declaration = Ctor;
1097     R.CursorKind = getCursorKindForDecl(R.Declaration);
1098     Results.push_back(R);
1099   }
1100 }
1101 
1102 static bool isConstructor(const Decl *ND) {
1103   if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1104     ND = Tmpl->getTemplatedDecl();
1105   return isa<CXXConstructorDecl>(ND);
1106 }
1107 
1108 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1109   assert(!ShadowMaps.empty() && "Must enter into a results scope");
1110 
1111   if (R.Kind != Result::RK_Declaration) {
1112     // For non-declaration results, just add the result.
1113     Results.push_back(R);
1114     return;
1115   }
1116 
1117   // Look through using declarations.
1118   if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1119     CodeCompletionResult Result(Using->getTargetDecl(),
1120                                 getBasePriority(Using->getTargetDecl()),
1121                                 R.Qualifier, false,
1122                                 (R.Availability == CXAvailability_Available ||
1123                                  R.Availability == CXAvailability_Deprecated),
1124                                 std::move(R.FixIts));
1125     Result.ShadowDecl = Using;
1126     MaybeAddResult(Result, CurContext);
1127     return;
1128   }
1129 
1130   const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1131   unsigned IDNS = CanonDecl->getIdentifierNamespace();
1132 
1133   bool AsNestedNameSpecifier = false;
1134   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1135     return;
1136 
1137   // C++ constructors are never found by name lookup.
1138   if (isConstructor(R.Declaration))
1139     return;
1140 
1141   ShadowMap &SMap = ShadowMaps.back();
1142   ShadowMapEntry::iterator I, IEnd;
1143   ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1144   if (NamePos != SMap.end()) {
1145     I = NamePos->second.begin();
1146     IEnd = NamePos->second.end();
1147   }
1148 
1149   for (; I != IEnd; ++I) {
1150     const NamedDecl *ND = I->first;
1151     unsigned Index = I->second;
1152     if (ND->getCanonicalDecl() == CanonDecl) {
1153       // This is a redeclaration. Always pick the newer declaration.
1154       Results[Index].Declaration = R.Declaration;
1155 
1156       // We're done.
1157       return;
1158     }
1159   }
1160 
1161   // This is a new declaration in this scope. However, check whether this
1162   // declaration name is hidden by a similarly-named declaration in an outer
1163   // scope.
1164   std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1165   --SMEnd;
1166   for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
1167     ShadowMapEntry::iterator I, IEnd;
1168     ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1169     if (NamePos != SM->end()) {
1170       I = NamePos->second.begin();
1171       IEnd = NamePos->second.end();
1172     }
1173     for (; I != IEnd; ++I) {
1174       // A tag declaration does not hide a non-tag declaration.
1175       if (I->first->hasTagIdentifierNamespace() &&
1176           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1177                    Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
1178         continue;
1179 
1180       // Protocols are in distinct namespaces from everything else.
1181       if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1182            (IDNS & Decl::IDNS_ObjCProtocol)) &&
1183           I->first->getIdentifierNamespace() != IDNS)
1184         continue;
1185 
1186       // The newly-added result is hidden by an entry in the shadow map.
1187       if (CheckHiddenResult(R, CurContext, I->first))
1188         return;
1189 
1190       break;
1191     }
1192   }
1193 
1194   // Make sure that any given declaration only shows up in the result set once.
1195   if (!AllDeclsFound.insert(CanonDecl).second)
1196     return;
1197 
1198   // If the filter is for nested-name-specifiers, then this result starts a
1199   // nested-name-specifier.
1200   if (AsNestedNameSpecifier) {
1201     R.StartsNestedNameSpecifier = true;
1202     R.Priority = CCP_NestedNameSpecifier;
1203   } else
1204     AdjustResultPriorityForDecl(R);
1205 
1206   // If this result is supposed to have an informative qualifier, add one.
1207   if (R.QualifierIsInformative && !R.Qualifier &&
1208       !R.StartsNestedNameSpecifier) {
1209     const DeclContext *Ctx = R.Declaration->getDeclContext();
1210     if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1211       R.Qualifier =
1212           NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1213     else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1214       R.Qualifier = NestedNameSpecifier::Create(
1215           SemaRef.Context, nullptr, false,
1216           SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1217     else
1218       R.QualifierIsInformative = false;
1219   }
1220 
1221   // Insert this result into the set of results and into the current shadow
1222   // map.
1223   SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1224   Results.push_back(R);
1225 
1226   if (!AsNestedNameSpecifier)
1227     MaybeAddConstructorResults(R);
1228 }
1229 
1230 static void setInBaseClass(ResultBuilder::Result &R) {
1231   R.Priority += CCD_InBaseClass;
1232   R.InBaseClass = true;
1233 }
1234 
1235 enum class OverloadCompare { BothViable, Dominates, Dominated };
1236 // Will Candidate ever be called on the object, when overloaded with Incumbent?
1237 // Returns Dominates if Candidate is always called, Dominated if Incumbent is
1238 // always called, BothViable if either may be called depending on arguments.
1239 // Precondition: must actually be overloads!
1240 static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate,
1241                                         const CXXMethodDecl &Incumbent,
1242                                         const Qualifiers &ObjectQuals,
1243                                         ExprValueKind ObjectKind) {
1244   // Base/derived shadowing is handled elsewhere.
1245   if (Candidate.getDeclContext() != Incumbent.getDeclContext())
1246     return OverloadCompare::BothViable;
1247   if (Candidate.isVariadic() != Incumbent.isVariadic() ||
1248       Candidate.getNumParams() != Incumbent.getNumParams() ||
1249       Candidate.getMinRequiredArguments() !=
1250           Incumbent.getMinRequiredArguments())
1251     return OverloadCompare::BothViable;
1252   for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
1253     if (Candidate.parameters()[I]->getType().getCanonicalType() !=
1254         Incumbent.parameters()[I]->getType().getCanonicalType())
1255       return OverloadCompare::BothViable;
1256   if (!Candidate.specific_attrs<EnableIfAttr>().empty() ||
1257       !Incumbent.specific_attrs<EnableIfAttr>().empty())
1258     return OverloadCompare::BothViable;
1259   // At this point, we know calls can't pick one or the other based on
1260   // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1261   RefQualifierKind CandidateRef = Candidate.getRefQualifier();
1262   RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
1263   if (CandidateRef != IncumbentRef) {
1264     // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1265     // and it can't be mixed with ref-unqualified overloads (in valid code).
1266 
1267     // For xvalue objects, we prefer the rvalue overload even if we have to
1268     // add qualifiers (which is rare, because const&& is rare).
1269     if (ObjectKind == clang::VK_XValue)
1270       return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
1271                                        : OverloadCompare::Dominated;
1272   }
1273   // Now the ref qualifiers are the same (or we're in some invalid state).
1274   // So make some decision based on the qualifiers.
1275   Qualifiers CandidateQual = Candidate.getMethodQualifiers();
1276   Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
1277   bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
1278   bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
1279   if (CandidateSuperset == IncumbentSuperset)
1280     return OverloadCompare::BothViable;
1281   return IncumbentSuperset ? OverloadCompare::Dominates
1282                            : OverloadCompare::Dominated;
1283 }
1284 
1285 bool ResultBuilder::canCxxMethodBeCalled(const CXXMethodDecl *Method,
1286                                          QualType BaseExprType) const {
1287   // Find the class scope that we're currently in.
1288   // We could e.g. be inside a lambda, so walk up the DeclContext until we
1289   // find a CXXMethodDecl.
1290   DeclContext *CurContext = SemaRef.CurContext;
1291   const auto *CurrentClassScope = [&]() -> const CXXRecordDecl * {
1292     for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
1293       const auto *CtxMethod = llvm::dyn_cast<CXXMethodDecl>(Ctx);
1294       if (CtxMethod && !CtxMethod->getParent()->isLambda()) {
1295         return CtxMethod->getParent();
1296       }
1297     }
1298     return nullptr;
1299   }();
1300 
1301   // If we're not inside the scope of the method's class, it can't be a call.
1302   bool FunctionCanBeCall =
1303       CurrentClassScope &&
1304       (CurrentClassScope == Method->getParent() ||
1305        CurrentClassScope->isDerivedFrom(Method->getParent()));
1306 
1307   // We skip the following calculation for exceptions if it's already true.
1308   if (FunctionCanBeCall)
1309     return true;
1310 
1311   // Exception: foo->FooBase::bar() or foo->Foo::bar() *is* a call.
1312   if (const CXXRecordDecl *MaybeDerived =
1313           BaseExprType.isNull() ? nullptr
1314                                 : BaseExprType->getAsCXXRecordDecl()) {
1315     auto *MaybeBase = Method->getParent();
1316     FunctionCanBeCall =
1317         MaybeDerived == MaybeBase || MaybeDerived->isDerivedFrom(MaybeBase);
1318   }
1319 
1320   return FunctionCanBeCall;
1321 }
1322 
1323 bool ResultBuilder::canFunctionBeCalled(const NamedDecl *ND,
1324                                         QualType BaseExprType) const {
1325   // We apply heuristics only to CCC_Symbol:
1326   // * CCC_{Arrow,Dot}MemberAccess reflect member access expressions:
1327   //   f.method() and f->method(). These are always calls.
1328   // * A qualified name to a member function may *not* be a call. We have to
1329   //   subdivide the cases: For example, f.Base::method(), which is regarded as
1330   //   CCC_Symbol, should be a call.
1331   // * Non-member functions and static member functions are always considered
1332   //   calls.
1333   if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) {
1334     if (const auto *FuncTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1335       ND = FuncTmpl->getTemplatedDecl();
1336     }
1337     const auto *Method = dyn_cast<CXXMethodDecl>(ND);
1338     if (Method && !Method->isStatic()) {
1339       return canCxxMethodBeCalled(Method, BaseExprType);
1340     }
1341   }
1342   return true;
1343 }
1344 
1345 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1346                               NamedDecl *Hiding, bool InBaseClass = false,
1347                               QualType BaseExprType = QualType()) {
1348   if (R.Kind != Result::RK_Declaration) {
1349     // For non-declaration results, just add the result.
1350     Results.push_back(R);
1351     return;
1352   }
1353 
1354   // Look through using declarations.
1355   if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1356     CodeCompletionResult Result(Using->getTargetDecl(),
1357                                 getBasePriority(Using->getTargetDecl()),
1358                                 R.Qualifier, false,
1359                                 (R.Availability == CXAvailability_Available ||
1360                                  R.Availability == CXAvailability_Deprecated),
1361                                 std::move(R.FixIts));
1362     Result.ShadowDecl = Using;
1363     AddResult(Result, CurContext, Hiding, /*InBaseClass=*/false,
1364               /*BaseExprType=*/BaseExprType);
1365     return;
1366   }
1367 
1368   bool AsNestedNameSpecifier = false;
1369   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1370     return;
1371 
1372   // C++ constructors are never found by name lookup.
1373   if (isConstructor(R.Declaration))
1374     return;
1375 
1376   if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
1377     return;
1378 
1379   // Make sure that any given declaration only shows up in the result set once.
1380   if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1381     return;
1382 
1383   // If the filter is for nested-name-specifiers, then this result starts a
1384   // nested-name-specifier.
1385   if (AsNestedNameSpecifier) {
1386     R.StartsNestedNameSpecifier = true;
1387     R.Priority = CCP_NestedNameSpecifier;
1388   } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
1389              InBaseClass &&
1390              isa<CXXRecordDecl>(
1391                  R.Declaration->getDeclContext()->getRedeclContext()))
1392     R.QualifierIsInformative = true;
1393 
1394   // If this result is supposed to have an informative qualifier, add one.
1395   if (R.QualifierIsInformative && !R.Qualifier &&
1396       !R.StartsNestedNameSpecifier) {
1397     const DeclContext *Ctx = R.Declaration->getDeclContext();
1398     if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1399       R.Qualifier =
1400           NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1401     else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1402       R.Qualifier = NestedNameSpecifier::Create(
1403           SemaRef.Context, nullptr, false,
1404           SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1405     else
1406       R.QualifierIsInformative = false;
1407   }
1408 
1409   // Adjust the priority if this result comes from a base class.
1410   if (InBaseClass)
1411     setInBaseClass(R);
1412 
1413   AdjustResultPriorityForDecl(R);
1414 
1415   if (HasObjectTypeQualifiers)
1416     if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1417       if (Method->isInstance()) {
1418         Qualifiers MethodQuals = Method->getMethodQualifiers();
1419         if (ObjectTypeQualifiers == MethodQuals)
1420           R.Priority += CCD_ObjectQualifierMatch;
1421         else if (ObjectTypeQualifiers - MethodQuals) {
1422           // The method cannot be invoked, because doing so would drop
1423           // qualifiers.
1424           return;
1425         }
1426         // Detect cases where a ref-qualified method cannot be invoked.
1427         switch (Method->getRefQualifier()) {
1428           case RQ_LValue:
1429             if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
1430               return;
1431             break;
1432           case RQ_RValue:
1433             if (ObjectKind == VK_LValue)
1434               return;
1435             break;
1436           case RQ_None:
1437             break;
1438         }
1439 
1440         /// Check whether this dominates another overloaded method, which should
1441         /// be suppressed (or vice versa).
1442         /// Motivating case is const_iterator begin() const vs iterator begin().
1443         auto &OverloadSet = OverloadMap[std::make_pair(
1444             CurContext, Method->getDeclName().getAsOpaqueInteger())];
1445         for (const DeclIndexPair Entry : OverloadSet) {
1446           Result &Incumbent = Results[Entry.second];
1447           switch (compareOverloads(*Method,
1448                                    *cast<CXXMethodDecl>(Incumbent.Declaration),
1449                                    ObjectTypeQualifiers, ObjectKind)) {
1450           case OverloadCompare::Dominates:
1451             // Replace the dominated overload with this one.
1452             // FIXME: if the overload dominates multiple incumbents then we
1453             // should remove all. But two overloads is by far the common case.
1454             Incumbent = std::move(R);
1455             return;
1456           case OverloadCompare::Dominated:
1457             // This overload can't be called, drop it.
1458             return;
1459           case OverloadCompare::BothViable:
1460             break;
1461           }
1462         }
1463         OverloadSet.Add(Method, Results.size());
1464       }
1465 
1466   R.FunctionCanBeCall = canFunctionBeCalled(R.getDeclaration(), BaseExprType);
1467 
1468   // Insert this result into the set of results.
1469   Results.push_back(R);
1470 
1471   if (!AsNestedNameSpecifier)
1472     MaybeAddConstructorResults(R);
1473 }
1474 
1475 void ResultBuilder::AddResult(Result R) {
1476   assert(R.Kind != Result::RK_Declaration &&
1477          "Declaration results need more context");
1478   Results.push_back(R);
1479 }
1480 
1481 /// Enter into a new scope.
1482 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1483 
1484 /// Exit from the current scope.
1485 void ResultBuilder::ExitScope() {
1486   ShadowMaps.pop_back();
1487 }
1488 
1489 /// Determines whether this given declaration will be found by
1490 /// ordinary name lookup.
1491 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1492   ND = ND->getUnderlyingDecl();
1493 
1494   // If name lookup finds a local extern declaration, then we are in a
1495   // context where it behaves like an ordinary name.
1496   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1497   if (SemaRef.getLangOpts().CPlusPlus)
1498     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1499   else if (SemaRef.getLangOpts().ObjC) {
1500     if (isa<ObjCIvarDecl>(ND))
1501       return true;
1502   }
1503 
1504   return ND->getIdentifierNamespace() & IDNS;
1505 }
1506 
1507 /// Determines whether this given declaration will be found by
1508 /// ordinary name lookup but is not a type name.
1509 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1510   ND = ND->getUnderlyingDecl();
1511   if (isa<TypeDecl>(ND))
1512     return false;
1513   // Objective-C interfaces names are not filtered by this method because they
1514   // can be used in a class property expression. We can still filter out
1515   // @class declarations though.
1516   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1517     if (!ID->getDefinition())
1518       return false;
1519   }
1520 
1521   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1522   if (SemaRef.getLangOpts().CPlusPlus)
1523     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1524   else if (SemaRef.getLangOpts().ObjC) {
1525     if (isa<ObjCIvarDecl>(ND))
1526       return true;
1527   }
1528 
1529   return ND->getIdentifierNamespace() & IDNS;
1530 }
1531 
1532 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1533   if (!IsOrdinaryNonTypeName(ND))
1534     return false;
1535 
1536   if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1537     if (VD->getType()->isIntegralOrEnumerationType())
1538       return true;
1539 
1540   return false;
1541 }
1542 
1543 /// Determines whether this given declaration will be found by
1544 /// ordinary name lookup.
1545 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1546   ND = ND->getUnderlyingDecl();
1547 
1548   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1549   if (SemaRef.getLangOpts().CPlusPlus)
1550     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1551 
1552   return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
1553          !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
1554 }
1555 
1556 /// Determines whether the given declaration is suitable as the
1557 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1558 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1559   // Allow us to find class templates, too.
1560   if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1561     ND = ClassTemplate->getTemplatedDecl();
1562 
1563   return SemaRef.isAcceptableNestedNameSpecifier(ND);
1564 }
1565 
1566 /// Determines whether the given declaration is an enumeration.
1567 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1568   return isa<EnumDecl>(ND);
1569 }
1570 
1571 /// Determines whether the given declaration is a class or struct.
1572 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1573   // Allow us to find class templates, too.
1574   if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1575     ND = ClassTemplate->getTemplatedDecl();
1576 
1577   // For purposes of this check, interfaces match too.
1578   if (const auto *RD = dyn_cast<RecordDecl>(ND))
1579     return RD->getTagKind() == TagTypeKind::Class ||
1580            RD->getTagKind() == TagTypeKind::Struct ||
1581            RD->getTagKind() == TagTypeKind::Interface;
1582 
1583   return false;
1584 }
1585 
1586 /// Determines whether the given declaration is a union.
1587 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1588   // Allow us to find class templates, too.
1589   if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1590     ND = ClassTemplate->getTemplatedDecl();
1591 
1592   if (const auto *RD = dyn_cast<RecordDecl>(ND))
1593     return RD->getTagKind() == TagTypeKind::Union;
1594 
1595   return false;
1596 }
1597 
1598 /// Determines whether the given declaration is a namespace.
1599 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1600   return isa<NamespaceDecl>(ND);
1601 }
1602 
1603 /// Determines whether the given declaration is a namespace or
1604 /// namespace alias.
1605 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1606   return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1607 }
1608 
1609 /// Determines whether the given declaration is a type.
1610 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1611   ND = ND->getUnderlyingDecl();
1612   return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1613 }
1614 
1615 /// Determines which members of a class should be visible via
1616 /// "." or "->".  Only value declarations, nested name specifiers, and
1617 /// using declarations thereof should show up.
1618 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1619   ND = ND->getUnderlyingDecl();
1620   return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1621          isa<ObjCPropertyDecl>(ND);
1622 }
1623 
1624 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1625   T = C.getCanonicalType(T);
1626   switch (T->getTypeClass()) {
1627   case Type::ObjCObject:
1628   case Type::ObjCInterface:
1629   case Type::ObjCObjectPointer:
1630     return true;
1631 
1632   case Type::Builtin:
1633     switch (cast<BuiltinType>(T)->getKind()) {
1634     case BuiltinType::ObjCId:
1635     case BuiltinType::ObjCClass:
1636     case BuiltinType::ObjCSel:
1637       return true;
1638 
1639     default:
1640       break;
1641     }
1642     return false;
1643 
1644   default:
1645     break;
1646   }
1647 
1648   if (!C.getLangOpts().CPlusPlus)
1649     return false;
1650 
1651   // FIXME: We could perform more analysis here to determine whether a
1652   // particular class type has any conversions to Objective-C types. For now,
1653   // just accept all class types.
1654   return T->isDependentType() || T->isRecordType();
1655 }
1656 
1657 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1658   QualType T = getDeclUsageType(SemaRef.Context, ND);
1659   if (T.isNull())
1660     return false;
1661 
1662   T = SemaRef.Context.getBaseElementType(T);
1663   return isObjCReceiverType(SemaRef.Context, T);
1664 }
1665 
1666 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1667     const NamedDecl *ND) const {
1668   if (IsObjCMessageReceiver(ND))
1669     return true;
1670 
1671   const auto *Var = dyn_cast<VarDecl>(ND);
1672   if (!Var)
1673     return false;
1674 
1675   return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1676 }
1677 
1678 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1679   if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1680       (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1681     return false;
1682 
1683   QualType T = getDeclUsageType(SemaRef.Context, ND);
1684   if (T.isNull())
1685     return false;
1686 
1687   T = SemaRef.Context.getBaseElementType(T);
1688   return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1689          T->isObjCIdType() ||
1690          (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1691 }
1692 
1693 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1694   return false;
1695 }
1696 
1697 /// Determines whether the given declaration is an Objective-C
1698 /// instance variable.
1699 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1700   return isa<ObjCIvarDecl>(ND);
1701 }
1702 
1703 namespace {
1704 
1705 /// Visible declaration consumer that adds a code-completion result
1706 /// for each visible declaration.
1707 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1708   ResultBuilder &Results;
1709   DeclContext *InitialLookupCtx;
1710   // NamingClass and BaseType are used for access-checking. See
1711   // Sema::IsSimplyAccessible for details.
1712   CXXRecordDecl *NamingClass;
1713   QualType BaseType;
1714   std::vector<FixItHint> FixIts;
1715 
1716 public:
1717   CodeCompletionDeclConsumer(
1718       ResultBuilder &Results, DeclContext *InitialLookupCtx,
1719       QualType BaseType = QualType(),
1720       std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1721       : Results(Results), InitialLookupCtx(InitialLookupCtx),
1722         FixIts(std::move(FixIts)) {
1723     NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1724     // If BaseType was not provided explicitly, emulate implicit 'this->'.
1725     if (BaseType.isNull()) {
1726       auto ThisType = Results.getSema().getCurrentThisType();
1727       if (!ThisType.isNull()) {
1728         assert(ThisType->isPointerType());
1729         BaseType = ThisType->getPointeeType();
1730         if (!NamingClass)
1731           NamingClass = BaseType->getAsCXXRecordDecl();
1732       }
1733     }
1734     this->BaseType = BaseType;
1735   }
1736 
1737   void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1738                  bool InBaseClass) override {
1739     ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1740                                  false, IsAccessible(ND, Ctx), FixIts);
1741     Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass, BaseType);
1742   }
1743 
1744   void EnteredContext(DeclContext *Ctx) override {
1745     Results.addVisitedContext(Ctx);
1746   }
1747 
1748 private:
1749   bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1750     // Naming class to use for access check. In most cases it was provided
1751     // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1752     // for unqualified lookup we fallback to the \p Ctx in which we found the
1753     // member.
1754     auto *NamingClass = this->NamingClass;
1755     QualType BaseType = this->BaseType;
1756     if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1757       if (!NamingClass)
1758         NamingClass = Cls;
1759       // When we emulate implicit 'this->' in an unqualified lookup, we might
1760       // end up with an invalid naming class. In that case, we avoid emulating
1761       // 'this->' qualifier to satisfy preconditions of the access checking.
1762       if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1763           !NamingClass->isDerivedFrom(Cls)) {
1764         NamingClass = Cls;
1765         BaseType = QualType();
1766       }
1767     } else {
1768       // The decl was found outside the C++ class, so only ObjC access checks
1769       // apply. Those do not rely on NamingClass and BaseType, so we clear them
1770       // out.
1771       NamingClass = nullptr;
1772       BaseType = QualType();
1773     }
1774     return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1775   }
1776 };
1777 } // namespace
1778 
1779 /// Add type specifiers for the current language as keyword results.
1780 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1781                                     ResultBuilder &Results) {
1782   typedef CodeCompletionResult Result;
1783   Results.AddResult(Result("short", CCP_Type));
1784   Results.AddResult(Result("long", CCP_Type));
1785   Results.AddResult(Result("signed", CCP_Type));
1786   Results.AddResult(Result("unsigned", CCP_Type));
1787   Results.AddResult(Result("void", CCP_Type));
1788   Results.AddResult(Result("char", CCP_Type));
1789   Results.AddResult(Result("int", CCP_Type));
1790   Results.AddResult(Result("float", CCP_Type));
1791   Results.AddResult(Result("double", CCP_Type));
1792   Results.AddResult(Result("enum", CCP_Type));
1793   Results.AddResult(Result("struct", CCP_Type));
1794   Results.AddResult(Result("union", CCP_Type));
1795   Results.AddResult(Result("const", CCP_Type));
1796   Results.AddResult(Result("volatile", CCP_Type));
1797 
1798   if (LangOpts.C99) {
1799     // C99-specific
1800     Results.AddResult(Result("_Complex", CCP_Type));
1801     Results.AddResult(Result("_Imaginary", CCP_Type));
1802     Results.AddResult(Result("_Bool", CCP_Type));
1803     Results.AddResult(Result("restrict", CCP_Type));
1804   }
1805 
1806   CodeCompletionBuilder Builder(Results.getAllocator(),
1807                                 Results.getCodeCompletionTUInfo());
1808   if (LangOpts.CPlusPlus) {
1809     // C++-specific
1810     Results.AddResult(
1811         Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
1812     Results.AddResult(Result("class", CCP_Type));
1813     Results.AddResult(Result("wchar_t", CCP_Type));
1814 
1815     // typename name
1816     Builder.AddTypedTextChunk("typename");
1817     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1818     Builder.AddPlaceholderChunk("name");
1819     Results.AddResult(Result(Builder.TakeString()));
1820 
1821     if (LangOpts.CPlusPlus11) {
1822       Results.AddResult(Result("auto", CCP_Type));
1823       Results.AddResult(Result("char16_t", CCP_Type));
1824       Results.AddResult(Result("char32_t", CCP_Type));
1825 
1826       Builder.AddTypedTextChunk("decltype");
1827       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1828       Builder.AddPlaceholderChunk("expression");
1829       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1830       Results.AddResult(Result(Builder.TakeString()));
1831     }
1832   } else
1833     Results.AddResult(Result("__auto_type", CCP_Type));
1834 
1835   // GNU keywords
1836   if (LangOpts.GNUKeywords) {
1837     // FIXME: Enable when we actually support decimal floating point.
1838     //    Results.AddResult(Result("_Decimal32"));
1839     //    Results.AddResult(Result("_Decimal64"));
1840     //    Results.AddResult(Result("_Decimal128"));
1841 
1842     Builder.AddTypedTextChunk("typeof");
1843     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1844     Builder.AddPlaceholderChunk("expression");
1845     Results.AddResult(Result(Builder.TakeString()));
1846 
1847     Builder.AddTypedTextChunk("typeof");
1848     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1849     Builder.AddPlaceholderChunk("type");
1850     Builder.AddChunk(CodeCompletionString::CK_RightParen);
1851     Results.AddResult(Result(Builder.TakeString()));
1852   }
1853 
1854   // Nullability
1855   Results.AddResult(Result("_Nonnull", CCP_Type));
1856   Results.AddResult(Result("_Null_unspecified", CCP_Type));
1857   Results.AddResult(Result("_Nullable", CCP_Type));
1858 }
1859 
1860 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1861                                  const LangOptions &LangOpts,
1862                                  ResultBuilder &Results) {
1863   typedef CodeCompletionResult Result;
1864   // Note: we don't suggest either "auto" or "register", because both
1865   // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1866   // in C++0x as a type specifier.
1867   Results.AddResult(Result("extern"));
1868   Results.AddResult(Result("static"));
1869 
1870   if (LangOpts.CPlusPlus11) {
1871     CodeCompletionAllocator &Allocator = Results.getAllocator();
1872     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1873 
1874     // alignas
1875     Builder.AddTypedTextChunk("alignas");
1876     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1877     Builder.AddPlaceholderChunk("expression");
1878     Builder.AddChunk(CodeCompletionString::CK_RightParen);
1879     Results.AddResult(Result(Builder.TakeString()));
1880 
1881     Results.AddResult(Result("constexpr"));
1882     Results.AddResult(Result("thread_local"));
1883   }
1884 }
1885 
1886 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1887                                   const LangOptions &LangOpts,
1888                                   ResultBuilder &Results) {
1889   typedef CodeCompletionResult Result;
1890   switch (CCC) {
1891   case Sema::PCC_Class:
1892   case Sema::PCC_MemberTemplate:
1893     if (LangOpts.CPlusPlus) {
1894       Results.AddResult(Result("explicit"));
1895       Results.AddResult(Result("friend"));
1896       Results.AddResult(Result("mutable"));
1897       Results.AddResult(Result("virtual"));
1898     }
1899     [[fallthrough]];
1900 
1901   case Sema::PCC_ObjCInterface:
1902   case Sema::PCC_ObjCImplementation:
1903   case Sema::PCC_Namespace:
1904   case Sema::PCC_Template:
1905     if (LangOpts.CPlusPlus || LangOpts.C99)
1906       Results.AddResult(Result("inline"));
1907     break;
1908 
1909   case Sema::PCC_ObjCInstanceVariableList:
1910   case Sema::PCC_Expression:
1911   case Sema::PCC_Statement:
1912   case Sema::PCC_TopLevelOrExpression:
1913   case Sema::PCC_ForInit:
1914   case Sema::PCC_Condition:
1915   case Sema::PCC_RecoveryInFunction:
1916   case Sema::PCC_Type:
1917   case Sema::PCC_ParenthesizedExpression:
1918   case Sema::PCC_LocalDeclarationSpecifiers:
1919     break;
1920   }
1921 }
1922 
1923 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1924 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1925 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1926                                      ResultBuilder &Results, bool NeedAt);
1927 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1928                                          ResultBuilder &Results, bool NeedAt);
1929 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1930                                     ResultBuilder &Results, bool NeedAt);
1931 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1932 
1933 static void AddTypedefResult(ResultBuilder &Results) {
1934   CodeCompletionBuilder Builder(Results.getAllocator(),
1935                                 Results.getCodeCompletionTUInfo());
1936   Builder.AddTypedTextChunk("typedef");
1937   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1938   Builder.AddPlaceholderChunk("type");
1939   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1940   Builder.AddPlaceholderChunk("name");
1941   Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1942   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1943 }
1944 
1945 // using name = type
1946 static void AddUsingAliasResult(CodeCompletionBuilder &Builder,
1947                                 ResultBuilder &Results) {
1948   Builder.AddTypedTextChunk("using");
1949   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1950   Builder.AddPlaceholderChunk("name");
1951   Builder.AddChunk(CodeCompletionString::CK_Equal);
1952   Builder.AddPlaceholderChunk("type");
1953   Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1954   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1955 }
1956 
1957 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1958                                const LangOptions &LangOpts) {
1959   switch (CCC) {
1960   case Sema::PCC_Namespace:
1961   case Sema::PCC_Class:
1962   case Sema::PCC_ObjCInstanceVariableList:
1963   case Sema::PCC_Template:
1964   case Sema::PCC_MemberTemplate:
1965   case Sema::PCC_Statement:
1966   case Sema::PCC_RecoveryInFunction:
1967   case Sema::PCC_Type:
1968   case Sema::PCC_ParenthesizedExpression:
1969   case Sema::PCC_LocalDeclarationSpecifiers:
1970   case Sema::PCC_TopLevelOrExpression:
1971     return true;
1972 
1973   case Sema::PCC_Expression:
1974   case Sema::PCC_Condition:
1975     return LangOpts.CPlusPlus;
1976 
1977   case Sema::PCC_ObjCInterface:
1978   case Sema::PCC_ObjCImplementation:
1979     return false;
1980 
1981   case Sema::PCC_ForInit:
1982     return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
1983   }
1984 
1985   llvm_unreachable("Invalid ParserCompletionContext!");
1986 }
1987 
1988 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1989                                                   const Preprocessor &PP) {
1990   PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1991   Policy.AnonymousTagLocations = false;
1992   Policy.SuppressStrongLifetime = true;
1993   Policy.SuppressUnwrittenScope = true;
1994   Policy.SuppressScope = true;
1995   Policy.CleanUglifiedParameters = true;
1996   return Policy;
1997 }
1998 
1999 /// Retrieve a printing policy suitable for code completion.
2000 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
2001   return getCompletionPrintingPolicy(S.Context, S.PP);
2002 }
2003 
2004 /// Retrieve the string representation of the given type as a string
2005 /// that has the appropriate lifetime for code completion.
2006 ///
2007 /// This routine provides a fast path where we provide constant strings for
2008 /// common type names.
2009 static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
2010                                            const PrintingPolicy &Policy,
2011                                            CodeCompletionAllocator &Allocator) {
2012   if (!T.getLocalQualifiers()) {
2013     // Built-in type names are constant strings.
2014     if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
2015       return BT->getNameAsCString(Policy);
2016 
2017     // Anonymous tag types are constant strings.
2018     if (const TagType *TagT = dyn_cast<TagType>(T))
2019       if (TagDecl *Tag = TagT->getDecl())
2020         if (!Tag->hasNameForLinkage()) {
2021           switch (Tag->getTagKind()) {
2022           case TagTypeKind::Struct:
2023             return "struct <anonymous>";
2024           case TagTypeKind::Interface:
2025             return "__interface <anonymous>";
2026           case TagTypeKind::Class:
2027             return "class <anonymous>";
2028           case TagTypeKind::Union:
2029             return "union <anonymous>";
2030           case TagTypeKind::Enum:
2031             return "enum <anonymous>";
2032           }
2033         }
2034   }
2035 
2036   // Slow path: format the type as a string.
2037   std::string Result;
2038   T.getAsStringInternal(Result, Policy);
2039   return Allocator.CopyString(Result);
2040 }
2041 
2042 /// Add a completion for "this", if we're in a member function.
2043 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
2044   QualType ThisTy = S.getCurrentThisType();
2045   if (ThisTy.isNull())
2046     return;
2047 
2048   CodeCompletionAllocator &Allocator = Results.getAllocator();
2049   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2050   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
2051   Builder.AddResultTypeChunk(
2052       GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
2053   Builder.AddTypedTextChunk("this");
2054   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2055 }
2056 
2057 static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
2058                                   ResultBuilder &Results,
2059                                   const LangOptions &LangOpts) {
2060   if (!LangOpts.CPlusPlus11)
2061     return;
2062 
2063   Builder.AddTypedTextChunk("static_assert");
2064   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2065   Builder.AddPlaceholderChunk("expression");
2066   Builder.AddChunk(CodeCompletionString::CK_Comma);
2067   Builder.AddPlaceholderChunk("message");
2068   Builder.AddChunk(CodeCompletionString::CK_RightParen);
2069   Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2070   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2071 }
2072 
2073 static void AddOverrideResults(ResultBuilder &Results,
2074                                const CodeCompletionContext &CCContext,
2075                                CodeCompletionBuilder &Builder) {
2076   Sema &S = Results.getSema();
2077   const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
2078   // If not inside a class/struct/union return empty.
2079   if (!CR)
2080     return;
2081   // First store overrides within current class.
2082   // These are stored by name to make querying fast in the later step.
2083   llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
2084   for (auto *Method : CR->methods()) {
2085     if (!Method->isVirtual() || !Method->getIdentifier())
2086       continue;
2087     Overrides[Method->getName()].push_back(Method);
2088   }
2089 
2090   for (const auto &Base : CR->bases()) {
2091     const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
2092     if (!BR)
2093       continue;
2094     for (auto *Method : BR->methods()) {
2095       if (!Method->isVirtual() || !Method->getIdentifier())
2096         continue;
2097       const auto it = Overrides.find(Method->getName());
2098       bool IsOverriden = false;
2099       if (it != Overrides.end()) {
2100         for (auto *MD : it->second) {
2101           // If the method in current body is not an overload of this virtual
2102           // function, then it overrides this one.
2103           if (!S.IsOverload(MD, Method, false)) {
2104             IsOverriden = true;
2105             break;
2106           }
2107         }
2108       }
2109       if (!IsOverriden) {
2110         // Generates a new CodeCompletionResult by taking this function and
2111         // converting it into an override declaration with only one chunk in the
2112         // final CodeCompletionString as a TypedTextChunk.
2113         std::string OverrideSignature;
2114         llvm::raw_string_ostream OS(OverrideSignature);
2115         CodeCompletionResult CCR(Method, 0);
2116         PrintingPolicy Policy =
2117             getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
2118         auto *CCS = CCR.createCodeCompletionStringForOverride(
2119             S.getPreprocessor(), S.getASTContext(), Builder,
2120             /*IncludeBriefComments=*/false, CCContext, Policy);
2121         Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
2122       }
2123     }
2124   }
2125 }
2126 
2127 /// Add language constructs that show up for "ordinary" names.
2128 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
2129                                    Sema &SemaRef, ResultBuilder &Results) {
2130   CodeCompletionAllocator &Allocator = Results.getAllocator();
2131   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2132 
2133   typedef CodeCompletionResult Result;
2134   switch (CCC) {
2135   case Sema::PCC_Namespace:
2136     if (SemaRef.getLangOpts().CPlusPlus) {
2137       if (Results.includeCodePatterns()) {
2138         // namespace <identifier> { declarations }
2139         Builder.AddTypedTextChunk("namespace");
2140         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2141         Builder.AddPlaceholderChunk("identifier");
2142         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2143         Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2144         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2145         Builder.AddPlaceholderChunk("declarations");
2146         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2147         Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2148         Results.AddResult(Result(Builder.TakeString()));
2149       }
2150 
2151       // namespace identifier = identifier ;
2152       Builder.AddTypedTextChunk("namespace");
2153       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2154       Builder.AddPlaceholderChunk("name");
2155       Builder.AddChunk(CodeCompletionString::CK_Equal);
2156       Builder.AddPlaceholderChunk("namespace");
2157       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2158       Results.AddResult(Result(Builder.TakeString()));
2159 
2160       // Using directives
2161       Builder.AddTypedTextChunk("using namespace");
2162       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2163       Builder.AddPlaceholderChunk("identifier");
2164       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2165       Results.AddResult(Result(Builder.TakeString()));
2166 
2167       // asm(string-literal)
2168       Builder.AddTypedTextChunk("asm");
2169       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2170       Builder.AddPlaceholderChunk("string-literal");
2171       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2172       Results.AddResult(Result(Builder.TakeString()));
2173 
2174       if (Results.includeCodePatterns()) {
2175         // Explicit template instantiation
2176         Builder.AddTypedTextChunk("template");
2177         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2178         Builder.AddPlaceholderChunk("declaration");
2179         Results.AddResult(Result(Builder.TakeString()));
2180       } else {
2181         Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2182       }
2183     }
2184 
2185     if (SemaRef.getLangOpts().ObjC)
2186       AddObjCTopLevelResults(Results, true);
2187 
2188     AddTypedefResult(Results);
2189     [[fallthrough]];
2190 
2191   case Sema::PCC_Class:
2192     if (SemaRef.getLangOpts().CPlusPlus) {
2193       // Using declaration
2194       Builder.AddTypedTextChunk("using");
2195       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2196       Builder.AddPlaceholderChunk("qualifier");
2197       Builder.AddTextChunk("::");
2198       Builder.AddPlaceholderChunk("name");
2199       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2200       Results.AddResult(Result(Builder.TakeString()));
2201 
2202       if (SemaRef.getLangOpts().CPlusPlus11)
2203         AddUsingAliasResult(Builder, Results);
2204 
2205       // using typename qualifier::name (only in a dependent context)
2206       if (SemaRef.CurContext->isDependentContext()) {
2207         Builder.AddTypedTextChunk("using typename");
2208         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2209         Builder.AddPlaceholderChunk("qualifier");
2210         Builder.AddTextChunk("::");
2211         Builder.AddPlaceholderChunk("name");
2212         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2213         Results.AddResult(Result(Builder.TakeString()));
2214       }
2215 
2216       AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2217 
2218       if (CCC == Sema::PCC_Class) {
2219         AddTypedefResult(Results);
2220 
2221         bool IsNotInheritanceScope = !S->isClassInheritanceScope();
2222         // public:
2223         Builder.AddTypedTextChunk("public");
2224         if (IsNotInheritanceScope && Results.includeCodePatterns())
2225           Builder.AddChunk(CodeCompletionString::CK_Colon);
2226         Results.AddResult(Result(Builder.TakeString()));
2227 
2228         // protected:
2229         Builder.AddTypedTextChunk("protected");
2230         if (IsNotInheritanceScope && Results.includeCodePatterns())
2231           Builder.AddChunk(CodeCompletionString::CK_Colon);
2232         Results.AddResult(Result(Builder.TakeString()));
2233 
2234         // private:
2235         Builder.AddTypedTextChunk("private");
2236         if (IsNotInheritanceScope && Results.includeCodePatterns())
2237           Builder.AddChunk(CodeCompletionString::CK_Colon);
2238         Results.AddResult(Result(Builder.TakeString()));
2239 
2240         // FIXME: This adds override results only if we are at the first word of
2241         // the declaration/definition. Also call this from other sides to have
2242         // more use-cases.
2243         AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
2244                            Builder);
2245       }
2246     }
2247     [[fallthrough]];
2248 
2249   case Sema::PCC_Template:
2250   case Sema::PCC_MemberTemplate:
2251     if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
2252       // template < parameters >
2253       Builder.AddTypedTextChunk("template");
2254       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2255       Builder.AddPlaceholderChunk("parameters");
2256       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2257       Results.AddResult(Result(Builder.TakeString()));
2258     } else {
2259       Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2260     }
2261 
2262     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2263     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2264     break;
2265 
2266   case Sema::PCC_ObjCInterface:
2267     AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2268     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2269     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2270     break;
2271 
2272   case Sema::PCC_ObjCImplementation:
2273     AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2274     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2275     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2276     break;
2277 
2278   case Sema::PCC_ObjCInstanceVariableList:
2279     AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2280     break;
2281 
2282   case Sema::PCC_RecoveryInFunction:
2283   case Sema::PCC_TopLevelOrExpression:
2284   case Sema::PCC_Statement: {
2285     if (SemaRef.getLangOpts().CPlusPlus11)
2286       AddUsingAliasResult(Builder, Results);
2287 
2288     AddTypedefResult(Results);
2289 
2290     if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
2291         SemaRef.getLangOpts().CXXExceptions) {
2292       Builder.AddTypedTextChunk("try");
2293       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2294       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2295       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2296       Builder.AddPlaceholderChunk("statements");
2297       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2298       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2299       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2300       Builder.AddTextChunk("catch");
2301       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2302       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2303       Builder.AddPlaceholderChunk("declaration");
2304       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2305       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2306       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2307       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2308       Builder.AddPlaceholderChunk("statements");
2309       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2310       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2311       Results.AddResult(Result(Builder.TakeString()));
2312     }
2313     if (SemaRef.getLangOpts().ObjC)
2314       AddObjCStatementResults(Results, true);
2315 
2316     if (Results.includeCodePatterns()) {
2317       // if (condition) { statements }
2318       Builder.AddTypedTextChunk("if");
2319       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2320       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2321       if (SemaRef.getLangOpts().CPlusPlus)
2322         Builder.AddPlaceholderChunk("condition");
2323       else
2324         Builder.AddPlaceholderChunk("expression");
2325       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2326       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2327       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2328       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2329       Builder.AddPlaceholderChunk("statements");
2330       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2331       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2332       Results.AddResult(Result(Builder.TakeString()));
2333 
2334       // switch (condition) { }
2335       Builder.AddTypedTextChunk("switch");
2336       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2337       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2338       if (SemaRef.getLangOpts().CPlusPlus)
2339         Builder.AddPlaceholderChunk("condition");
2340       else
2341         Builder.AddPlaceholderChunk("expression");
2342       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2343       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2344       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2345       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2346       Builder.AddPlaceholderChunk("cases");
2347       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2348       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2349       Results.AddResult(Result(Builder.TakeString()));
2350     }
2351 
2352     // Switch-specific statements.
2353     if (SemaRef.getCurFunction() &&
2354         !SemaRef.getCurFunction()->SwitchStack.empty()) {
2355       // case expression:
2356       Builder.AddTypedTextChunk("case");
2357       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2358       Builder.AddPlaceholderChunk("expression");
2359       Builder.AddChunk(CodeCompletionString::CK_Colon);
2360       Results.AddResult(Result(Builder.TakeString()));
2361 
2362       // default:
2363       Builder.AddTypedTextChunk("default");
2364       Builder.AddChunk(CodeCompletionString::CK_Colon);
2365       Results.AddResult(Result(Builder.TakeString()));
2366     }
2367 
2368     if (Results.includeCodePatterns()) {
2369       /// while (condition) { statements }
2370       Builder.AddTypedTextChunk("while");
2371       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2372       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2373       if (SemaRef.getLangOpts().CPlusPlus)
2374         Builder.AddPlaceholderChunk("condition");
2375       else
2376         Builder.AddPlaceholderChunk("expression");
2377       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2378       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2379       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2380       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2381       Builder.AddPlaceholderChunk("statements");
2382       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2383       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2384       Results.AddResult(Result(Builder.TakeString()));
2385 
2386       // do { statements } while ( expression );
2387       Builder.AddTypedTextChunk("do");
2388       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2389       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2390       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2391       Builder.AddPlaceholderChunk("statements");
2392       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2393       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2394       Builder.AddTextChunk("while");
2395       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2396       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2397       Builder.AddPlaceholderChunk("expression");
2398       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2399       Results.AddResult(Result(Builder.TakeString()));
2400 
2401       // for ( for-init-statement ; condition ; expression ) { statements }
2402       Builder.AddTypedTextChunk("for");
2403       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2404       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2405       if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
2406         Builder.AddPlaceholderChunk("init-statement");
2407       else
2408         Builder.AddPlaceholderChunk("init-expression");
2409       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2410       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2411       Builder.AddPlaceholderChunk("condition");
2412       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2413       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2414       Builder.AddPlaceholderChunk("inc-expression");
2415       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2416       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2417       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2418       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2419       Builder.AddPlaceholderChunk("statements");
2420       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2421       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2422       Results.AddResult(Result(Builder.TakeString()));
2423 
2424       if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
2425         // for ( range_declaration (:|in) range_expression ) { statements }
2426         Builder.AddTypedTextChunk("for");
2427         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2428         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2429         Builder.AddPlaceholderChunk("range-declaration");
2430         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2431         if (SemaRef.getLangOpts().ObjC)
2432           Builder.AddTextChunk("in");
2433         else
2434           Builder.AddChunk(CodeCompletionString::CK_Colon);
2435         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2436         Builder.AddPlaceholderChunk("range-expression");
2437         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2438         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2439         Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2440         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2441         Builder.AddPlaceholderChunk("statements");
2442         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2443         Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2444         Results.AddResult(Result(Builder.TakeString()));
2445       }
2446     }
2447 
2448     if (S->getContinueParent()) {
2449       // continue ;
2450       Builder.AddTypedTextChunk("continue");
2451       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2452       Results.AddResult(Result(Builder.TakeString()));
2453     }
2454 
2455     if (S->getBreakParent()) {
2456       // break ;
2457       Builder.AddTypedTextChunk("break");
2458       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2459       Results.AddResult(Result(Builder.TakeString()));
2460     }
2461 
2462     // "return expression ;" or "return ;", depending on the return type.
2463     QualType ReturnType;
2464     if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2465       ReturnType = Function->getReturnType();
2466     else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2467       ReturnType = Method->getReturnType();
2468     else if (SemaRef.getCurBlock() &&
2469              !SemaRef.getCurBlock()->ReturnType.isNull())
2470       ReturnType = SemaRef.getCurBlock()->ReturnType;;
2471     if (ReturnType.isNull() || ReturnType->isVoidType()) {
2472       Builder.AddTypedTextChunk("return");
2473       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2474       Results.AddResult(Result(Builder.TakeString()));
2475     } else {
2476       assert(!ReturnType.isNull());
2477       // "return expression ;"
2478       Builder.AddTypedTextChunk("return");
2479       Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
2480       Builder.AddPlaceholderChunk("expression");
2481       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2482       Results.AddResult(Result(Builder.TakeString()));
2483       // When boolean, also add 'return true;' and 'return false;'.
2484       if (ReturnType->isBooleanType()) {
2485         Builder.AddTypedTextChunk("return true");
2486         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2487         Results.AddResult(Result(Builder.TakeString()));
2488 
2489         Builder.AddTypedTextChunk("return false");
2490         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2491         Results.AddResult(Result(Builder.TakeString()));
2492       }
2493       // For pointers, suggest 'return nullptr' in C++.
2494       if (SemaRef.getLangOpts().CPlusPlus11 &&
2495           (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
2496         Builder.AddTypedTextChunk("return nullptr");
2497         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2498         Results.AddResult(Result(Builder.TakeString()));
2499       }
2500     }
2501 
2502     // goto identifier ;
2503     Builder.AddTypedTextChunk("goto");
2504     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2505     Builder.AddPlaceholderChunk("label");
2506     Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2507     Results.AddResult(Result(Builder.TakeString()));
2508 
2509     // Using directives
2510     Builder.AddTypedTextChunk("using namespace");
2511     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2512     Builder.AddPlaceholderChunk("identifier");
2513     Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2514     Results.AddResult(Result(Builder.TakeString()));
2515 
2516     AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2517   }
2518     [[fallthrough]];
2519 
2520   // Fall through (for statement expressions).
2521   case Sema::PCC_ForInit:
2522   case Sema::PCC_Condition:
2523     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2524     // Fall through: conditions and statements can have expressions.
2525     [[fallthrough]];
2526 
2527   case Sema::PCC_ParenthesizedExpression:
2528     if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2529         CCC == Sema::PCC_ParenthesizedExpression) {
2530       // (__bridge <type>)<expression>
2531       Builder.AddTypedTextChunk("__bridge");
2532       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2533       Builder.AddPlaceholderChunk("type");
2534       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2535       Builder.AddPlaceholderChunk("expression");
2536       Results.AddResult(Result(Builder.TakeString()));
2537 
2538       // (__bridge_transfer <Objective-C type>)<expression>
2539       Builder.AddTypedTextChunk("__bridge_transfer");
2540       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2541       Builder.AddPlaceholderChunk("Objective-C type");
2542       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2543       Builder.AddPlaceholderChunk("expression");
2544       Results.AddResult(Result(Builder.TakeString()));
2545 
2546       // (__bridge_retained <CF type>)<expression>
2547       Builder.AddTypedTextChunk("__bridge_retained");
2548       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2549       Builder.AddPlaceholderChunk("CF type");
2550       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2551       Builder.AddPlaceholderChunk("expression");
2552       Results.AddResult(Result(Builder.TakeString()));
2553     }
2554     // Fall through
2555     [[fallthrough]];
2556 
2557   case Sema::PCC_Expression: {
2558     if (SemaRef.getLangOpts().CPlusPlus) {
2559       // 'this', if we're in a non-static member function.
2560       addThisCompletion(SemaRef, Results);
2561 
2562       // true
2563       Builder.AddResultTypeChunk("bool");
2564       Builder.AddTypedTextChunk("true");
2565       Results.AddResult(Result(Builder.TakeString()));
2566 
2567       // false
2568       Builder.AddResultTypeChunk("bool");
2569       Builder.AddTypedTextChunk("false");
2570       Results.AddResult(Result(Builder.TakeString()));
2571 
2572       if (SemaRef.getLangOpts().RTTI) {
2573         // dynamic_cast < type-id > ( expression )
2574         Builder.AddTypedTextChunk("dynamic_cast");
2575         Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2576         Builder.AddPlaceholderChunk("type");
2577         Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2578         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2579         Builder.AddPlaceholderChunk("expression");
2580         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2581         Results.AddResult(Result(Builder.TakeString()));
2582       }
2583 
2584       // static_cast < type-id > ( expression )
2585       Builder.AddTypedTextChunk("static_cast");
2586       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2587       Builder.AddPlaceholderChunk("type");
2588       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2589       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2590       Builder.AddPlaceholderChunk("expression");
2591       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2592       Results.AddResult(Result(Builder.TakeString()));
2593 
2594       // reinterpret_cast < type-id > ( expression )
2595       Builder.AddTypedTextChunk("reinterpret_cast");
2596       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2597       Builder.AddPlaceholderChunk("type");
2598       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2599       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2600       Builder.AddPlaceholderChunk("expression");
2601       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2602       Results.AddResult(Result(Builder.TakeString()));
2603 
2604       // const_cast < type-id > ( expression )
2605       Builder.AddTypedTextChunk("const_cast");
2606       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2607       Builder.AddPlaceholderChunk("type");
2608       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2609       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2610       Builder.AddPlaceholderChunk("expression");
2611       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2612       Results.AddResult(Result(Builder.TakeString()));
2613 
2614       if (SemaRef.getLangOpts().RTTI) {
2615         // typeid ( expression-or-type )
2616         Builder.AddResultTypeChunk("std::type_info");
2617         Builder.AddTypedTextChunk("typeid");
2618         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2619         Builder.AddPlaceholderChunk("expression-or-type");
2620         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2621         Results.AddResult(Result(Builder.TakeString()));
2622       }
2623 
2624       // new T ( ... )
2625       Builder.AddTypedTextChunk("new");
2626       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2627       Builder.AddPlaceholderChunk("type");
2628       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2629       Builder.AddPlaceholderChunk("expressions");
2630       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2631       Results.AddResult(Result(Builder.TakeString()));
2632 
2633       // new T [ ] ( ... )
2634       Builder.AddTypedTextChunk("new");
2635       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2636       Builder.AddPlaceholderChunk("type");
2637       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2638       Builder.AddPlaceholderChunk("size");
2639       Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2640       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2641       Builder.AddPlaceholderChunk("expressions");
2642       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2643       Results.AddResult(Result(Builder.TakeString()));
2644 
2645       // delete expression
2646       Builder.AddResultTypeChunk("void");
2647       Builder.AddTypedTextChunk("delete");
2648       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2649       Builder.AddPlaceholderChunk("expression");
2650       Results.AddResult(Result(Builder.TakeString()));
2651 
2652       // delete [] expression
2653       Builder.AddResultTypeChunk("void");
2654       Builder.AddTypedTextChunk("delete");
2655       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2656       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2657       Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2658       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2659       Builder.AddPlaceholderChunk("expression");
2660       Results.AddResult(Result(Builder.TakeString()));
2661 
2662       if (SemaRef.getLangOpts().CXXExceptions) {
2663         // throw expression
2664         Builder.AddResultTypeChunk("void");
2665         Builder.AddTypedTextChunk("throw");
2666         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2667         Builder.AddPlaceholderChunk("expression");
2668         Results.AddResult(Result(Builder.TakeString()));
2669       }
2670 
2671       // FIXME: Rethrow?
2672 
2673       if (SemaRef.getLangOpts().CPlusPlus11) {
2674         // nullptr
2675         Builder.AddResultTypeChunk("std::nullptr_t");
2676         Builder.AddTypedTextChunk("nullptr");
2677         Results.AddResult(Result(Builder.TakeString()));
2678 
2679         // alignof
2680         Builder.AddResultTypeChunk("size_t");
2681         Builder.AddTypedTextChunk("alignof");
2682         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2683         Builder.AddPlaceholderChunk("type");
2684         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2685         Results.AddResult(Result(Builder.TakeString()));
2686 
2687         // noexcept
2688         Builder.AddResultTypeChunk("bool");
2689         Builder.AddTypedTextChunk("noexcept");
2690         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2691         Builder.AddPlaceholderChunk("expression");
2692         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2693         Results.AddResult(Result(Builder.TakeString()));
2694 
2695         // sizeof... expression
2696         Builder.AddResultTypeChunk("size_t");
2697         Builder.AddTypedTextChunk("sizeof...");
2698         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2699         Builder.AddPlaceholderChunk("parameter-pack");
2700         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2701         Results.AddResult(Result(Builder.TakeString()));
2702       }
2703     }
2704 
2705     if (SemaRef.getLangOpts().ObjC) {
2706       // Add "super", if we're in an Objective-C class with a superclass.
2707       if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2708         // The interface can be NULL.
2709         if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2710           if (ID->getSuperClass()) {
2711             std::string SuperType;
2712             SuperType = ID->getSuperClass()->getNameAsString();
2713             if (Method->isInstanceMethod())
2714               SuperType += " *";
2715 
2716             Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2717             Builder.AddTypedTextChunk("super");
2718             Results.AddResult(Result(Builder.TakeString()));
2719           }
2720       }
2721 
2722       AddObjCExpressionResults(Results, true);
2723     }
2724 
2725     if (SemaRef.getLangOpts().C11) {
2726       // _Alignof
2727       Builder.AddResultTypeChunk("size_t");
2728       if (SemaRef.PP.isMacroDefined("alignof"))
2729         Builder.AddTypedTextChunk("alignof");
2730       else
2731         Builder.AddTypedTextChunk("_Alignof");
2732       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2733       Builder.AddPlaceholderChunk("type");
2734       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2735       Results.AddResult(Result(Builder.TakeString()));
2736     }
2737 
2738     if (SemaRef.getLangOpts().C23) {
2739       // nullptr
2740       Builder.AddResultTypeChunk("nullptr_t");
2741       Builder.AddTypedTextChunk("nullptr");
2742       Results.AddResult(Result(Builder.TakeString()));
2743     }
2744 
2745     // sizeof expression
2746     Builder.AddResultTypeChunk("size_t");
2747     Builder.AddTypedTextChunk("sizeof");
2748     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2749     Builder.AddPlaceholderChunk("expression-or-type");
2750     Builder.AddChunk(CodeCompletionString::CK_RightParen);
2751     Results.AddResult(Result(Builder.TakeString()));
2752     break;
2753   }
2754 
2755   case Sema::PCC_Type:
2756   case Sema::PCC_LocalDeclarationSpecifiers:
2757     break;
2758   }
2759 
2760   if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2761     AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2762 
2763   if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2764     Results.AddResult(Result("operator"));
2765 }
2766 
2767 /// If the given declaration has an associated type, add it as a result
2768 /// type chunk.
2769 static void AddResultTypeChunk(ASTContext &Context,
2770                                const PrintingPolicy &Policy,
2771                                const NamedDecl *ND, QualType BaseType,
2772                                CodeCompletionBuilder &Result) {
2773   if (!ND)
2774     return;
2775 
2776   // Skip constructors and conversion functions, which have their return types
2777   // built into their names.
2778   if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
2779     return;
2780 
2781   // Determine the type of the declaration (if it has a type).
2782   QualType T;
2783   if (const FunctionDecl *Function = ND->getAsFunction())
2784     T = Function->getReturnType();
2785   else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2786     if (!BaseType.isNull())
2787       T = Method->getSendResultType(BaseType);
2788     else
2789       T = Method->getReturnType();
2790   } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2791     T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2792     T = clang::TypeName::getFullyQualifiedType(T, Context);
2793   } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2794     /* Do nothing: ignore unresolved using declarations*/
2795   } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2796     if (!BaseType.isNull())
2797       T = Ivar->getUsageType(BaseType);
2798     else
2799       T = Ivar->getType();
2800   } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2801     T = Value->getType();
2802   } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2803     if (!BaseType.isNull())
2804       T = Property->getUsageType(BaseType);
2805     else
2806       T = Property->getType();
2807   }
2808 
2809   if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2810     return;
2811 
2812   Result.AddResultTypeChunk(
2813       GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2814 }
2815 
2816 static void MaybeAddSentinel(Preprocessor &PP,
2817                              const NamedDecl *FunctionOrMethod,
2818                              CodeCompletionBuilder &Result) {
2819   if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2820     if (Sentinel->getSentinel() == 0) {
2821       if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
2822         Result.AddTextChunk(", nil");
2823       else if (PP.isMacroDefined("NULL"))
2824         Result.AddTextChunk(", NULL");
2825       else
2826         Result.AddTextChunk(", (void*)0");
2827     }
2828 }
2829 
2830 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2831                                              QualType &Type) {
2832   std::string Result;
2833   if (ObjCQuals & Decl::OBJC_TQ_In)
2834     Result += "in ";
2835   else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2836     Result += "inout ";
2837   else if (ObjCQuals & Decl::OBJC_TQ_Out)
2838     Result += "out ";
2839   if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2840     Result += "bycopy ";
2841   else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2842     Result += "byref ";
2843   if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2844     Result += "oneway ";
2845   if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2846     if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2847       switch (*nullability) {
2848       case NullabilityKind::NonNull:
2849         Result += "nonnull ";
2850         break;
2851 
2852       case NullabilityKind::Nullable:
2853         Result += "nullable ";
2854         break;
2855 
2856       case NullabilityKind::Unspecified:
2857         Result += "null_unspecified ";
2858         break;
2859 
2860       case NullabilityKind::NullableResult:
2861         llvm_unreachable("Not supported as a context-sensitive keyword!");
2862         break;
2863       }
2864     }
2865   }
2866   return Result;
2867 }
2868 
2869 /// Tries to find the most appropriate type location for an Objective-C
2870 /// block placeholder.
2871 ///
2872 /// This function ignores things like typedefs and qualifiers in order to
2873 /// present the most relevant and accurate block placeholders in code completion
2874 /// results.
2875 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2876                                          FunctionTypeLoc &Block,
2877                                          FunctionProtoTypeLoc &BlockProto,
2878                                          bool SuppressBlock = false) {
2879   if (!TSInfo)
2880     return;
2881   TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2882   while (true) {
2883     // Look through typedefs.
2884     if (!SuppressBlock) {
2885       if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
2886         if (TypeSourceInfo *InnerTSInfo =
2887                 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2888           TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2889           continue;
2890         }
2891       }
2892 
2893       // Look through qualified types
2894       if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2895         TL = QualifiedTL.getUnqualifiedLoc();
2896         continue;
2897       }
2898 
2899       if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2900         TL = AttrTL.getModifiedLoc();
2901         continue;
2902       }
2903     }
2904 
2905     // Try to get the function prototype behind the block pointer type,
2906     // then we're done.
2907     if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2908       TL = BlockPtr.getPointeeLoc().IgnoreParens();
2909       Block = TL.getAs<FunctionTypeLoc>();
2910       BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2911     }
2912     break;
2913   }
2914 }
2915 
2916 static std::string formatBlockPlaceholder(
2917     const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2918     FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2919     bool SuppressBlockName = false, bool SuppressBlock = false,
2920     std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt);
2921 
2922 static std::string FormatFunctionParameter(
2923     const PrintingPolicy &Policy, const DeclaratorDecl *Param,
2924     bool SuppressName = false, bool SuppressBlock = false,
2925     std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) {
2926   // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2927   // It would be better to pass in the param Type, which is usually available.
2928   // But this case is rare, so just pretend we fell back to int as elsewhere.
2929   if (!Param)
2930     return "int";
2931   Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None;
2932   if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
2933     ObjCQual = PVD->getObjCDeclQualifier();
2934   bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2935   if (Param->getType()->isDependentType() ||
2936       !Param->getType()->isBlockPointerType()) {
2937     // The argument for a dependent or non-block parameter is a placeholder
2938     // containing that parameter's type.
2939     std::string Result;
2940 
2941     if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2942       Result = std::string(Param->getIdentifier()->deuglifiedName());
2943 
2944     QualType Type = Param->getType();
2945     if (ObjCSubsts)
2946       Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2947                                     ObjCSubstitutionContext::Parameter);
2948     if (ObjCMethodParam) {
2949       Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
2950       Result += Type.getAsString(Policy) + ")";
2951       if (Param->getIdentifier() && !SuppressName)
2952         Result += Param->getIdentifier()->deuglifiedName();
2953     } else {
2954       Type.getAsStringInternal(Result, Policy);
2955     }
2956     return Result;
2957   }
2958 
2959   // The argument for a block pointer parameter is a block literal with
2960   // the appropriate type.
2961   FunctionTypeLoc Block;
2962   FunctionProtoTypeLoc BlockProto;
2963   findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2964                                SuppressBlock);
2965   // Try to retrieve the block type information from the property if this is a
2966   // parameter in a setter.
2967   if (!Block && ObjCMethodParam &&
2968       cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2969     if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2970                              ->findPropertyDecl(/*CheckOverrides=*/false))
2971       findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2972                                    SuppressBlock);
2973   }
2974 
2975   if (!Block) {
2976     // We were unable to find a FunctionProtoTypeLoc with parameter names
2977     // for the block; just use the parameter type as a placeholder.
2978     std::string Result;
2979     if (!ObjCMethodParam && Param->getIdentifier())
2980       Result = std::string(Param->getIdentifier()->deuglifiedName());
2981 
2982     QualType Type = Param->getType().getUnqualifiedType();
2983 
2984     if (ObjCMethodParam) {
2985       Result = Type.getAsString(Policy);
2986       std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
2987       if (!Quals.empty())
2988         Result = "(" + Quals + " " + Result + ")";
2989       if (Result.back() != ')')
2990         Result += " ";
2991       if (Param->getIdentifier())
2992         Result += Param->getIdentifier()->deuglifiedName();
2993     } else {
2994       Type.getAsStringInternal(Result, Policy);
2995     }
2996 
2997     return Result;
2998   }
2999 
3000   // We have the function prototype behind the block pointer type, as it was
3001   // written in the source.
3002   return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
3003                                 /*SuppressBlockName=*/false, SuppressBlock,
3004                                 ObjCSubsts);
3005 }
3006 
3007 /// Returns a placeholder string that corresponds to an Objective-C block
3008 /// declaration.
3009 ///
3010 /// \param BlockDecl A declaration with an Objective-C block type.
3011 ///
3012 /// \param Block The most relevant type location for that block type.
3013 ///
3014 /// \param SuppressBlockName Determines whether or not the name of the block
3015 /// declaration is included in the resulting string.
3016 static std::string
3017 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
3018                        FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
3019                        bool SuppressBlockName, bool SuppressBlock,
3020                        std::optional<ArrayRef<QualType>> ObjCSubsts) {
3021   std::string Result;
3022   QualType ResultType = Block.getTypePtr()->getReturnType();
3023   if (ObjCSubsts)
3024     ResultType =
3025         ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
3026                                      ObjCSubstitutionContext::Result);
3027   if (!ResultType->isVoidType() || SuppressBlock)
3028     ResultType.getAsStringInternal(Result, Policy);
3029 
3030   // Format the parameter list.
3031   std::string Params;
3032   if (!BlockProto || Block.getNumParams() == 0) {
3033     if (BlockProto && BlockProto.getTypePtr()->isVariadic())
3034       Params = "(...)";
3035     else
3036       Params = "(void)";
3037   } else {
3038     Params += "(";
3039     for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
3040       if (I)
3041         Params += ", ";
3042       Params += FormatFunctionParameter(Policy, Block.getParam(I),
3043                                         /*SuppressName=*/false,
3044                                         /*SuppressBlock=*/true, ObjCSubsts);
3045 
3046       if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
3047         Params += ", ...";
3048     }
3049     Params += ")";
3050   }
3051 
3052   if (SuppressBlock) {
3053     // Format as a parameter.
3054     Result = Result + " (^";
3055     if (!SuppressBlockName && BlockDecl->getIdentifier())
3056       Result += BlockDecl->getIdentifier()->getName();
3057     Result += ")";
3058     Result += Params;
3059   } else {
3060     // Format as a block literal argument.
3061     Result = '^' + Result;
3062     Result += Params;
3063 
3064     if (!SuppressBlockName && BlockDecl->getIdentifier())
3065       Result += BlockDecl->getIdentifier()->getName();
3066   }
3067 
3068   return Result;
3069 }
3070 
3071 static std::string GetDefaultValueString(const ParmVarDecl *Param,
3072                                          const SourceManager &SM,
3073                                          const LangOptions &LangOpts) {
3074   const SourceRange SrcRange = Param->getDefaultArgRange();
3075   CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
3076   bool Invalid = CharSrcRange.isInvalid();
3077   if (Invalid)
3078     return "";
3079   StringRef srcText =
3080       Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
3081   if (Invalid)
3082     return "";
3083 
3084   if (srcText.empty() || srcText == "=") {
3085     // Lexer can't determine the value.
3086     // This happens if the code is incorrect (for example class is forward
3087     // declared).
3088     return "";
3089   }
3090   std::string DefValue(srcText.str());
3091   // FIXME: remove this check if the Lexer::getSourceText value is fixed and
3092   // this value always has (or always does not have) '=' in front of it
3093   if (DefValue.at(0) != '=') {
3094     // If we don't have '=' in front of value.
3095     // Lexer returns built-in types values without '=' and user-defined types
3096     // values with it.
3097     return " = " + DefValue;
3098   }
3099   return " " + DefValue;
3100 }
3101 
3102 /// Add function parameter chunks to the given code completion string.
3103 static void AddFunctionParameterChunks(Preprocessor &PP,
3104                                        const PrintingPolicy &Policy,
3105                                        const FunctionDecl *Function,
3106                                        CodeCompletionBuilder &Result,
3107                                        unsigned Start = 0,
3108                                        bool InOptional = false) {
3109   bool FirstParameter = true;
3110 
3111   for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
3112     const ParmVarDecl *Param = Function->getParamDecl(P);
3113 
3114     if (Param->hasDefaultArg() && !InOptional) {
3115       // When we see an optional default argument, put that argument and
3116       // the remaining default arguments into a new, optional string.
3117       CodeCompletionBuilder Opt(Result.getAllocator(),
3118                                 Result.getCodeCompletionTUInfo());
3119       if (!FirstParameter)
3120         Opt.AddChunk(CodeCompletionString::CK_Comma);
3121       AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
3122       Result.AddOptionalChunk(Opt.TakeString());
3123       break;
3124     }
3125 
3126     if (FirstParameter)
3127       FirstParameter = false;
3128     else
3129       Result.AddChunk(CodeCompletionString::CK_Comma);
3130 
3131     InOptional = false;
3132 
3133     // Format the placeholder string.
3134     std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
3135     if (Param->hasDefaultArg())
3136       PlaceholderStr +=
3137           GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
3138 
3139     if (Function->isVariadic() && P == N - 1)
3140       PlaceholderStr += ", ...";
3141 
3142     // Add the placeholder string.
3143     Result.AddPlaceholderChunk(
3144         Result.getAllocator().CopyString(PlaceholderStr));
3145   }
3146 
3147   if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
3148     if (Proto->isVariadic()) {
3149       if (Proto->getNumParams() == 0)
3150         Result.AddPlaceholderChunk("...");
3151 
3152       MaybeAddSentinel(PP, Function, Result);
3153     }
3154 }
3155 
3156 /// Add template parameter chunks to the given code completion string.
3157 static void AddTemplateParameterChunks(
3158     ASTContext &Context, const PrintingPolicy &Policy,
3159     const TemplateDecl *Template, CodeCompletionBuilder &Result,
3160     unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
3161   bool FirstParameter = true;
3162 
3163   // Prefer to take the template parameter names from the first declaration of
3164   // the template.
3165   Template = cast<TemplateDecl>(Template->getCanonicalDecl());
3166 
3167   TemplateParameterList *Params = Template->getTemplateParameters();
3168   TemplateParameterList::iterator PEnd = Params->end();
3169   if (MaxParameters)
3170     PEnd = Params->begin() + MaxParameters;
3171   for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
3172        ++P) {
3173     bool HasDefaultArg = false;
3174     std::string PlaceholderStr;
3175     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
3176       if (TTP->wasDeclaredWithTypename())
3177         PlaceholderStr = "typename";
3178       else if (const auto *TC = TTP->getTypeConstraint()) {
3179         llvm::raw_string_ostream OS(PlaceholderStr);
3180         TC->print(OS, Policy);
3181         OS.flush();
3182       } else
3183         PlaceholderStr = "class";
3184 
3185       if (TTP->getIdentifier()) {
3186         PlaceholderStr += ' ';
3187         PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3188       }
3189 
3190       HasDefaultArg = TTP->hasDefaultArgument();
3191     } else if (NonTypeTemplateParmDecl *NTTP =
3192                    dyn_cast<NonTypeTemplateParmDecl>(*P)) {
3193       if (NTTP->getIdentifier())
3194         PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
3195       NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
3196       HasDefaultArg = NTTP->hasDefaultArgument();
3197     } else {
3198       assert(isa<TemplateTemplateParmDecl>(*P));
3199       TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
3200 
3201       // Since putting the template argument list into the placeholder would
3202       // be very, very long, we just use an abbreviation.
3203       PlaceholderStr = "template<...> class";
3204       if (TTP->getIdentifier()) {
3205         PlaceholderStr += ' ';
3206         PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3207       }
3208 
3209       HasDefaultArg = TTP->hasDefaultArgument();
3210     }
3211 
3212     if (HasDefaultArg && !InDefaultArg) {
3213       // When we see an optional default argument, put that argument and
3214       // the remaining default arguments into a new, optional string.
3215       CodeCompletionBuilder Opt(Result.getAllocator(),
3216                                 Result.getCodeCompletionTUInfo());
3217       if (!FirstParameter)
3218         Opt.AddChunk(CodeCompletionString::CK_Comma);
3219       AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
3220                                  P - Params->begin(), true);
3221       Result.AddOptionalChunk(Opt.TakeString());
3222       break;
3223     }
3224 
3225     InDefaultArg = false;
3226 
3227     if (FirstParameter)
3228       FirstParameter = false;
3229     else
3230       Result.AddChunk(CodeCompletionString::CK_Comma);
3231 
3232     // Add the placeholder string.
3233     Result.AddPlaceholderChunk(
3234         Result.getAllocator().CopyString(PlaceholderStr));
3235   }
3236 }
3237 
3238 /// Add a qualifier to the given code-completion string, if the
3239 /// provided nested-name-specifier is non-NULL.
3240 static void AddQualifierToCompletionString(CodeCompletionBuilder &Result,
3241                                            NestedNameSpecifier *Qualifier,
3242                                            bool QualifierIsInformative,
3243                                            ASTContext &Context,
3244                                            const PrintingPolicy &Policy) {
3245   if (!Qualifier)
3246     return;
3247 
3248   std::string PrintedNNS;
3249   {
3250     llvm::raw_string_ostream OS(PrintedNNS);
3251     Qualifier->print(OS, Policy);
3252   }
3253   if (QualifierIsInformative)
3254     Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
3255   else
3256     Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
3257 }
3258 
3259 static void
3260 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
3261                                        const FunctionDecl *Function) {
3262   const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
3263   if (!Proto || !Proto->getMethodQuals())
3264     return;
3265 
3266   // FIXME: Add ref-qualifier!
3267 
3268   // Handle single qualifiers without copying
3269   if (Proto->getMethodQuals().hasOnlyConst()) {
3270     Result.AddInformativeChunk(" const");
3271     return;
3272   }
3273 
3274   if (Proto->getMethodQuals().hasOnlyVolatile()) {
3275     Result.AddInformativeChunk(" volatile");
3276     return;
3277   }
3278 
3279   if (Proto->getMethodQuals().hasOnlyRestrict()) {
3280     Result.AddInformativeChunk(" restrict");
3281     return;
3282   }
3283 
3284   // Handle multiple qualifiers.
3285   std::string QualsStr;
3286   if (Proto->isConst())
3287     QualsStr += " const";
3288   if (Proto->isVolatile())
3289     QualsStr += " volatile";
3290   if (Proto->isRestrict())
3291     QualsStr += " restrict";
3292   Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
3293 }
3294 
3295 /// Add the name of the given declaration
3296 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
3297                               const NamedDecl *ND,
3298                               CodeCompletionBuilder &Result) {
3299   DeclarationName Name = ND->getDeclName();
3300   if (!Name)
3301     return;
3302 
3303   switch (Name.getNameKind()) {
3304   case DeclarationName::CXXOperatorName: {
3305     const char *OperatorName = nullptr;
3306     switch (Name.getCXXOverloadedOperator()) {
3307     case OO_None:
3308     case OO_Conditional:
3309     case NUM_OVERLOADED_OPERATORS:
3310       OperatorName = "operator";
3311       break;
3312 
3313 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
3314   case OO_##Name:                                                              \
3315     OperatorName = "operator" Spelling;                                        \
3316     break;
3317 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3318 #include "clang/Basic/OperatorKinds.def"
3319 
3320     case OO_New:
3321       OperatorName = "operator new";
3322       break;
3323     case OO_Delete:
3324       OperatorName = "operator delete";
3325       break;
3326     case OO_Array_New:
3327       OperatorName = "operator new[]";
3328       break;
3329     case OO_Array_Delete:
3330       OperatorName = "operator delete[]";
3331       break;
3332     case OO_Call:
3333       OperatorName = "operator()";
3334       break;
3335     case OO_Subscript:
3336       OperatorName = "operator[]";
3337       break;
3338     }
3339     Result.AddTypedTextChunk(OperatorName);
3340     break;
3341   }
3342 
3343   case DeclarationName::Identifier:
3344   case DeclarationName::CXXConversionFunctionName:
3345   case DeclarationName::CXXDestructorName:
3346   case DeclarationName::CXXLiteralOperatorName:
3347     Result.AddTypedTextChunk(
3348         Result.getAllocator().CopyString(ND->getNameAsString()));
3349     break;
3350 
3351   case DeclarationName::CXXDeductionGuideName:
3352   case DeclarationName::CXXUsingDirective:
3353   case DeclarationName::ObjCZeroArgSelector:
3354   case DeclarationName::ObjCOneArgSelector:
3355   case DeclarationName::ObjCMultiArgSelector:
3356     break;
3357 
3358   case DeclarationName::CXXConstructorName: {
3359     CXXRecordDecl *Record = nullptr;
3360     QualType Ty = Name.getCXXNameType();
3361     if (const auto *RecordTy = Ty->getAs<RecordType>())
3362       Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3363     else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3364       Record = InjectedTy->getDecl();
3365     else {
3366       Result.AddTypedTextChunk(
3367           Result.getAllocator().CopyString(ND->getNameAsString()));
3368       break;
3369     }
3370 
3371     Result.AddTypedTextChunk(
3372         Result.getAllocator().CopyString(Record->getNameAsString()));
3373     if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3374       Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3375       AddTemplateParameterChunks(Context, Policy, Template, Result);
3376       Result.AddChunk(CodeCompletionString::CK_RightAngle);
3377     }
3378     break;
3379   }
3380   }
3381 }
3382 
3383 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3384     Sema &S, const CodeCompletionContext &CCContext,
3385     CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3386     bool IncludeBriefComments) {
3387   return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3388                                     CCTUInfo, IncludeBriefComments);
3389 }
3390 
3391 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
3392     Preprocessor &PP, CodeCompletionAllocator &Allocator,
3393     CodeCompletionTUInfo &CCTUInfo) {
3394   assert(Kind == RK_Macro);
3395   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3396   const MacroInfo *MI = PP.getMacroInfo(Macro);
3397   Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3398 
3399   if (!MI || !MI->isFunctionLike())
3400     return Result.TakeString();
3401 
3402   // Format a function-like macro with placeholders for the arguments.
3403   Result.AddChunk(CodeCompletionString::CK_LeftParen);
3404   MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3405 
3406   // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3407   if (MI->isC99Varargs()) {
3408     --AEnd;
3409 
3410     if (A == AEnd) {
3411       Result.AddPlaceholderChunk("...");
3412     }
3413   }
3414 
3415   for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
3416     if (A != MI->param_begin())
3417       Result.AddChunk(CodeCompletionString::CK_Comma);
3418 
3419     if (MI->isVariadic() && (A + 1) == AEnd) {
3420       SmallString<32> Arg = (*A)->getName();
3421       if (MI->isC99Varargs())
3422         Arg += ", ...";
3423       else
3424         Arg += "...";
3425       Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3426       break;
3427     }
3428 
3429     // Non-variadic macros are simple.
3430     Result.AddPlaceholderChunk(
3431         Result.getAllocator().CopyString((*A)->getName()));
3432   }
3433   Result.AddChunk(CodeCompletionString::CK_RightParen);
3434   return Result.TakeString();
3435 }
3436 
3437 /// If possible, create a new code completion string for the given
3438 /// result.
3439 ///
3440 /// \returns Either a new, heap-allocated code completion string describing
3441 /// how to use this result, or NULL to indicate that the string or name of the
3442 /// result is all that is needed.
3443 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3444     ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3445     CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3446     bool IncludeBriefComments) {
3447   if (Kind == RK_Macro)
3448     return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3449 
3450   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3451 
3452   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
3453   if (Kind == RK_Pattern) {
3454     Pattern->Priority = Priority;
3455     Pattern->Availability = Availability;
3456 
3457     if (Declaration) {
3458       Result.addParentContext(Declaration->getDeclContext());
3459       Pattern->ParentName = Result.getParentName();
3460       if (const RawComment *RC =
3461               getPatternCompletionComment(Ctx, Declaration)) {
3462         Result.addBriefComment(RC->getBriefText(Ctx));
3463         Pattern->BriefComment = Result.getBriefComment();
3464       }
3465     }
3466 
3467     return Pattern;
3468   }
3469 
3470   if (Kind == RK_Keyword) {
3471     Result.AddTypedTextChunk(Keyword);
3472     return Result.TakeString();
3473   }
3474   assert(Kind == RK_Declaration && "Missed a result kind?");
3475   return createCodeCompletionStringForDecl(
3476       PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3477 }
3478 
3479 static void printOverrideString(const CodeCompletionString &CCS,
3480                                 std::string &BeforeName,
3481                                 std::string &NameAndSignature) {
3482   bool SeenTypedChunk = false;
3483   for (auto &Chunk : CCS) {
3484     if (Chunk.Kind == CodeCompletionString::CK_Optional) {
3485       assert(SeenTypedChunk && "optional parameter before name");
3486       // Note that we put all chunks inside into NameAndSignature.
3487       printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
3488       continue;
3489     }
3490     SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
3491     if (SeenTypedChunk)
3492       NameAndSignature += Chunk.Text;
3493     else
3494       BeforeName += Chunk.Text;
3495   }
3496 }
3497 
3498 CodeCompletionString *
3499 CodeCompletionResult::createCodeCompletionStringForOverride(
3500     Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3501     bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3502     PrintingPolicy &Policy) {
3503   auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3504                                                 /*IncludeBriefComments=*/false,
3505                                                 CCContext, Policy);
3506   std::string BeforeName;
3507   std::string NameAndSignature;
3508   // For overrides all chunks go into the result, none are informative.
3509   printOverrideString(*CCS, BeforeName, NameAndSignature);
3510   NameAndSignature += " override";
3511 
3512   Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
3513   Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3514   Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
3515   return Result.TakeString();
3516 }
3517 
3518 // FIXME: Right now this works well with lambdas. Add support for other functor
3519 // types like std::function.
3520 static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) {
3521   const auto *VD = dyn_cast<VarDecl>(ND);
3522   if (!VD)
3523     return nullptr;
3524   const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
3525   if (!RecordDecl || !RecordDecl->isLambda())
3526     return nullptr;
3527   return RecordDecl->getLambdaCallOperator();
3528 }
3529 
3530 CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
3531     Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3532     bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3533     PrintingPolicy &Policy) {
3534   const NamedDecl *ND = Declaration;
3535   Result.addParentContext(ND->getDeclContext());
3536 
3537   if (IncludeBriefComments) {
3538     // Add documentation comment, if it exists.
3539     if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3540       Result.addBriefComment(RC->getBriefText(Ctx));
3541     }
3542   }
3543 
3544   if (StartsNestedNameSpecifier) {
3545     Result.AddTypedTextChunk(
3546         Result.getAllocator().CopyString(ND->getNameAsString()));
3547     Result.AddTextChunk("::");
3548     return Result.TakeString();
3549   }
3550 
3551   for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3552     Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3553 
3554   auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
3555     AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
3556     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3557                                    Ctx, Policy);
3558     AddTypedNameChunk(Ctx, Policy, ND, Result);
3559     Result.AddChunk(CodeCompletionString::CK_LeftParen);
3560     AddFunctionParameterChunks(PP, Policy, Function, Result);
3561     Result.AddChunk(CodeCompletionString::CK_RightParen);
3562     AddFunctionTypeQualsToCompletionString(Result, Function);
3563   };
3564 
3565   if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3566     AddFunctionTypeAndResult(Function);
3567     return Result.TakeString();
3568   }
3569 
3570   if (const auto *CallOperator =
3571           dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
3572     AddFunctionTypeAndResult(CallOperator);
3573     return Result.TakeString();
3574   }
3575 
3576   AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3577 
3578   if (const FunctionTemplateDecl *FunTmpl =
3579           dyn_cast<FunctionTemplateDecl>(ND)) {
3580     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3581                                    Ctx, Policy);
3582     FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3583     AddTypedNameChunk(Ctx, Policy, Function, Result);
3584 
3585     // Figure out which template parameters are deduced (or have default
3586     // arguments).
3587     // Note that we're creating a non-empty bit vector so that we can go
3588     // through the loop below to omit default template parameters for non-call
3589     // cases.
3590     llvm::SmallBitVector Deduced(FunTmpl->getTemplateParameters()->size());
3591     // Avoid running it if this is not a call: We should emit *all* template
3592     // parameters.
3593     if (FunctionCanBeCall)
3594       Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3595     unsigned LastDeducibleArgument;
3596     for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3597          --LastDeducibleArgument) {
3598       if (!Deduced[LastDeducibleArgument - 1]) {
3599         // C++0x: Figure out if the template argument has a default. If so,
3600         // the user doesn't need to type this argument.
3601         // FIXME: We need to abstract template parameters better!
3602         bool HasDefaultArg = false;
3603         NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3604             LastDeducibleArgument - 1);
3605         if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3606           HasDefaultArg = TTP->hasDefaultArgument();
3607         else if (NonTypeTemplateParmDecl *NTTP =
3608                      dyn_cast<NonTypeTemplateParmDecl>(Param))
3609           HasDefaultArg = NTTP->hasDefaultArgument();
3610         else {
3611           assert(isa<TemplateTemplateParmDecl>(Param));
3612           HasDefaultArg =
3613               cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3614         }
3615 
3616         if (!HasDefaultArg)
3617           break;
3618       }
3619     }
3620 
3621     if (LastDeducibleArgument || !FunctionCanBeCall) {
3622       // Some of the function template arguments cannot be deduced from a
3623       // function call, so we introduce an explicit template argument list
3624       // containing all of the arguments up to the first deducible argument.
3625       //
3626       // Or, if this isn't a call, emit all the template arguments
3627       // to disambiguate the (potential) overloads.
3628       //
3629       // FIXME: Detect cases where the function parameters can be deduced from
3630       // the surrounding context, as per [temp.deduct.funcaddr].
3631       // e.g.,
3632       // template <class T> void foo(T);
3633       // void (*f)(int) = foo;
3634       Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3635       AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3636                                  LastDeducibleArgument);
3637       Result.AddChunk(CodeCompletionString::CK_RightAngle);
3638     }
3639 
3640     // Add the function parameters
3641     Result.AddChunk(CodeCompletionString::CK_LeftParen);
3642     AddFunctionParameterChunks(PP, Policy, Function, Result);
3643     Result.AddChunk(CodeCompletionString::CK_RightParen);
3644     AddFunctionTypeQualsToCompletionString(Result, Function);
3645     return Result.TakeString();
3646   }
3647 
3648   if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3649     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3650                                    Ctx, Policy);
3651     Result.AddTypedTextChunk(
3652         Result.getAllocator().CopyString(Template->getNameAsString()));
3653     Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3654     AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3655     Result.AddChunk(CodeCompletionString::CK_RightAngle);
3656     return Result.TakeString();
3657   }
3658 
3659   if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3660     Selector Sel = Method->getSelector();
3661     if (Sel.isUnarySelector()) {
3662       Result.AddTypedTextChunk(
3663           Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3664       return Result.TakeString();
3665     }
3666 
3667     std::string SelName = Sel.getNameForSlot(0).str();
3668     SelName += ':';
3669     if (StartParameter == 0)
3670       Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3671     else {
3672       Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3673 
3674       // If there is only one parameter, and we're past it, add an empty
3675       // typed-text chunk since there is nothing to type.
3676       if (Method->param_size() == 1)
3677         Result.AddTypedTextChunk("");
3678     }
3679     unsigned Idx = 0;
3680     // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3681     // method parameters.
3682     for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
3683                                               PEnd = Method->param_end();
3684          P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
3685       if (Idx > 0) {
3686         std::string Keyword;
3687         if (Idx > StartParameter)
3688           Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3689         if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3690           Keyword += II->getName();
3691         Keyword += ":";
3692         if (Idx < StartParameter || AllParametersAreInformative)
3693           Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3694         else
3695           Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3696       }
3697 
3698       // If we're before the starting parameter, skip the placeholder.
3699       if (Idx < StartParameter)
3700         continue;
3701 
3702       std::string Arg;
3703       QualType ParamType = (*P)->getType();
3704       std::optional<ArrayRef<QualType>> ObjCSubsts;
3705       if (!CCContext.getBaseType().isNull())
3706         ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3707 
3708       if (ParamType->isBlockPointerType() && !DeclaringEntity)
3709         Arg = FormatFunctionParameter(Policy, *P, true,
3710                                       /*SuppressBlock=*/false, ObjCSubsts);
3711       else {
3712         if (ObjCSubsts)
3713           ParamType = ParamType.substObjCTypeArgs(
3714               Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3715         Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3716                                               ParamType);
3717         Arg += ParamType.getAsString(Policy) + ")";
3718         if (IdentifierInfo *II = (*P)->getIdentifier())
3719           if (DeclaringEntity || AllParametersAreInformative)
3720             Arg += II->getName();
3721       }
3722 
3723       if (Method->isVariadic() && (P + 1) == PEnd)
3724         Arg += ", ...";
3725 
3726       if (DeclaringEntity)
3727         Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3728       else if (AllParametersAreInformative)
3729         Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3730       else
3731         Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3732     }
3733 
3734     if (Method->isVariadic()) {
3735       if (Method->param_size() == 0) {
3736         if (DeclaringEntity)
3737           Result.AddTextChunk(", ...");
3738         else if (AllParametersAreInformative)
3739           Result.AddInformativeChunk(", ...");
3740         else
3741           Result.AddPlaceholderChunk(", ...");
3742       }
3743 
3744       MaybeAddSentinel(PP, Method, Result);
3745     }
3746 
3747     return Result.TakeString();
3748   }
3749 
3750   if (Qualifier)
3751     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3752                                    Ctx, Policy);
3753 
3754   Result.AddTypedTextChunk(
3755       Result.getAllocator().CopyString(ND->getNameAsString()));
3756   return Result.TakeString();
3757 }
3758 
3759 const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
3760                                               const NamedDecl *ND) {
3761   if (!ND)
3762     return nullptr;
3763   if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3764     return RC;
3765 
3766   // Try to find comment from a property for ObjC methods.
3767   const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3768   if (!M)
3769     return nullptr;
3770   const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3771   if (!PDecl)
3772     return nullptr;
3773 
3774   return Ctx.getRawCommentForAnyRedecl(PDecl);
3775 }
3776 
3777 const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx,
3778                                                      const NamedDecl *ND) {
3779   const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3780   if (!M || !M->isPropertyAccessor())
3781     return nullptr;
3782 
3783   // Provide code completion comment for self.GetterName where
3784   // GetterName is the getter method for a property with name
3785   // different from the property name (declared via a property
3786   // getter attribute.
3787   const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3788   if (!PDecl)
3789     return nullptr;
3790   if (PDecl->getGetterName() == M->getSelector() &&
3791       PDecl->getIdentifier() != M->getIdentifier()) {
3792     if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3793       return RC;
3794     if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3795       return RC;
3796   }
3797   return nullptr;
3798 }
3799 
3800 const RawComment *clang::getParameterComment(
3801     const ASTContext &Ctx,
3802     const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3803   auto FDecl = Result.getFunction();
3804   if (!FDecl)
3805     return nullptr;
3806   if (ArgIndex < FDecl->getNumParams())
3807     return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3808   return nullptr;
3809 }
3810 
3811 static void AddOverloadAggregateChunks(const RecordDecl *RD,
3812                                        const PrintingPolicy &Policy,
3813                                        CodeCompletionBuilder &Result,
3814                                        unsigned CurrentArg) {
3815   unsigned ChunkIndex = 0;
3816   auto AddChunk = [&](llvm::StringRef Placeholder) {
3817     if (ChunkIndex > 0)
3818       Result.AddChunk(CodeCompletionString::CK_Comma);
3819     const char *Copy = Result.getAllocator().CopyString(Placeholder);
3820     if (ChunkIndex == CurrentArg)
3821       Result.AddCurrentParameterChunk(Copy);
3822     else
3823       Result.AddPlaceholderChunk(Copy);
3824     ++ChunkIndex;
3825   };
3826   // Aggregate initialization has all bases followed by all fields.
3827   // (Bases are not legal in C++11 but in that case we never get here).
3828   if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
3829     for (const auto &Base : CRD->bases())
3830       AddChunk(Base.getType().getAsString(Policy));
3831   }
3832   for (const auto &Field : RD->fields())
3833     AddChunk(FormatFunctionParameter(Policy, Field));
3834 }
3835 
3836 /// Add function overload parameter chunks to the given code completion
3837 /// string.
3838 static void AddOverloadParameterChunks(
3839     ASTContext &Context, const PrintingPolicy &Policy,
3840     const FunctionDecl *Function, const FunctionProtoType *Prototype,
3841     FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result,
3842     unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) {
3843   if (!Function && !Prototype) {
3844     Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3845     return;
3846   }
3847 
3848   bool FirstParameter = true;
3849   unsigned NumParams =
3850       Function ? Function->getNumParams() : Prototype->getNumParams();
3851 
3852   for (unsigned P = Start; P != NumParams; ++P) {
3853     if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3854       // When we see an optional default argument, put that argument and
3855       // the remaining default arguments into a new, optional string.
3856       CodeCompletionBuilder Opt(Result.getAllocator(),
3857                                 Result.getCodeCompletionTUInfo());
3858       if (!FirstParameter)
3859         Opt.AddChunk(CodeCompletionString::CK_Comma);
3860       // Optional sections are nested.
3861       AddOverloadParameterChunks(Context, Policy, Function, Prototype,
3862                                  PrototypeLoc, Opt, CurrentArg, P,
3863                                  /*InOptional=*/true);
3864       Result.AddOptionalChunk(Opt.TakeString());
3865       return;
3866     }
3867 
3868     if (FirstParameter)
3869       FirstParameter = false;
3870     else
3871       Result.AddChunk(CodeCompletionString::CK_Comma);
3872 
3873     InOptional = false;
3874 
3875     // Format the placeholder string.
3876     std::string Placeholder;
3877     assert(P < Prototype->getNumParams());
3878     if (Function || PrototypeLoc) {
3879       const ParmVarDecl *Param =
3880           Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P);
3881       Placeholder = FormatFunctionParameter(Policy, Param);
3882       if (Param->hasDefaultArg())
3883         Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3884                                              Context.getLangOpts());
3885     } else {
3886       Placeholder = Prototype->getParamType(P).getAsString(Policy);
3887     }
3888 
3889     if (P == CurrentArg)
3890       Result.AddCurrentParameterChunk(
3891           Result.getAllocator().CopyString(Placeholder));
3892     else
3893       Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3894   }
3895 
3896   if (Prototype && Prototype->isVariadic()) {
3897     CodeCompletionBuilder Opt(Result.getAllocator(),
3898                               Result.getCodeCompletionTUInfo());
3899     if (!FirstParameter)
3900       Opt.AddChunk(CodeCompletionString::CK_Comma);
3901 
3902     if (CurrentArg < NumParams)
3903       Opt.AddPlaceholderChunk("...");
3904     else
3905       Opt.AddCurrentParameterChunk("...");
3906 
3907     Result.AddOptionalChunk(Opt.TakeString());
3908   }
3909 }
3910 
3911 static std::string
3912 formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
3913                                    const PrintingPolicy &Policy) {
3914   if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
3915     Optional = Type->hasDefaultArgument();
3916   } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3917     Optional = NonType->hasDefaultArgument();
3918   } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3919     Optional = Template->hasDefaultArgument();
3920   }
3921   std::string Result;
3922   llvm::raw_string_ostream OS(Result);
3923   Param->print(OS, Policy);
3924   return Result;
3925 }
3926 
3927 static std::string templateResultType(const TemplateDecl *TD,
3928                                       const PrintingPolicy &Policy) {
3929   if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
3930     return CTD->getTemplatedDecl()->getKindName().str();
3931   if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
3932     return VTD->getTemplatedDecl()->getType().getAsString(Policy);
3933   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
3934     return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
3935   if (isa<TypeAliasTemplateDecl>(TD))
3936     return "type";
3937   if (isa<TemplateTemplateParmDecl>(TD))
3938     return "class";
3939   if (isa<ConceptDecl>(TD))
3940     return "concept";
3941   return "";
3942 }
3943 
3944 static CodeCompletionString *createTemplateSignatureString(
3945     const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
3946     const PrintingPolicy &Policy) {
3947   llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray();
3948   CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
3949                                         Builder.getCodeCompletionTUInfo());
3950   std::string ResultType = templateResultType(TD, Policy);
3951   if (!ResultType.empty())
3952     Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
3953   Builder.AddTextChunk(
3954       Builder.getAllocator().CopyString(TD->getNameAsString()));
3955   Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
3956   // Initially we're writing into the main string. Once we see an optional arg
3957   // (with default), we're writing into the nested optional chunk.
3958   CodeCompletionBuilder *Current = &Builder;
3959   for (unsigned I = 0; I < Params.size(); ++I) {
3960     bool Optional = false;
3961     std::string Placeholder =
3962         formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
3963     if (Optional)
3964       Current = &OptionalBuilder;
3965     if (I > 0)
3966       Current->AddChunk(CodeCompletionString::CK_Comma);
3967     Current->AddChunk(I == CurrentArg
3968                           ? CodeCompletionString::CK_CurrentParameter
3969                           : CodeCompletionString::CK_Placeholder,
3970                       Current->getAllocator().CopyString(Placeholder));
3971   }
3972   // Add the optional chunk to the main string if we ever used it.
3973   if (Current == &OptionalBuilder)
3974     Builder.AddOptionalChunk(OptionalBuilder.TakeString());
3975   Builder.AddChunk(CodeCompletionString::CK_RightAngle);
3976   // For function templates, ResultType was the function's return type.
3977   // Give some clue this is a function. (Don't show the possibly-bulky params).
3978   if (isa<FunctionTemplateDecl>(TD))
3979     Builder.AddInformativeChunk("()");
3980   return Builder.TakeString();
3981 }
3982 
3983 CodeCompletionString *
3984 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3985     unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3986     CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
3987     bool Braced) const {
3988   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3989   // Show signatures of constructors as they are declared:
3990   //   vector(int n) rather than vector<string>(int n)
3991   // This is less noisy without being less clear, and avoids tricky cases.
3992   Policy.SuppressTemplateArgsInCXXConstructors = true;
3993 
3994   // FIXME: Set priority, availability appropriately.
3995   CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
3996                                CXAvailability_Available);
3997 
3998   if (getKind() == CK_Template)
3999     return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
4000                                          Policy);
4001 
4002   FunctionDecl *FDecl = getFunction();
4003   const FunctionProtoType *Proto =
4004       dyn_cast_or_null<FunctionProtoType>(getFunctionType());
4005 
4006   // First, the name/type of the callee.
4007   if (getKind() == CK_Aggregate) {
4008     Result.AddTextChunk(
4009         Result.getAllocator().CopyString(getAggregate()->getName()));
4010   } else if (FDecl) {
4011     if (IncludeBriefComments) {
4012       if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
4013         Result.addBriefComment(RC->getBriefText(S.getASTContext()));
4014     }
4015     AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
4016 
4017     std::string Name;
4018     llvm::raw_string_ostream OS(Name);
4019     FDecl->getDeclName().print(OS, Policy);
4020     Result.AddTextChunk(Result.getAllocator().CopyString(OS.str()));
4021   } else {
4022     // Function without a declaration. Just give the return type.
4023     Result.AddResultTypeChunk(Result.getAllocator().CopyString(
4024         getFunctionType()->getReturnType().getAsString(Policy)));
4025   }
4026 
4027   // Next, the brackets and parameters.
4028   Result.AddChunk(Braced ? CodeCompletionString::CK_LeftBrace
4029                          : CodeCompletionString::CK_LeftParen);
4030   if (getKind() == CK_Aggregate)
4031     AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
4032   else
4033     AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto,
4034                                getFunctionProtoTypeLoc(), Result, CurrentArg);
4035   Result.AddChunk(Braced ? CodeCompletionString::CK_RightBrace
4036                          : CodeCompletionString::CK_RightParen);
4037 
4038   return Result.TakeString();
4039 }
4040 
4041 unsigned clang::getMacroUsagePriority(StringRef MacroName,
4042                                       const LangOptions &LangOpts,
4043                                       bool PreferredTypeIsPointer) {
4044   unsigned Priority = CCP_Macro;
4045 
4046   // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
4047   if (MacroName.equals("nil") || MacroName.equals("NULL") ||
4048       MacroName.equals("Nil")) {
4049     Priority = CCP_Constant;
4050     if (PreferredTypeIsPointer)
4051       Priority = Priority / CCF_SimilarTypeMatch;
4052   }
4053   // Treat "YES", "NO", "true", and "false" as constants.
4054   else if (MacroName.equals("YES") || MacroName.equals("NO") ||
4055            MacroName.equals("true") || MacroName.equals("false"))
4056     Priority = CCP_Constant;
4057   // Treat "bool" as a type.
4058   else if (MacroName.equals("bool"))
4059     Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
4060 
4061   return Priority;
4062 }
4063 
4064 CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
4065   if (!D)
4066     return CXCursor_UnexposedDecl;
4067 
4068   switch (D->getKind()) {
4069   case Decl::Enum:
4070     return CXCursor_EnumDecl;
4071   case Decl::EnumConstant:
4072     return CXCursor_EnumConstantDecl;
4073   case Decl::Field:
4074     return CXCursor_FieldDecl;
4075   case Decl::Function:
4076     return CXCursor_FunctionDecl;
4077   case Decl::ObjCCategory:
4078     return CXCursor_ObjCCategoryDecl;
4079   case Decl::ObjCCategoryImpl:
4080     return CXCursor_ObjCCategoryImplDecl;
4081   case Decl::ObjCImplementation:
4082     return CXCursor_ObjCImplementationDecl;
4083 
4084   case Decl::ObjCInterface:
4085     return CXCursor_ObjCInterfaceDecl;
4086   case Decl::ObjCIvar:
4087     return CXCursor_ObjCIvarDecl;
4088   case Decl::ObjCMethod:
4089     return cast<ObjCMethodDecl>(D)->isInstanceMethod()
4090                ? CXCursor_ObjCInstanceMethodDecl
4091                : CXCursor_ObjCClassMethodDecl;
4092   case Decl::CXXMethod:
4093     return CXCursor_CXXMethod;
4094   case Decl::CXXConstructor:
4095     return CXCursor_Constructor;
4096   case Decl::CXXDestructor:
4097     return CXCursor_Destructor;
4098   case Decl::CXXConversion:
4099     return CXCursor_ConversionFunction;
4100   case Decl::ObjCProperty:
4101     return CXCursor_ObjCPropertyDecl;
4102   case Decl::ObjCProtocol:
4103     return CXCursor_ObjCProtocolDecl;
4104   case Decl::ParmVar:
4105     return CXCursor_ParmDecl;
4106   case Decl::Typedef:
4107     return CXCursor_TypedefDecl;
4108   case Decl::TypeAlias:
4109     return CXCursor_TypeAliasDecl;
4110   case Decl::TypeAliasTemplate:
4111     return CXCursor_TypeAliasTemplateDecl;
4112   case Decl::Var:
4113     return CXCursor_VarDecl;
4114   case Decl::Namespace:
4115     return CXCursor_Namespace;
4116   case Decl::NamespaceAlias:
4117     return CXCursor_NamespaceAlias;
4118   case Decl::TemplateTypeParm:
4119     return CXCursor_TemplateTypeParameter;
4120   case Decl::NonTypeTemplateParm:
4121     return CXCursor_NonTypeTemplateParameter;
4122   case Decl::TemplateTemplateParm:
4123     return CXCursor_TemplateTemplateParameter;
4124   case Decl::FunctionTemplate:
4125     return CXCursor_FunctionTemplate;
4126   case Decl::ClassTemplate:
4127     return CXCursor_ClassTemplate;
4128   case Decl::AccessSpec:
4129     return CXCursor_CXXAccessSpecifier;
4130   case Decl::ClassTemplatePartialSpecialization:
4131     return CXCursor_ClassTemplatePartialSpecialization;
4132   case Decl::UsingDirective:
4133     return CXCursor_UsingDirective;
4134   case Decl::StaticAssert:
4135     return CXCursor_StaticAssert;
4136   case Decl::Friend:
4137     return CXCursor_FriendDecl;
4138   case Decl::TranslationUnit:
4139     return CXCursor_TranslationUnit;
4140 
4141   case Decl::Using:
4142   case Decl::UnresolvedUsingValue:
4143   case Decl::UnresolvedUsingTypename:
4144     return CXCursor_UsingDeclaration;
4145 
4146   case Decl::UsingEnum:
4147     return CXCursor_EnumDecl;
4148 
4149   case Decl::ObjCPropertyImpl:
4150     switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
4151     case ObjCPropertyImplDecl::Dynamic:
4152       return CXCursor_ObjCDynamicDecl;
4153 
4154     case ObjCPropertyImplDecl::Synthesize:
4155       return CXCursor_ObjCSynthesizeDecl;
4156     }
4157     llvm_unreachable("Unexpected Kind!");
4158 
4159   case Decl::Import:
4160     return CXCursor_ModuleImportDecl;
4161 
4162   case Decl::ObjCTypeParam:
4163     return CXCursor_TemplateTypeParameter;
4164 
4165   case Decl::Concept:
4166     return CXCursor_ConceptDecl;
4167 
4168   case Decl::LinkageSpec:
4169     return CXCursor_LinkageSpec;
4170 
4171   default:
4172     if (const auto *TD = dyn_cast<TagDecl>(D)) {
4173       switch (TD->getTagKind()) {
4174       case TagTypeKind::Interface: // fall through
4175       case TagTypeKind::Struct:
4176         return CXCursor_StructDecl;
4177       case TagTypeKind::Class:
4178         return CXCursor_ClassDecl;
4179       case TagTypeKind::Union:
4180         return CXCursor_UnionDecl;
4181       case TagTypeKind::Enum:
4182         return CXCursor_EnumDecl;
4183       }
4184     }
4185   }
4186 
4187   return CXCursor_UnexposedDecl;
4188 }
4189 
4190 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
4191                             bool LoadExternal, bool IncludeUndefined,
4192                             bool TargetTypeIsPointer = false) {
4193   typedef CodeCompletionResult Result;
4194 
4195   Results.EnterNewScope();
4196 
4197   for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
4198                                     MEnd = PP.macro_end(LoadExternal);
4199        M != MEnd; ++M) {
4200     auto MD = PP.getMacroDefinition(M->first);
4201     if (IncludeUndefined || MD) {
4202       MacroInfo *MI = MD.getMacroInfo();
4203       if (MI && MI->isUsedForHeaderGuard())
4204         continue;
4205 
4206       Results.AddResult(
4207           Result(M->first, MI,
4208                  getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
4209                                        TargetTypeIsPointer)));
4210     }
4211   }
4212 
4213   Results.ExitScope();
4214 }
4215 
4216 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
4217                                      ResultBuilder &Results) {
4218   typedef CodeCompletionResult Result;
4219 
4220   Results.EnterNewScope();
4221 
4222   Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
4223   Results.AddResult(Result("__FUNCTION__", CCP_Constant));
4224   if (LangOpts.C99 || LangOpts.CPlusPlus11)
4225     Results.AddResult(Result("__func__", CCP_Constant));
4226   Results.ExitScope();
4227 }
4228 
4229 static void HandleCodeCompleteResults(Sema *S,
4230                                       CodeCompleteConsumer *CodeCompleter,
4231                                       const CodeCompletionContext &Context,
4232                                       CodeCompletionResult *Results,
4233                                       unsigned NumResults) {
4234   if (CodeCompleter)
4235     CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
4236 }
4237 
4238 static CodeCompletionContext
4239 mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) {
4240   switch (PCC) {
4241   case Sema::PCC_Namespace:
4242     return CodeCompletionContext::CCC_TopLevel;
4243 
4244   case Sema::PCC_Class:
4245     return CodeCompletionContext::CCC_ClassStructUnion;
4246 
4247   case Sema::PCC_ObjCInterface:
4248     return CodeCompletionContext::CCC_ObjCInterface;
4249 
4250   case Sema::PCC_ObjCImplementation:
4251     return CodeCompletionContext::CCC_ObjCImplementation;
4252 
4253   case Sema::PCC_ObjCInstanceVariableList:
4254     return CodeCompletionContext::CCC_ObjCIvarList;
4255 
4256   case Sema::PCC_Template:
4257   case Sema::PCC_MemberTemplate:
4258     if (S.CurContext->isFileContext())
4259       return CodeCompletionContext::CCC_TopLevel;
4260     if (S.CurContext->isRecord())
4261       return CodeCompletionContext::CCC_ClassStructUnion;
4262     return CodeCompletionContext::CCC_Other;
4263 
4264   case Sema::PCC_RecoveryInFunction:
4265     return CodeCompletionContext::CCC_Recovery;
4266 
4267   case Sema::PCC_ForInit:
4268     if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
4269         S.getLangOpts().ObjC)
4270       return CodeCompletionContext::CCC_ParenthesizedExpression;
4271     else
4272       return CodeCompletionContext::CCC_Expression;
4273 
4274   case Sema::PCC_Expression:
4275     return CodeCompletionContext::CCC_Expression;
4276   case Sema::PCC_Condition:
4277     return CodeCompletionContext(CodeCompletionContext::CCC_Expression,
4278                                  S.getASTContext().BoolTy);
4279 
4280   case Sema::PCC_Statement:
4281     return CodeCompletionContext::CCC_Statement;
4282 
4283   case Sema::PCC_Type:
4284     return CodeCompletionContext::CCC_Type;
4285 
4286   case Sema::PCC_ParenthesizedExpression:
4287     return CodeCompletionContext::CCC_ParenthesizedExpression;
4288 
4289   case Sema::PCC_LocalDeclarationSpecifiers:
4290     return CodeCompletionContext::CCC_Type;
4291   case Sema::PCC_TopLevelOrExpression:
4292     return CodeCompletionContext::CCC_TopLevelOrExpression;
4293   }
4294 
4295   llvm_unreachable("Invalid ParserCompletionContext!");
4296 }
4297 
4298 /// If we're in a C++ virtual member function, add completion results
4299 /// that invoke the functions we override, since it's common to invoke the
4300 /// overridden function as well as adding new functionality.
4301 ///
4302 /// \param S The semantic analysis object for which we are generating results.
4303 ///
4304 /// \param InContext This context in which the nested-name-specifier preceding
4305 /// the code-completion point
4306 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
4307                                   ResultBuilder &Results) {
4308   // Look through blocks.
4309   DeclContext *CurContext = S.CurContext;
4310   while (isa<BlockDecl>(CurContext))
4311     CurContext = CurContext->getParent();
4312 
4313   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
4314   if (!Method || !Method->isVirtual())
4315     return;
4316 
4317   // We need to have names for all of the parameters, if we're going to
4318   // generate a forwarding call.
4319   for (auto *P : Method->parameters())
4320     if (!P->getDeclName())
4321       return;
4322 
4323   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
4324   for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
4325     CodeCompletionBuilder Builder(Results.getAllocator(),
4326                                   Results.getCodeCompletionTUInfo());
4327     if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
4328       continue;
4329 
4330     // If we need a nested-name-specifier, add one now.
4331     if (!InContext) {
4332       NestedNameSpecifier *NNS = getRequiredQualification(
4333           S.Context, CurContext, Overridden->getDeclContext());
4334       if (NNS) {
4335         std::string Str;
4336         llvm::raw_string_ostream OS(Str);
4337         NNS->print(OS, Policy);
4338         Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
4339       }
4340     } else if (!InContext->Equals(Overridden->getDeclContext()))
4341       continue;
4342 
4343     Builder.AddTypedTextChunk(
4344         Results.getAllocator().CopyString(Overridden->getNameAsString()));
4345     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4346     bool FirstParam = true;
4347     for (auto *P : Method->parameters()) {
4348       if (FirstParam)
4349         FirstParam = false;
4350       else
4351         Builder.AddChunk(CodeCompletionString::CK_Comma);
4352 
4353       Builder.AddPlaceholderChunk(
4354           Results.getAllocator().CopyString(P->getIdentifier()->getName()));
4355     }
4356     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4357     Results.AddResult(CodeCompletionResult(
4358         Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
4359         CXAvailability_Available, Overridden));
4360     Results.Ignore(Overridden);
4361   }
4362 }
4363 
4364 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
4365                                     ModuleIdPath Path) {
4366   typedef CodeCompletionResult Result;
4367   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4368                         CodeCompleter->getCodeCompletionTUInfo(),
4369                         CodeCompletionContext::CCC_Other);
4370   Results.EnterNewScope();
4371 
4372   CodeCompletionAllocator &Allocator = Results.getAllocator();
4373   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
4374   typedef CodeCompletionResult Result;
4375   if (Path.empty()) {
4376     // Enumerate all top-level modules.
4377     SmallVector<Module *, 8> Modules;
4378     PP.getHeaderSearchInfo().collectAllModules(Modules);
4379     for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
4380       Builder.AddTypedTextChunk(
4381           Builder.getAllocator().CopyString(Modules[I]->Name));
4382       Results.AddResult(Result(
4383           Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4384           Modules[I]->isAvailable() ? CXAvailability_Available
4385                                     : CXAvailability_NotAvailable));
4386     }
4387   } else if (getLangOpts().Modules) {
4388     // Load the named module.
4389     Module *Mod =
4390         PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
4391                                         /*IsInclusionDirective=*/false);
4392     // Enumerate submodules.
4393     if (Mod) {
4394       for (auto *Submodule : Mod->submodules()) {
4395         Builder.AddTypedTextChunk(
4396             Builder.getAllocator().CopyString(Submodule->Name));
4397         Results.AddResult(Result(
4398             Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4399             Submodule->isAvailable() ? CXAvailability_Available
4400                                      : CXAvailability_NotAvailable));
4401       }
4402     }
4403   }
4404   Results.ExitScope();
4405   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4406                             Results.data(), Results.size());
4407 }
4408 
4409 void Sema::CodeCompleteOrdinaryName(Scope *S,
4410                                     ParserCompletionContext CompletionContext) {
4411   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4412                         CodeCompleter->getCodeCompletionTUInfo(),
4413                         mapCodeCompletionContext(*this, CompletionContext));
4414   Results.EnterNewScope();
4415 
4416   // Determine how to filter results, e.g., so that the names of
4417   // values (functions, enumerators, function templates, etc.) are
4418   // only allowed where we can have an expression.
4419   switch (CompletionContext) {
4420   case PCC_Namespace:
4421   case PCC_Class:
4422   case PCC_ObjCInterface:
4423   case PCC_ObjCImplementation:
4424   case PCC_ObjCInstanceVariableList:
4425   case PCC_Template:
4426   case PCC_MemberTemplate:
4427   case PCC_Type:
4428   case PCC_LocalDeclarationSpecifiers:
4429     Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4430     break;
4431 
4432   case PCC_Statement:
4433   case PCC_TopLevelOrExpression:
4434   case PCC_ParenthesizedExpression:
4435   case PCC_Expression:
4436   case PCC_ForInit:
4437   case PCC_Condition:
4438     if (WantTypesInContext(CompletionContext, getLangOpts()))
4439       Results.setFilter(&ResultBuilder::IsOrdinaryName);
4440     else
4441       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4442 
4443     if (getLangOpts().CPlusPlus)
4444       MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
4445     break;
4446 
4447   case PCC_RecoveryInFunction:
4448     // Unfiltered
4449     break;
4450   }
4451 
4452   // If we are in a C++ non-static member function, check the qualifiers on
4453   // the member function to filter/prioritize the results list.
4454   auto ThisType = getCurrentThisType();
4455   if (!ThisType.isNull())
4456     Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
4457                                     VK_LValue);
4458 
4459   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4460   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4461                      CodeCompleter->includeGlobals(),
4462                      CodeCompleter->loadExternal());
4463 
4464   AddOrdinaryNameResults(CompletionContext, S, *this, Results);
4465   Results.ExitScope();
4466 
4467   switch (CompletionContext) {
4468   case PCC_ParenthesizedExpression:
4469   case PCC_Expression:
4470   case PCC_Statement:
4471   case PCC_TopLevelOrExpression:
4472   case PCC_RecoveryInFunction:
4473     if (S->getFnParent())
4474       AddPrettyFunctionResults(getLangOpts(), Results);
4475     break;
4476 
4477   case PCC_Namespace:
4478   case PCC_Class:
4479   case PCC_ObjCInterface:
4480   case PCC_ObjCImplementation:
4481   case PCC_ObjCInstanceVariableList:
4482   case PCC_Template:
4483   case PCC_MemberTemplate:
4484   case PCC_ForInit:
4485   case PCC_Condition:
4486   case PCC_Type:
4487   case PCC_LocalDeclarationSpecifiers:
4488     break;
4489   }
4490 
4491   if (CodeCompleter->includeMacros())
4492     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
4493 
4494   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4495                             Results.data(), Results.size());
4496 }
4497 
4498 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4499                                        ParsedType Receiver,
4500                                        ArrayRef<IdentifierInfo *> SelIdents,
4501                                        bool AtArgumentExpression, bool IsSuper,
4502                                        ResultBuilder &Results);
4503 
4504 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
4505                                 bool AllowNonIdentifiers,
4506                                 bool AllowNestedNameSpecifiers) {
4507   typedef CodeCompletionResult Result;
4508   ResultBuilder Results(
4509       *this, CodeCompleter->getAllocator(),
4510       CodeCompleter->getCodeCompletionTUInfo(),
4511       AllowNestedNameSpecifiers
4512           // FIXME: Try to separate codepath leading here to deduce whether we
4513           // need an existing symbol or a new one.
4514           ? CodeCompletionContext::CCC_SymbolOrNewName
4515           : CodeCompletionContext::CCC_NewName);
4516   Results.EnterNewScope();
4517 
4518   // Type qualifiers can come after names.
4519   Results.AddResult(Result("const"));
4520   Results.AddResult(Result("volatile"));
4521   if (getLangOpts().C99)
4522     Results.AddResult(Result("restrict"));
4523 
4524   if (getLangOpts().CPlusPlus) {
4525     if (getLangOpts().CPlusPlus11 &&
4526         (DS.getTypeSpecType() == DeclSpec::TST_class ||
4527          DS.getTypeSpecType() == DeclSpec::TST_struct))
4528       Results.AddResult("final");
4529 
4530     if (AllowNonIdentifiers) {
4531       Results.AddResult(Result("operator"));
4532     }
4533 
4534     // Add nested-name-specifiers.
4535     if (AllowNestedNameSpecifiers) {
4536       Results.allowNestedNameSpecifiers();
4537       Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4538       CodeCompletionDeclConsumer Consumer(Results, CurContext);
4539       LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4540                          CodeCompleter->includeGlobals(),
4541                          CodeCompleter->loadExternal());
4542       Results.setFilter(nullptr);
4543     }
4544   }
4545   Results.ExitScope();
4546 
4547   // If we're in a context where we might have an expression (rather than a
4548   // declaration), and what we've seen so far is an Objective-C type that could
4549   // be a receiver of a class message, this may be a class message send with
4550   // the initial opening bracket '[' missing. Add appropriate completions.
4551   if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
4552       DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
4553       DS.getTypeSpecType() == DeclSpec::TST_typename &&
4554       DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
4555       DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
4556       !DS.isTypeAltiVecVector() && S &&
4557       (S->getFlags() & Scope::DeclScope) != 0 &&
4558       (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
4559                         Scope::FunctionPrototypeScope | Scope::AtCatchScope)) ==
4560           0) {
4561     ParsedType T = DS.getRepAsType();
4562     if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4563       AddClassMessageCompletions(*this, S, T, std::nullopt, false, false,
4564                                  Results);
4565   }
4566 
4567   // Note that we intentionally suppress macro results here, since we do not
4568   // encourage using macros to produce the names of entities.
4569 
4570   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4571                             Results.data(), Results.size());
4572 }
4573 
4574 static const char *underscoreAttrScope(llvm::StringRef Scope) {
4575   if (Scope == "clang")
4576     return "_Clang";
4577   if (Scope == "gnu")
4578     return "__gnu__";
4579   return nullptr;
4580 }
4581 
4582 static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
4583   if (Scope == "_Clang")
4584     return "clang";
4585   if (Scope == "__gnu__")
4586     return "gnu";
4587   return nullptr;
4588 }
4589 
4590 void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax,
4591                                  AttributeCompletion Completion,
4592                                  const IdentifierInfo *InScope) {
4593   if (Completion == AttributeCompletion::None)
4594     return;
4595   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4596                         CodeCompleter->getCodeCompletionTUInfo(),
4597                         CodeCompletionContext::CCC_Attribute);
4598 
4599   // We're going to iterate over the normalized spellings of the attribute.
4600   // These don't include "underscore guarding": the normalized spelling is
4601   // clang::foo but you can also write _Clang::__foo__.
4602   //
4603   // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4604   // you care about clashing with macros or you don't).
4605   //
4606   // So if we're already in a scope, we determine its canonical spellings
4607   // (for comparison with normalized attr spelling) and remember whether it was
4608   // underscore-guarded (so we know how to spell contained attributes).
4609   llvm::StringRef InScopeName;
4610   bool InScopeUnderscore = false;
4611   if (InScope) {
4612     InScopeName = InScope->getName();
4613     if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
4614       InScopeName = NoUnderscore;
4615       InScopeUnderscore = true;
4616     }
4617   }
4618   bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
4619                               Syntax == AttributeCommonInfo::AS_CXX11 ||
4620                               Syntax == AttributeCommonInfo::AS_C23;
4621 
4622   llvm::DenseSet<llvm::StringRef> FoundScopes;
4623   auto AddCompletions = [&](const ParsedAttrInfo &A) {
4624     if (A.IsTargetSpecific && !A.existsInTarget(Context.getTargetInfo()))
4625       return;
4626     if (!A.acceptsLangOpts(getLangOpts()))
4627       return;
4628     for (const auto &S : A.Spellings) {
4629       if (S.Syntax != Syntax)
4630         continue;
4631       llvm::StringRef Name = S.NormalizedFullName;
4632       llvm::StringRef Scope;
4633       if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
4634            Syntax == AttributeCommonInfo::AS_C23)) {
4635         std::tie(Scope, Name) = Name.split("::");
4636         if (Name.empty()) // oops, unscoped
4637           std::swap(Name, Scope);
4638       }
4639 
4640       // Do we just want a list of scopes rather than attributes?
4641       if (Completion == AttributeCompletion::Scope) {
4642         // Make sure to emit each scope only once.
4643         if (!Scope.empty() && FoundScopes.insert(Scope).second) {
4644           Results.AddResult(
4645               CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
4646           // Include alternate form (__gnu__ instead of gnu).
4647           if (const char *Scope2 = underscoreAttrScope(Scope))
4648             Results.AddResult(CodeCompletionResult(Scope2));
4649         }
4650         continue;
4651       }
4652 
4653       // If a scope was specified, it must match but we don't need to print it.
4654       if (!InScopeName.empty()) {
4655         if (Scope != InScopeName)
4656           continue;
4657         Scope = "";
4658       }
4659 
4660       auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
4661                      bool Underscores) {
4662         CodeCompletionBuilder Builder(Results.getAllocator(),
4663                                       Results.getCodeCompletionTUInfo());
4664         llvm::SmallString<32> Text;
4665         if (!Scope.empty()) {
4666           Text.append(Scope);
4667           Text.append("::");
4668         }
4669         if (Underscores)
4670           Text.append("__");
4671         Text.append(Name);
4672         if (Underscores)
4673           Text.append("__");
4674         Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
4675 
4676         if (!A.ArgNames.empty()) {
4677           Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
4678           bool First = true;
4679           for (const char *Arg : A.ArgNames) {
4680             if (!First)
4681               Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
4682             First = false;
4683             Builder.AddPlaceholderChunk(Arg);
4684           }
4685           Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
4686         }
4687 
4688         Results.AddResult(Builder.TakeString());
4689       };
4690 
4691       // Generate the non-underscore-guarded result.
4692       // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4693       // If an underscore-guarded scope was specified, only the
4694       // underscore-guarded attribute name is relevant.
4695       if (!InScopeUnderscore)
4696         Add(Scope, Name, /*Underscores=*/false);
4697 
4698       // Generate the underscore-guarded version, for syntaxes that support it.
4699       // We skip this if the scope was already spelled and not guarded, or
4700       // we must spell it and can't guard it.
4701       if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
4702         llvm::SmallString<32> Guarded;
4703         if (Scope.empty()) {
4704           Add(Scope, Name, /*Underscores=*/true);
4705         } else {
4706           const char *GuardedScope = underscoreAttrScope(Scope);
4707           if (!GuardedScope)
4708             continue;
4709           Add(GuardedScope, Name, /*Underscores=*/true);
4710         }
4711       }
4712 
4713       // It may be nice to include the Kind so we can look up the docs later.
4714     }
4715   };
4716 
4717   for (const auto *A : ParsedAttrInfo::getAllBuiltin())
4718     AddCompletions(*A);
4719   for (const auto &Entry : ParsedAttrInfoRegistry::entries())
4720     AddCompletions(*Entry.instantiate());
4721 
4722   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4723                             Results.data(), Results.size());
4724 }
4725 
4726 struct Sema::CodeCompleteExpressionData {
4727   CodeCompleteExpressionData(QualType PreferredType = QualType(),
4728                              bool IsParenthesized = false)
4729       : PreferredType(PreferredType), IntegralConstantExpression(false),
4730         ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4731 
4732   QualType PreferredType;
4733   bool IntegralConstantExpression;
4734   bool ObjCCollection;
4735   bool IsParenthesized;
4736   SmallVector<Decl *, 4> IgnoreDecls;
4737 };
4738 
4739 namespace {
4740 /// Information that allows to avoid completing redundant enumerators.
4741 struct CoveredEnumerators {
4742   llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen;
4743   NestedNameSpecifier *SuggestedQualifier = nullptr;
4744 };
4745 } // namespace
4746 
4747 static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
4748                            EnumDecl *Enum, DeclContext *CurContext,
4749                            const CoveredEnumerators &Enumerators) {
4750   NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
4751   if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
4752     // If there are no prior enumerators in C++, check whether we have to
4753     // qualify the names of the enumerators that we suggest, because they
4754     // may not be visible in this scope.
4755     Qualifier = getRequiredQualification(Context, CurContext, Enum);
4756   }
4757 
4758   Results.EnterNewScope();
4759   for (auto *E : Enum->enumerators()) {
4760     if (Enumerators.Seen.count(E))
4761       continue;
4762 
4763     CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4764     Results.AddResult(R, CurContext, nullptr, false);
4765   }
4766   Results.ExitScope();
4767 }
4768 
4769 /// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4770 /// function pointers, std::function, etc).
4771 static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) {
4772   assert(!T.isNull());
4773   // Try to extract first template argument from std::function<> and similar.
4774   // Note we only handle the sugared types, they closely match what users wrote.
4775   // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4776   if (auto *Specialization = T->getAs<TemplateSpecializationType>()) {
4777     if (Specialization->template_arguments().size() != 1)
4778       return nullptr;
4779     const TemplateArgument &Argument = Specialization->template_arguments()[0];
4780     if (Argument.getKind() != TemplateArgument::Type)
4781       return nullptr;
4782     return Argument.getAsType()->getAs<FunctionProtoType>();
4783   }
4784   // Handle other cases.
4785   if (T->isPointerType())
4786     T = T->getPointeeType();
4787   return T->getAs<FunctionProtoType>();
4788 }
4789 
4790 /// Adds a pattern completion for a lambda expression with the specified
4791 /// parameter types and placeholders for parameter names.
4792 static void AddLambdaCompletion(ResultBuilder &Results,
4793                                 llvm::ArrayRef<QualType> Parameters,
4794                                 const LangOptions &LangOpts) {
4795   if (!Results.includeCodePatterns())
4796     return;
4797   CodeCompletionBuilder Completion(Results.getAllocator(),
4798                                    Results.getCodeCompletionTUInfo());
4799   // [](<parameters>) {}
4800   Completion.AddChunk(CodeCompletionString::CK_LeftBracket);
4801   Completion.AddPlaceholderChunk("=");
4802   Completion.AddChunk(CodeCompletionString::CK_RightBracket);
4803   if (!Parameters.empty()) {
4804     Completion.AddChunk(CodeCompletionString::CK_LeftParen);
4805     bool First = true;
4806     for (auto Parameter : Parameters) {
4807       if (!First)
4808         Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma);
4809       else
4810         First = false;
4811 
4812       constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
4813       std::string Type = std::string(NamePlaceholder);
4814       Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
4815       llvm::StringRef Prefix, Suffix;
4816       std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
4817       Prefix = Prefix.rtrim();
4818       Suffix = Suffix.ltrim();
4819 
4820       Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
4821       Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4822       Completion.AddPlaceholderChunk("parameter");
4823       Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
4824     };
4825     Completion.AddChunk(CodeCompletionString::CK_RightParen);
4826   }
4827   Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
4828   Completion.AddChunk(CodeCompletionString::CK_LeftBrace);
4829   Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4830   Completion.AddPlaceholderChunk("body");
4831   Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4832   Completion.AddChunk(CodeCompletionString::CK_RightBrace);
4833 
4834   Results.AddResult(Completion.TakeString());
4835 }
4836 
4837 /// Perform code-completion in an expression context when we know what
4838 /// type we're looking for.
4839 void Sema::CodeCompleteExpression(Scope *S,
4840                                   const CodeCompleteExpressionData &Data) {
4841   ResultBuilder Results(
4842       *this, CodeCompleter->getAllocator(),
4843       CodeCompleter->getCodeCompletionTUInfo(),
4844       CodeCompletionContext(
4845           Data.IsParenthesized
4846               ? CodeCompletionContext::CCC_ParenthesizedExpression
4847               : CodeCompletionContext::CCC_Expression,
4848           Data.PreferredType));
4849   auto PCC =
4850       Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
4851   if (Data.ObjCCollection)
4852     Results.setFilter(&ResultBuilder::IsObjCCollection);
4853   else if (Data.IntegralConstantExpression)
4854     Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4855   else if (WantTypesInContext(PCC, getLangOpts()))
4856     Results.setFilter(&ResultBuilder::IsOrdinaryName);
4857   else
4858     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4859 
4860   if (!Data.PreferredType.isNull())
4861     Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4862 
4863   // Ignore any declarations that we were told that we don't care about.
4864   for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
4865     Results.Ignore(Data.IgnoreDecls[I]);
4866 
4867   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4868   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4869                      CodeCompleter->includeGlobals(),
4870                      CodeCompleter->loadExternal());
4871 
4872   Results.EnterNewScope();
4873   AddOrdinaryNameResults(PCC, S, *this, Results);
4874   Results.ExitScope();
4875 
4876   bool PreferredTypeIsPointer = false;
4877   if (!Data.PreferredType.isNull()) {
4878     PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
4879                              Data.PreferredType->isMemberPointerType() ||
4880                              Data.PreferredType->isBlockPointerType();
4881     if (Data.PreferredType->isEnumeralType()) {
4882       EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
4883       if (auto *Def = Enum->getDefinition())
4884         Enum = Def;
4885       // FIXME: collect covered enumerators in cases like:
4886       //        if (x == my_enum::one) { ... } else if (x == ^) {}
4887       AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators());
4888     }
4889   }
4890 
4891   if (S->getFnParent() && !Data.ObjCCollection &&
4892       !Data.IntegralConstantExpression)
4893     AddPrettyFunctionResults(getLangOpts(), Results);
4894 
4895   if (CodeCompleter->includeMacros())
4896     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
4897                     PreferredTypeIsPointer);
4898 
4899   // Complete a lambda expression when preferred type is a function.
4900   if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) {
4901     if (const FunctionProtoType *F =
4902             TryDeconstructFunctionLike(Data.PreferredType))
4903       AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
4904   }
4905 
4906   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4907                             Results.data(), Results.size());
4908 }
4909 
4910 void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType,
4911                                   bool IsParenthesized) {
4912   return CodeCompleteExpression(
4913       S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
4914 }
4915 
4916 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E,
4917                                          QualType PreferredType) {
4918   if (E.isInvalid())
4919     CodeCompleteExpression(S, PreferredType);
4920   else if (getLangOpts().ObjC)
4921     CodeCompleteObjCInstanceMessage(S, E.get(), std::nullopt, false);
4922 }
4923 
4924 /// The set of properties that have already been added, referenced by
4925 /// property name.
4926 typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet;
4927 
4928 /// Retrieve the container definition, if any?
4929 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
4930   if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4931     if (Interface->hasDefinition())
4932       return Interface->getDefinition();
4933 
4934     return Interface;
4935   }
4936 
4937   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4938     if (Protocol->hasDefinition())
4939       return Protocol->getDefinition();
4940 
4941     return Protocol;
4942   }
4943   return Container;
4944 }
4945 
4946 /// Adds a block invocation code completion result for the given block
4947 /// declaration \p BD.
4948 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
4949                              CodeCompletionBuilder &Builder,
4950                              const NamedDecl *BD,
4951                              const FunctionTypeLoc &BlockLoc,
4952                              const FunctionProtoTypeLoc &BlockProtoLoc) {
4953   Builder.AddResultTypeChunk(
4954       GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
4955                               Policy, Builder.getAllocator()));
4956 
4957   AddTypedNameChunk(Context, Policy, BD, Builder);
4958   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4959 
4960   if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
4961     Builder.AddPlaceholderChunk("...");
4962   } else {
4963     for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
4964       if (I)
4965         Builder.AddChunk(CodeCompletionString::CK_Comma);
4966 
4967       // Format the placeholder string.
4968       std::string PlaceholderStr =
4969           FormatFunctionParameter(Policy, BlockLoc.getParam(I));
4970 
4971       if (I == N - 1 && BlockProtoLoc &&
4972           BlockProtoLoc.getTypePtr()->isVariadic())
4973         PlaceholderStr += ", ...";
4974 
4975       // Add the placeholder string.
4976       Builder.AddPlaceholderChunk(
4977           Builder.getAllocator().CopyString(PlaceholderStr));
4978     }
4979   }
4980 
4981   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4982 }
4983 
4984 static void
4985 AddObjCProperties(const CodeCompletionContext &CCContext,
4986                   ObjCContainerDecl *Container, bool AllowCategories,
4987                   bool AllowNullaryMethods, DeclContext *CurContext,
4988                   AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
4989                   bool IsBaseExprStatement = false,
4990                   bool IsClassProperty = false, bool InOriginalClass = true) {
4991   typedef CodeCompletionResult Result;
4992 
4993   // Retrieve the definition.
4994   Container = getContainerDef(Container);
4995 
4996   // Add properties in this container.
4997   const auto AddProperty = [&](const ObjCPropertyDecl *P) {
4998     if (!AddedProperties.insert(P->getIdentifier()).second)
4999       return;
5000 
5001     // FIXME: Provide block invocation completion for non-statement
5002     // expressions.
5003     if (!P->getType().getTypePtr()->isBlockPointerType() ||
5004         !IsBaseExprStatement) {
5005       Result R = Result(P, Results.getBasePriority(P), nullptr);
5006       if (!InOriginalClass)
5007         setInBaseClass(R);
5008       Results.MaybeAddResult(R, CurContext);
5009       return;
5010     }
5011 
5012     // Block setter and invocation completion is provided only when we are able
5013     // to find the FunctionProtoTypeLoc with parameter names for the block.
5014     FunctionTypeLoc BlockLoc;
5015     FunctionProtoTypeLoc BlockProtoLoc;
5016     findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
5017                                  BlockProtoLoc);
5018     if (!BlockLoc) {
5019       Result R = Result(P, Results.getBasePriority(P), nullptr);
5020       if (!InOriginalClass)
5021         setInBaseClass(R);
5022       Results.MaybeAddResult(R, CurContext);
5023       return;
5024     }
5025 
5026     // The default completion result for block properties should be the block
5027     // invocation completion when the base expression is a statement.
5028     CodeCompletionBuilder Builder(Results.getAllocator(),
5029                                   Results.getCodeCompletionTUInfo());
5030     AddObjCBlockCall(Container->getASTContext(),
5031                      getCompletionPrintingPolicy(Results.getSema()), Builder, P,
5032                      BlockLoc, BlockProtoLoc);
5033     Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
5034     if (!InOriginalClass)
5035       setInBaseClass(R);
5036     Results.MaybeAddResult(R, CurContext);
5037 
5038     // Provide additional block setter completion iff the base expression is a
5039     // statement and the block property is mutable.
5040     if (!P->isReadOnly()) {
5041       CodeCompletionBuilder Builder(Results.getAllocator(),
5042                                     Results.getCodeCompletionTUInfo());
5043       AddResultTypeChunk(Container->getASTContext(),
5044                          getCompletionPrintingPolicy(Results.getSema()), P,
5045                          CCContext.getBaseType(), Builder);
5046       Builder.AddTypedTextChunk(
5047           Results.getAllocator().CopyString(P->getName()));
5048       Builder.AddChunk(CodeCompletionString::CK_Equal);
5049 
5050       std::string PlaceholderStr = formatBlockPlaceholder(
5051           getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
5052           BlockProtoLoc, /*SuppressBlockName=*/true);
5053       // Add the placeholder string.
5054       Builder.AddPlaceholderChunk(
5055           Builder.getAllocator().CopyString(PlaceholderStr));
5056 
5057       // When completing blocks properties that return void the default
5058       // property completion result should show up before the setter,
5059       // otherwise the setter completion should show up before the default
5060       // property completion, as we normally want to use the result of the
5061       // call.
5062       Result R =
5063           Result(Builder.TakeString(), P,
5064                  Results.getBasePriority(P) +
5065                      (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
5066                           ? CCD_BlockPropertySetter
5067                           : -CCD_BlockPropertySetter));
5068       if (!InOriginalClass)
5069         setInBaseClass(R);
5070       Results.MaybeAddResult(R, CurContext);
5071     }
5072   };
5073 
5074   if (IsClassProperty) {
5075     for (const auto *P : Container->class_properties())
5076       AddProperty(P);
5077   } else {
5078     for (const auto *P : Container->instance_properties())
5079       AddProperty(P);
5080   }
5081 
5082   // Add nullary methods or implicit class properties
5083   if (AllowNullaryMethods) {
5084     ASTContext &Context = Container->getASTContext();
5085     PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5086     // Adds a method result
5087     const auto AddMethod = [&](const ObjCMethodDecl *M) {
5088       IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
5089       if (!Name)
5090         return;
5091       if (!AddedProperties.insert(Name).second)
5092         return;
5093       CodeCompletionBuilder Builder(Results.getAllocator(),
5094                                     Results.getCodeCompletionTUInfo());
5095       AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
5096       Builder.AddTypedTextChunk(
5097           Results.getAllocator().CopyString(Name->getName()));
5098       Result R = Result(Builder.TakeString(), M,
5099                         CCP_MemberDeclaration + CCD_MethodAsProperty);
5100       if (!InOriginalClass)
5101         setInBaseClass(R);
5102       Results.MaybeAddResult(R, CurContext);
5103     };
5104 
5105     if (IsClassProperty) {
5106       for (const auto *M : Container->methods()) {
5107         // Gather the class method that can be used as implicit property
5108         // getters. Methods with arguments or methods that return void aren't
5109         // added to the results as they can't be used as a getter.
5110         if (!M->getSelector().isUnarySelector() ||
5111             M->getReturnType()->isVoidType() || M->isInstanceMethod())
5112           continue;
5113         AddMethod(M);
5114       }
5115     } else {
5116       for (auto *M : Container->methods()) {
5117         if (M->getSelector().isUnarySelector())
5118           AddMethod(M);
5119       }
5120     }
5121   }
5122 
5123   // Add properties in referenced protocols.
5124   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5125     for (auto *P : Protocol->protocols())
5126       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5127                         CurContext, AddedProperties, Results,
5128                         IsBaseExprStatement, IsClassProperty,
5129                         /*InOriginalClass*/ false);
5130   } else if (ObjCInterfaceDecl *IFace =
5131                  dyn_cast<ObjCInterfaceDecl>(Container)) {
5132     if (AllowCategories) {
5133       // Look through categories.
5134       for (auto *Cat : IFace->known_categories())
5135         AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
5136                           CurContext, AddedProperties, Results,
5137                           IsBaseExprStatement, IsClassProperty,
5138                           InOriginalClass);
5139     }
5140 
5141     // Look through protocols.
5142     for (auto *I : IFace->all_referenced_protocols())
5143       AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
5144                         CurContext, AddedProperties, Results,
5145                         IsBaseExprStatement, IsClassProperty,
5146                         /*InOriginalClass*/ false);
5147 
5148     // Look in the superclass.
5149     if (IFace->getSuperClass())
5150       AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
5151                         AllowNullaryMethods, CurContext, AddedProperties,
5152                         Results, IsBaseExprStatement, IsClassProperty,
5153                         /*InOriginalClass*/ false);
5154   } else if (const auto *Category =
5155                  dyn_cast<ObjCCategoryDecl>(Container)) {
5156     // Look through protocols.
5157     for (auto *P : Category->protocols())
5158       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5159                         CurContext, AddedProperties, Results,
5160                         IsBaseExprStatement, IsClassProperty,
5161                         /*InOriginalClass*/ false);
5162   }
5163 }
5164 
5165 static void
5166 AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results,
5167                                   Scope *S, QualType BaseType,
5168                                   ExprValueKind BaseKind, RecordDecl *RD,
5169                                   std::optional<FixItHint> AccessOpFixIt) {
5170   // Indicate that we are performing a member access, and the cv-qualifiers
5171   // for the base object type.
5172   Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
5173 
5174   // Access to a C/C++ class, struct, or union.
5175   Results.allowNestedNameSpecifiers();
5176   std::vector<FixItHint> FixIts;
5177   if (AccessOpFixIt)
5178     FixIts.emplace_back(*AccessOpFixIt);
5179   CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
5180   SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
5181                              SemaRef.CodeCompleter->includeGlobals(),
5182                              /*IncludeDependentBases=*/true,
5183                              SemaRef.CodeCompleter->loadExternal());
5184 
5185   if (SemaRef.getLangOpts().CPlusPlus) {
5186     if (!Results.empty()) {
5187       // The "template" keyword can follow "->" or "." in the grammar.
5188       // However, we only want to suggest the template keyword if something
5189       // is dependent.
5190       bool IsDependent = BaseType->isDependentType();
5191       if (!IsDependent) {
5192         for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
5193           if (DeclContext *Ctx = DepScope->getEntity()) {
5194             IsDependent = Ctx->isDependentContext();
5195             break;
5196           }
5197       }
5198 
5199       if (IsDependent)
5200         Results.AddResult(CodeCompletionResult("template"));
5201     }
5202   }
5203 }
5204 
5205 // Returns the RecordDecl inside the BaseType, falling back to primary template
5206 // in case of specializations. Since we might not have a decl for the
5207 // instantiation/specialization yet, e.g. dependent code.
5208 static RecordDecl *getAsRecordDecl(QualType BaseType) {
5209   BaseType = BaseType.getNonReferenceType();
5210   if (auto *RD = BaseType->getAsRecordDecl()) {
5211     if (const auto *CTSD =
5212             llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
5213       // Template might not be instantiated yet, fall back to primary template
5214       // in such cases.
5215       if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
5216         RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
5217     }
5218     return RD;
5219   }
5220 
5221   if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
5222     if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
5223             TST->getTemplateName().getAsTemplateDecl())) {
5224       return TD->getTemplatedDecl();
5225     }
5226   }
5227 
5228   return nullptr;
5229 }
5230 
5231 namespace {
5232 // Collects completion-relevant information about a concept-constrainted type T.
5233 // In particular, examines the constraint expressions to find members of T.
5234 //
5235 // The design is very simple: we walk down each constraint looking for
5236 // expressions of the form T.foo().
5237 // If we're extra lucky, the return type is specified.
5238 // We don't do any clever handling of && or || in constraint expressions, we
5239 // take members from both branches.
5240 //
5241 // For example, given:
5242 //   template <class T> concept X = requires (T t, string& s) { t.print(s); };
5243 //   template <X U> void foo(U u) { u.^ }
5244 // We want to suggest the inferred member function 'print(string)'.
5245 // We see that u has type U, so X<U> holds.
5246 // X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5247 // By looking at the CallExpr we find the signature of print().
5248 //
5249 // While we tend to know in advance which kind of members (access via . -> ::)
5250 // we want, it's simpler just to gather them all and post-filter.
5251 //
5252 // FIXME: some of this machinery could be used for non-concept type-parms too,
5253 // enabling completion for type parameters based on other uses of that param.
5254 //
5255 // FIXME: there are other cases where a type can be constrained by a concept,
5256 // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5257 class ConceptInfo {
5258 public:
5259   // Describes a likely member of a type, inferred by concept constraints.
5260   // Offered as a code completion for T. T-> and T:: contexts.
5261   struct Member {
5262     // Always non-null: we only handle members with ordinary identifier names.
5263     const IdentifierInfo *Name = nullptr;
5264     // Set for functions we've seen called.
5265     // We don't have the declared parameter types, only the actual types of
5266     // arguments we've seen. These are still valuable, as it's hard to render
5267     // a useful function completion with neither parameter types nor names!
5268     std::optional<SmallVector<QualType, 1>> ArgTypes;
5269     // Whether this is accessed as T.member, T->member, or T::member.
5270     enum AccessOperator {
5271       Colons,
5272       Arrow,
5273       Dot,
5274     } Operator = Dot;
5275     // What's known about the type of a variable or return type of a function.
5276     const TypeConstraint *ResultType = nullptr;
5277     // FIXME: also track:
5278     //   - kind of entity (function/variable/type), to expose structured results
5279     //   - template args kinds/types, as a proxy for template params
5280 
5281     // For now we simply return these results as "pattern" strings.
5282     CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc,
5283                                  CodeCompletionTUInfo &Info) const {
5284       CodeCompletionBuilder B(Alloc, Info);
5285       // Result type
5286       if (ResultType) {
5287         std::string AsString;
5288         {
5289           llvm::raw_string_ostream OS(AsString);
5290           QualType ExactType = deduceType(*ResultType);
5291           if (!ExactType.isNull())
5292             ExactType.print(OS, getCompletionPrintingPolicy(S));
5293           else
5294             ResultType->print(OS, getCompletionPrintingPolicy(S));
5295         }
5296         B.AddResultTypeChunk(Alloc.CopyString(AsString));
5297       }
5298       // Member name
5299       B.AddTypedTextChunk(Alloc.CopyString(Name->getName()));
5300       // Function argument list
5301       if (ArgTypes) {
5302         B.AddChunk(clang::CodeCompletionString::CK_LeftParen);
5303         bool First = true;
5304         for (QualType Arg : *ArgTypes) {
5305           if (First)
5306             First = false;
5307           else {
5308             B.AddChunk(clang::CodeCompletionString::CK_Comma);
5309             B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
5310           }
5311           B.AddPlaceholderChunk(Alloc.CopyString(
5312               Arg.getAsString(getCompletionPrintingPolicy(S))));
5313         }
5314         B.AddChunk(clang::CodeCompletionString::CK_RightParen);
5315       }
5316       return B.TakeString();
5317     }
5318   };
5319 
5320   // BaseType is the type parameter T to infer members from.
5321   // T must be accessible within S, as we use it to find the template entity
5322   // that T is attached to in order to gather the relevant constraints.
5323   ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) {
5324     auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S);
5325     for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity))
5326       believe(E, &BaseType);
5327   }
5328 
5329   std::vector<Member> members() {
5330     std::vector<Member> Results;
5331     for (const auto &E : this->Results)
5332       Results.push_back(E.second);
5333     llvm::sort(Results, [](const Member &L, const Member &R) {
5334       return L.Name->getName() < R.Name->getName();
5335     });
5336     return Results;
5337   }
5338 
5339 private:
5340   // Infer members of T, given that the expression E (dependent on T) is true.
5341   void believe(const Expr *E, const TemplateTypeParmType *T) {
5342     if (!E || !T)
5343       return;
5344     if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) {
5345       // If the concept is
5346       //   template <class A, class B> concept CD = f<A, B>();
5347       // And the concept specialization is
5348       //   CD<int, T>
5349       // Then we're substituting T for B, so we want to make f<A, B>() true
5350       // by adding members to B - i.e. believe(f<A, B>(), B);
5351       //
5352       // For simplicity:
5353       // - we don't attempt to substitute int for A
5354       // - when T is used in other ways (like CD<T*>) we ignore it
5355       ConceptDecl *CD = CSE->getNamedConcept();
5356       TemplateParameterList *Params = CD->getTemplateParameters();
5357       unsigned Index = 0;
5358       for (const auto &Arg : CSE->getTemplateArguments()) {
5359         if (Index >= Params->size())
5360           break; // Won't happen in valid code.
5361         if (isApprox(Arg, T)) {
5362           auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index));
5363           if (!TTPD)
5364             continue;
5365           // T was used as an argument, and bound to the parameter TT.
5366           auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl());
5367           // So now we know the constraint as a function of TT is true.
5368           believe(CD->getConstraintExpr(), TT);
5369           // (concepts themselves have no associated constraints to require)
5370         }
5371 
5372         ++Index;
5373       }
5374     } else if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5375       // For A && B, we can infer members from both branches.
5376       // For A || B, the union is still more useful than the intersection.
5377       if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
5378         believe(BO->getLHS(), T);
5379         believe(BO->getRHS(), T);
5380       }
5381     } else if (auto *RE = dyn_cast<RequiresExpr>(E)) {
5382       // A requires(){...} lets us infer members from each requirement.
5383       for (const concepts::Requirement *Req : RE->getRequirements()) {
5384         if (!Req->isDependent())
5385           continue; // Can't tell us anything about T.
5386         // Now Req cannot a substitution-error: those aren't dependent.
5387 
5388         if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) {
5389           // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5390           QualType AssertedType = TR->getType()->getType();
5391           ValidVisitor(this, T).TraverseType(AssertedType);
5392         } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
5393           ValidVisitor Visitor(this, T);
5394           // If we have a type constraint on the value of the expression,
5395           // AND the whole outer expression describes a member, then we'll
5396           // be able to use the constraint to provide the return type.
5397           if (ER->getReturnTypeRequirement().isTypeConstraint()) {
5398             Visitor.OuterType =
5399                 ER->getReturnTypeRequirement().getTypeConstraint();
5400             Visitor.OuterExpr = ER->getExpr();
5401           }
5402           Visitor.TraverseStmt(ER->getExpr());
5403         } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) {
5404           believe(NR->getConstraintExpr(), T);
5405         }
5406       }
5407     }
5408   }
5409 
5410   // This visitor infers members of T based on traversing expressions/types
5411   // that involve T. It is invoked with code known to be valid for T.
5412   class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> {
5413     ConceptInfo *Outer;
5414     const TemplateTypeParmType *T;
5415 
5416     CallExpr *Caller = nullptr;
5417     Expr *Callee = nullptr;
5418 
5419   public:
5420     // If set, OuterExpr is constrained by OuterType.
5421     Expr *OuterExpr = nullptr;
5422     const TypeConstraint *OuterType = nullptr;
5423 
5424     ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T)
5425         : Outer(Outer), T(T) {
5426       assert(T);
5427     }
5428 
5429     // In T.foo or T->foo, `foo` is a member function/variable.
5430     bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
5431       const Type *Base = E->getBaseType().getTypePtr();
5432       bool IsArrow = E->isArrow();
5433       if (Base->isPointerType() && IsArrow) {
5434         IsArrow = false;
5435         Base = Base->getPointeeType().getTypePtr();
5436       }
5437       if (isApprox(Base, T))
5438         addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot);
5439       return true;
5440     }
5441 
5442     // In T::foo, `foo` is a static member function/variable.
5443     bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
5444       if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T))
5445         addValue(E, E->getDeclName(), Member::Colons);
5446       return true;
5447     }
5448 
5449     // In T::typename foo, `foo` is a type.
5450     bool VisitDependentNameType(DependentNameType *DNT) {
5451       const auto *Q = DNT->getQualifier();
5452       if (Q && isApprox(Q->getAsType(), T))
5453         addType(DNT->getIdentifier());
5454       return true;
5455     }
5456 
5457     // In T::foo::bar, `foo` must be a type.
5458     // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5459     bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
5460       if (NNSL) {
5461         NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier();
5462         const auto *Q = NNS->getPrefix();
5463         if (Q && isApprox(Q->getAsType(), T))
5464           addType(NNS->getAsIdentifier());
5465       }
5466       // FIXME: also handle T::foo<X>::bar
5467       return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL);
5468     }
5469 
5470     // FIXME also handle T::foo<X>
5471 
5472     // Track the innermost caller/callee relationship so we can tell if a
5473     // nested expr is being called as a function.
5474     bool VisitCallExpr(CallExpr *CE) {
5475       Caller = CE;
5476       Callee = CE->getCallee();
5477       return true;
5478     }
5479 
5480   private:
5481     void addResult(Member &&M) {
5482       auto R = Outer->Results.try_emplace(M.Name);
5483       Member &O = R.first->second;
5484       // Overwrite existing if the new member has more info.
5485       // The preference of . vs :: vs -> is fairly arbitrary.
5486       if (/*Inserted*/ R.second ||
5487           std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr,
5488                           M.Operator) > std::make_tuple(O.ArgTypes.has_value(),
5489                                                         O.ResultType != nullptr,
5490                                                         O.Operator))
5491         O = std::move(M);
5492     }
5493 
5494     void addType(const IdentifierInfo *Name) {
5495       if (!Name)
5496         return;
5497       Member M;
5498       M.Name = Name;
5499       M.Operator = Member::Colons;
5500       addResult(std::move(M));
5501     }
5502 
5503     void addValue(Expr *E, DeclarationName Name,
5504                   Member::AccessOperator Operator) {
5505       if (!Name.isIdentifier())
5506         return;
5507       Member Result;
5508       Result.Name = Name.getAsIdentifierInfo();
5509       Result.Operator = Operator;
5510       // If this is the callee of an immediately-enclosing CallExpr, then
5511       // treat it as a method, otherwise it's a variable.
5512       if (Caller != nullptr && Callee == E) {
5513         Result.ArgTypes.emplace();
5514         for (const auto *Arg : Caller->arguments())
5515           Result.ArgTypes->push_back(Arg->getType());
5516         if (Caller == OuterExpr) {
5517           Result.ResultType = OuterType;
5518         }
5519       } else {
5520         if (E == OuterExpr)
5521           Result.ResultType = OuterType;
5522       }
5523       addResult(std::move(Result));
5524     }
5525   };
5526 
5527   static bool isApprox(const TemplateArgument &Arg, const Type *T) {
5528     return Arg.getKind() == TemplateArgument::Type &&
5529            isApprox(Arg.getAsType().getTypePtr(), T);
5530   }
5531 
5532   static bool isApprox(const Type *T1, const Type *T2) {
5533     return T1 && T2 &&
5534            T1->getCanonicalTypeUnqualified() ==
5535                T2->getCanonicalTypeUnqualified();
5536   }
5537 
5538   // Returns the DeclContext immediately enclosed by the template parameter
5539   // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5540   // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5541   static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D,
5542                                          Scope *S) {
5543     if (D == nullptr)
5544       return nullptr;
5545     Scope *Inner = nullptr;
5546     while (S) {
5547       if (S->isTemplateParamScope() && S->isDeclScope(D))
5548         return Inner ? Inner->getEntity() : nullptr;
5549       Inner = S;
5550       S = S->getParent();
5551     }
5552     return nullptr;
5553   }
5554 
5555   // Gets all the type constraint expressions that might apply to the type
5556   // variables associated with DC (as returned by getTemplatedEntity()).
5557   static SmallVector<const Expr *, 1>
5558   constraintsForTemplatedEntity(DeclContext *DC) {
5559     SmallVector<const Expr *, 1> Result;
5560     if (DC == nullptr)
5561       return Result;
5562     // Primary templates can have constraints.
5563     if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate())
5564       TD->getAssociatedConstraints(Result);
5565     // Partial specializations may have constraints.
5566     if (const auto *CTPSD =
5567             dyn_cast<ClassTemplatePartialSpecializationDecl>(DC))
5568       CTPSD->getAssociatedConstraints(Result);
5569     if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC))
5570       VTPSD->getAssociatedConstraints(Result);
5571     return Result;
5572   }
5573 
5574   // Attempt to find the unique type satisfying a constraint.
5575   // This lets us show e.g. `int` instead of `std::same_as<int>`.
5576   static QualType deduceType(const TypeConstraint &T) {
5577     // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5578     // In this case the return type is T.
5579     DeclarationName DN = T.getNamedConcept()->getDeclName();
5580     if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as"))
5581       if (const auto *Args = T.getTemplateArgsAsWritten())
5582         if (Args->getNumTemplateArgs() == 1) {
5583           const auto &Arg = Args->arguments().front().getArgument();
5584           if (Arg.getKind() == TemplateArgument::Type)
5585             return Arg.getAsType();
5586         }
5587     return {};
5588   }
5589 
5590   llvm::DenseMap<const IdentifierInfo *, Member> Results;
5591 };
5592 
5593 // Returns a type for E that yields acceptable member completions.
5594 // In particular, when E->getType() is DependentTy, try to guess a likely type.
5595 // We accept some lossiness (like dropping parameters).
5596 // We only try to handle common expressions on the LHS of MemberExpr.
5597 QualType getApproximateType(const Expr *E) {
5598   if (E->getType().isNull())
5599     return QualType();
5600   E = E->IgnoreParenImpCasts();
5601   QualType Unresolved = E->getType();
5602   // We only resolve DependentTy, or undeduced autos (including auto* etc).
5603   if (!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent)) {
5604     AutoType *Auto = Unresolved->getContainedAutoType();
5605     if (!Auto || !Auto->isUndeducedAutoType())
5606       return Unresolved;
5607   }
5608   // A call: approximate-resolve callee to a function type, get its return type
5609   if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) {
5610     QualType Callee = getApproximateType(CE->getCallee());
5611     if (Callee.isNull() ||
5612         Callee->isSpecificPlaceholderType(BuiltinType::BoundMember))
5613       Callee = Expr::findBoundMemberType(CE->getCallee());
5614     if (Callee.isNull())
5615       return Unresolved;
5616 
5617     if (const auto *FnTypePtr = Callee->getAs<PointerType>()) {
5618       Callee = FnTypePtr->getPointeeType();
5619     } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) {
5620       Callee = BPT->getPointeeType();
5621     }
5622     if (const FunctionType *FnType = Callee->getAs<FunctionType>())
5623       return FnType->getReturnType().getNonReferenceType();
5624 
5625     // Unresolved call: try to guess the return type.
5626     if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) {
5627       // If all candidates have the same approximate return type, use it.
5628       // Discard references and const to allow more to be "the same".
5629       // (In particular, if there's one candidate + ADL, resolve it).
5630       const Type *Common = nullptr;
5631       for (const auto *D : OE->decls()) {
5632         QualType ReturnType;
5633         if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
5634           ReturnType = FD->getReturnType();
5635         else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
5636           ReturnType = FTD->getTemplatedDecl()->getReturnType();
5637         if (ReturnType.isNull())
5638           continue;
5639         const Type *Candidate =
5640             ReturnType.getNonReferenceType().getCanonicalType().getTypePtr();
5641         if (Common && Common != Candidate)
5642           return Unresolved; // Multiple candidates.
5643         Common = Candidate;
5644       }
5645       if (Common != nullptr)
5646         return QualType(Common, 0);
5647     }
5648   }
5649   // A dependent member: approximate-resolve the base, then lookup.
5650   if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5651     QualType Base = CDSME->isImplicitAccess()
5652                         ? CDSME->getBaseType()
5653                         : getApproximateType(CDSME->getBase());
5654     if (CDSME->isArrow() && !Base.isNull())
5655       Base = Base->getPointeeType(); // could handle unique_ptr etc here?
5656     auto *RD =
5657         Base.isNull()
5658             ? nullptr
5659             : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base));
5660     if (RD && RD->isCompleteDefinition()) {
5661       // Look up member heuristically, including in bases.
5662       for (const auto *Member : RD->lookupDependentName(
5663                CDSME->getMember(), [](const NamedDecl *Member) {
5664                  return llvm::isa<ValueDecl>(Member);
5665                })) {
5666         return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType();
5667       }
5668     }
5669   }
5670   // A reference to an `auto` variable: approximate-resolve its initializer.
5671   if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) {
5672     if (const auto *VD = llvm::dyn_cast<VarDecl>(DRE->getDecl())) {
5673       if (VD->hasInit())
5674         return getApproximateType(VD->getInit());
5675     }
5676   }
5677   return Unresolved;
5678 }
5679 
5680 // If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5681 // last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5682 // calls before here. (So the ParenListExpr should be nonempty, but check just
5683 // in case)
5684 Expr *unwrapParenList(Expr *Base) {
5685   if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) {
5686     if (PLE->getNumExprs() == 0)
5687       return nullptr;
5688     Base = PLE->getExpr(PLE->getNumExprs() - 1);
5689   }
5690   return Base;
5691 }
5692 
5693 } // namespace
5694 
5695 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5696                                            Expr *OtherOpBase,
5697                                            SourceLocation OpLoc, bool IsArrow,
5698                                            bool IsBaseExprStatement,
5699                                            QualType PreferredType) {
5700   Base = unwrapParenList(Base);
5701   OtherOpBase = unwrapParenList(OtherOpBase);
5702   if (!Base || !CodeCompleter)
5703     return;
5704 
5705   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5706   if (ConvertedBase.isInvalid())
5707     return;
5708   QualType ConvertedBaseType = getApproximateType(ConvertedBase.get());
5709 
5710   enum CodeCompletionContext::Kind contextKind;
5711 
5712   if (IsArrow) {
5713     if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
5714       ConvertedBaseType = Ptr->getPointeeType();
5715   }
5716 
5717   if (IsArrow) {
5718     contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
5719   } else {
5720     if (ConvertedBaseType->isObjCObjectPointerType() ||
5721         ConvertedBaseType->isObjCObjectOrInterfaceType()) {
5722       contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
5723     } else {
5724       contextKind = CodeCompletionContext::CCC_DotMemberAccess;
5725     }
5726   }
5727 
5728   CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
5729   CCContext.setPreferredType(PreferredType);
5730   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5731                         CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5732                         &ResultBuilder::IsMember);
5733 
5734   auto DoCompletion = [&](Expr *Base, bool IsArrow,
5735                           std::optional<FixItHint> AccessOpFixIt) -> bool {
5736     if (!Base)
5737       return false;
5738 
5739     ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5740     if (ConvertedBase.isInvalid())
5741       return false;
5742     Base = ConvertedBase.get();
5743 
5744     QualType BaseType = getApproximateType(Base);
5745     if (BaseType.isNull())
5746       return false;
5747     ExprValueKind BaseKind = Base->getValueKind();
5748 
5749     if (IsArrow) {
5750       if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5751         BaseType = Ptr->getPointeeType();
5752         BaseKind = VK_LValue;
5753       } else if (BaseType->isObjCObjectPointerType() ||
5754                  BaseType->isTemplateTypeParmType()) {
5755         // Both cases (dot/arrow) handled below.
5756       } else {
5757         return false;
5758       }
5759     }
5760 
5761     if (RecordDecl *RD = getAsRecordDecl(BaseType)) {
5762       AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
5763                                         RD, std::move(AccessOpFixIt));
5764     } else if (const auto *TTPT =
5765                    dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) {
5766       auto Operator =
5767           IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot;
5768       for (const auto &R : ConceptInfo(*TTPT, S).members()) {
5769         if (R.Operator != Operator)
5770           continue;
5771         CodeCompletionResult Result(
5772             R.render(*this, CodeCompleter->getAllocator(),
5773                      CodeCompleter->getCodeCompletionTUInfo()));
5774         if (AccessOpFixIt)
5775           Result.FixIts.push_back(*AccessOpFixIt);
5776         Results.AddResult(std::move(Result));
5777       }
5778     } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
5779       // Objective-C property reference. Bail if we're performing fix-it code
5780       // completion since Objective-C properties are normally backed by ivars,
5781       // most Objective-C fix-its here would have little value.
5782       if (AccessOpFixIt) {
5783         return false;
5784       }
5785       AddedPropertiesSet AddedProperties;
5786 
5787       if (const ObjCObjectPointerType *ObjCPtr =
5788               BaseType->getAsObjCInterfacePointerType()) {
5789         // Add property results based on our interface.
5790         assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
5791         AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
5792                           /*AllowNullaryMethods=*/true, CurContext,
5793                           AddedProperties, Results, IsBaseExprStatement);
5794       }
5795 
5796       // Add properties from the protocols in a qualified interface.
5797       for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals())
5798         AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
5799                           CurContext, AddedProperties, Results,
5800                           IsBaseExprStatement, /*IsClassProperty*/ false,
5801                           /*InOriginalClass*/ false);
5802     } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
5803                (!IsArrow && BaseType->isObjCObjectType())) {
5804       // Objective-C instance variable access. Bail if we're performing fix-it
5805       // code completion since Objective-C properties are normally backed by
5806       // ivars, most Objective-C fix-its here would have little value.
5807       if (AccessOpFixIt) {
5808         return false;
5809       }
5810       ObjCInterfaceDecl *Class = nullptr;
5811       if (const ObjCObjectPointerType *ObjCPtr =
5812               BaseType->getAs<ObjCObjectPointerType>())
5813         Class = ObjCPtr->getInterfaceDecl();
5814       else
5815         Class = BaseType->castAs<ObjCObjectType>()->getInterface();
5816 
5817       // Add all ivars from this class and its superclasses.
5818       if (Class) {
5819         CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
5820         Results.setFilter(&ResultBuilder::IsObjCIvar);
5821         LookupVisibleDecls(
5822             Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
5823             /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
5824       }
5825     }
5826 
5827     // FIXME: How do we cope with isa?
5828     return true;
5829   };
5830 
5831   Results.EnterNewScope();
5832 
5833   bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt);
5834   if (CodeCompleter->includeFixIts()) {
5835     const CharSourceRange OpRange =
5836         CharSourceRange::getTokenRange(OpLoc, OpLoc);
5837     CompletionSucceded |= DoCompletion(
5838         OtherOpBase, !IsArrow,
5839         FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->"));
5840   }
5841 
5842   Results.ExitScope();
5843 
5844   if (!CompletionSucceded)
5845     return;
5846 
5847   // Hand off the results found for code completion.
5848   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5849                             Results.data(), Results.size());
5850 }
5851 
5852 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
5853                                                 IdentifierInfo &ClassName,
5854                                                 SourceLocation ClassNameLoc,
5855                                                 bool IsBaseExprStatement) {
5856   IdentifierInfo *ClassNamePtr = &ClassName;
5857   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
5858   if (!IFace)
5859     return;
5860   CodeCompletionContext CCContext(
5861       CodeCompletionContext::CCC_ObjCPropertyAccess);
5862   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5863                         CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5864                         &ResultBuilder::IsMember);
5865   Results.EnterNewScope();
5866   AddedPropertiesSet AddedProperties;
5867   AddObjCProperties(CCContext, IFace, true,
5868                     /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
5869                     Results, IsBaseExprStatement,
5870                     /*IsClassProperty=*/true);
5871   Results.ExitScope();
5872   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5873                             Results.data(), Results.size());
5874 }
5875 
5876 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
5877   if (!CodeCompleter)
5878     return;
5879 
5880   ResultBuilder::LookupFilter Filter = nullptr;
5881   enum CodeCompletionContext::Kind ContextKind =
5882       CodeCompletionContext::CCC_Other;
5883   switch ((DeclSpec::TST)TagSpec) {
5884   case DeclSpec::TST_enum:
5885     Filter = &ResultBuilder::IsEnum;
5886     ContextKind = CodeCompletionContext::CCC_EnumTag;
5887     break;
5888 
5889   case DeclSpec::TST_union:
5890     Filter = &ResultBuilder::IsUnion;
5891     ContextKind = CodeCompletionContext::CCC_UnionTag;
5892     break;
5893 
5894   case DeclSpec::TST_struct:
5895   case DeclSpec::TST_class:
5896   case DeclSpec::TST_interface:
5897     Filter = &ResultBuilder::IsClassOrStruct;
5898     ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
5899     break;
5900 
5901   default:
5902     llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
5903   }
5904 
5905   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5906                         CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
5907   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5908 
5909   // First pass: look for tags.
5910   Results.setFilter(Filter);
5911   LookupVisibleDecls(S, LookupTagName, Consumer,
5912                      CodeCompleter->includeGlobals(),
5913                      CodeCompleter->loadExternal());
5914 
5915   if (CodeCompleter->includeGlobals()) {
5916     // Second pass: look for nested name specifiers.
5917     Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
5918     LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
5919                        CodeCompleter->includeGlobals(),
5920                        CodeCompleter->loadExternal());
5921   }
5922 
5923   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5924                             Results.data(), Results.size());
5925 }
5926 
5927 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
5928                                     const LangOptions &LangOpts) {
5929   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
5930     Results.AddResult("const");
5931   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
5932     Results.AddResult("volatile");
5933   if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
5934     Results.AddResult("restrict");
5935   if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
5936     Results.AddResult("_Atomic");
5937   if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
5938     Results.AddResult("__unaligned");
5939 }
5940 
5941 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
5942   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5943                         CodeCompleter->getCodeCompletionTUInfo(),
5944                         CodeCompletionContext::CCC_TypeQualifiers);
5945   Results.EnterNewScope();
5946   AddTypeQualifierResults(DS, Results, LangOpts);
5947   Results.ExitScope();
5948   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5949                             Results.data(), Results.size());
5950 }
5951 
5952 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
5953                                           const VirtSpecifiers *VS) {
5954   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5955                         CodeCompleter->getCodeCompletionTUInfo(),
5956                         CodeCompletionContext::CCC_TypeQualifiers);
5957   Results.EnterNewScope();
5958   AddTypeQualifierResults(DS, Results, LangOpts);
5959   if (LangOpts.CPlusPlus11) {
5960     Results.AddResult("noexcept");
5961     if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() &&
5962         !D.isStaticMember()) {
5963       if (!VS || !VS->isFinalSpecified())
5964         Results.AddResult("final");
5965       if (!VS || !VS->isOverrideSpecified())
5966         Results.AddResult("override");
5967     }
5968   }
5969   Results.ExitScope();
5970   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5971                             Results.data(), Results.size());
5972 }
5973 
5974 void Sema::CodeCompleteBracketDeclarator(Scope *S) {
5975   CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
5976 }
5977 
5978 void Sema::CodeCompleteCase(Scope *S) {
5979   if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
5980     return;
5981 
5982   SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
5983   // Condition expression might be invalid, do not continue in this case.
5984   if (!Switch->getCond())
5985     return;
5986   QualType type = Switch->getCond()->IgnoreImplicit()->getType();
5987   if (!type->isEnumeralType()) {
5988     CodeCompleteExpressionData Data(type);
5989     Data.IntegralConstantExpression = true;
5990     CodeCompleteExpression(S, Data);
5991     return;
5992   }
5993 
5994   // Code-complete the cases of a switch statement over an enumeration type
5995   // by providing the list of
5996   EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
5997   if (EnumDecl *Def = Enum->getDefinition())
5998     Enum = Def;
5999 
6000   // Determine which enumerators we have already seen in the switch statement.
6001   // FIXME: Ideally, we would also be able to look *past* the code-completion
6002   // token, in case we are code-completing in the middle of the switch and not
6003   // at the end. However, we aren't able to do so at the moment.
6004   CoveredEnumerators Enumerators;
6005   for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
6006        SC = SC->getNextSwitchCase()) {
6007     CaseStmt *Case = dyn_cast<CaseStmt>(SC);
6008     if (!Case)
6009       continue;
6010 
6011     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
6012     if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
6013       if (auto *Enumerator =
6014               dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6015         // We look into the AST of the case statement to determine which
6016         // enumerator was named. Alternatively, we could compute the value of
6017         // the integral constant expression, then compare it against the
6018         // values of each enumerator. However, value-based approach would not
6019         // work as well with C++ templates where enumerators declared within a
6020         // template are type- and value-dependent.
6021         Enumerators.Seen.insert(Enumerator);
6022 
6023         // If this is a qualified-id, keep track of the nested-name-specifier
6024         // so that we can reproduce it as part of code completion, e.g.,
6025         //
6026         //   switch (TagD.getKind()) {
6027         //     case TagDecl::TK_enum:
6028         //       break;
6029         //     case XXX
6030         //
6031         // At the XXX, our completions are TagDecl::TK_union,
6032         // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
6033         // TK_struct, and TK_class.
6034         Enumerators.SuggestedQualifier = DRE->getQualifier();
6035       }
6036   }
6037 
6038   // Add any enumerators that have not yet been mentioned.
6039   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6040                         CodeCompleter->getCodeCompletionTUInfo(),
6041                         CodeCompletionContext::CCC_Expression);
6042   AddEnumerators(Results, Context, Enum, CurContext, Enumerators);
6043 
6044   if (CodeCompleter->includeMacros()) {
6045     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6046   }
6047   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6048                             Results.data(), Results.size());
6049 }
6050 
6051 static bool anyNullArguments(ArrayRef<Expr *> Args) {
6052   if (Args.size() && !Args.data())
6053     return true;
6054 
6055   for (unsigned I = 0; I != Args.size(); ++I)
6056     if (!Args[I])
6057       return true;
6058 
6059   return false;
6060 }
6061 
6062 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
6063 
6064 static void mergeCandidatesWithResults(
6065     Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
6066     OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) {
6067   // Sort the overload candidate set by placing the best overloads first.
6068   llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
6069                                       const OverloadCandidate &Y) {
6070     return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
6071                                      CandidateSet.getKind());
6072   });
6073 
6074   // Add the remaining viable overload candidates as code-completion results.
6075   for (OverloadCandidate &Candidate : CandidateSet) {
6076     if (Candidate.Function) {
6077       if (Candidate.Function->isDeleted())
6078         continue;
6079       if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
6080                                 Candidate.Function) &&
6081           Candidate.Function->getNumParams() <= ArgSize &&
6082           // Having zero args is annoying, normally we don't surface a function
6083           // with 2 params, if you already have 2 params, because you are
6084           // inserting the 3rd now. But with zero, it helps the user to figure
6085           // out there are no overloads that take any arguments. Hence we are
6086           // keeping the overload.
6087           ArgSize > 0)
6088         continue;
6089     }
6090     if (Candidate.Viable)
6091       Results.push_back(ResultCandidate(Candidate.Function));
6092   }
6093 }
6094 
6095 /// Get the type of the Nth parameter from a given set of overload
6096 /// candidates.
6097 static QualType getParamType(Sema &SemaRef,
6098                              ArrayRef<ResultCandidate> Candidates, unsigned N) {
6099 
6100   // Given the overloads 'Candidates' for a function call matching all arguments
6101   // up to N, return the type of the Nth parameter if it is the same for all
6102   // overload candidates.
6103   QualType ParamType;
6104   for (auto &Candidate : Candidates) {
6105     QualType CandidateParamType = Candidate.getParamType(N);
6106     if (CandidateParamType.isNull())
6107       continue;
6108     if (ParamType.isNull()) {
6109       ParamType = CandidateParamType;
6110       continue;
6111     }
6112     if (!SemaRef.Context.hasSameUnqualifiedType(
6113             ParamType.getNonReferenceType(),
6114             CandidateParamType.getNonReferenceType()))
6115       // Two conflicting types, give up.
6116       return QualType();
6117   }
6118 
6119   return ParamType;
6120 }
6121 
6122 static QualType
6123 ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates,
6124                      unsigned CurrentArg, SourceLocation OpenParLoc,
6125                      bool Braced) {
6126   if (Candidates.empty())
6127     return QualType();
6128   if (SemaRef.getPreprocessor().isCodeCompletionReached())
6129     SemaRef.CodeCompleter->ProcessOverloadCandidates(
6130         SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc,
6131         Braced);
6132   return getParamType(SemaRef, Candidates, CurrentArg);
6133 }
6134 
6135 // Given a callee expression `Fn`, if the call is through a function pointer,
6136 // try to find the declaration of the corresponding function pointer type,
6137 // so that we can recover argument names from it.
6138 static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
6139   TypeLoc Target;
6140   if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) {
6141     Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
6142 
6143   } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) {
6144     const auto *D = DR->getDecl();
6145     if (const auto *const VD = dyn_cast<VarDecl>(D)) {
6146       Target = VD->getTypeSourceInfo()->getTypeLoc();
6147     }
6148   }
6149 
6150   if (!Target)
6151     return {};
6152 
6153   // Unwrap types that may be wrapping the function type
6154   while (true) {
6155     if (auto P = Target.getAs<PointerTypeLoc>()) {
6156       Target = P.getPointeeLoc();
6157       continue;
6158     }
6159     if (auto A = Target.getAs<AttributedTypeLoc>()) {
6160       Target = A.getModifiedLoc();
6161       continue;
6162     }
6163     if (auto P = Target.getAs<ParenTypeLoc>()) {
6164       Target = P.getInnerLoc();
6165       continue;
6166     }
6167     break;
6168   }
6169 
6170   if (auto F = Target.getAs<FunctionProtoTypeLoc>()) {
6171     return F;
6172   }
6173 
6174   return {};
6175 }
6176 
6177 QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
6178                                         SourceLocation OpenParLoc) {
6179   Fn = unwrapParenList(Fn);
6180   if (!CodeCompleter || !Fn)
6181     return QualType();
6182 
6183   // FIXME: Provide support for variadic template functions.
6184   // Ignore type-dependent call expressions entirely.
6185   if (Fn->isTypeDependent() || anyNullArguments(Args))
6186     return QualType();
6187   // In presence of dependent args we surface all possible signatures using the
6188   // non-dependent args in the prefix. Afterwards we do a post filtering to make
6189   // sure provided candidates satisfy parameter count restrictions.
6190   auto ArgsWithoutDependentTypes =
6191       Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); });
6192 
6193   SmallVector<ResultCandidate, 8> Results;
6194 
6195   Expr *NakedFn = Fn->IgnoreParenCasts();
6196   // Build an overload candidate set based on the functions we find.
6197   SourceLocation Loc = Fn->getExprLoc();
6198   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6199 
6200   if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) {
6201     AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, CandidateSet,
6202                                 /*PartialOverloading=*/true);
6203   } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
6204     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
6205     if (UME->hasExplicitTemplateArgs()) {
6206       UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
6207       TemplateArgs = &TemplateArgsBuffer;
6208     }
6209 
6210     // Add the base as first argument (use a nullptr if the base is implicit).
6211     SmallVector<Expr *, 12> ArgExprs(
6212         1, UME->isImplicitAccess() ? nullptr : UME->getBase());
6213     ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6214                     ArgsWithoutDependentTypes.end());
6215     UnresolvedSet<8> Decls;
6216     Decls.append(UME->decls_begin(), UME->decls_end());
6217     const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
6218     AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
6219                           /*SuppressUserConversions=*/false,
6220                           /*PartialOverloading=*/true, FirstArgumentIsBase);
6221   } else {
6222     FunctionDecl *FD = nullptr;
6223     if (auto *MCE = dyn_cast<MemberExpr>(NakedFn))
6224       FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
6225     else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn))
6226       FD = dyn_cast<FunctionDecl>(DRE->getDecl());
6227     if (FD) { // We check whether it's a resolved function declaration.
6228       if (!getLangOpts().CPlusPlus ||
6229           !FD->getType()->getAs<FunctionProtoType>())
6230         Results.push_back(ResultCandidate(FD));
6231       else
6232         AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
6233                              ArgsWithoutDependentTypes, CandidateSet,
6234                              /*SuppressUserConversions=*/false,
6235                              /*PartialOverloading=*/true);
6236 
6237     } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
6238       // If expression's type is CXXRecordDecl, it may overload the function
6239       // call operator, so we check if it does and add them as candidates.
6240       // A complete type is needed to lookup for member function call operators.
6241       if (isCompleteType(Loc, NakedFn->getType())) {
6242         DeclarationName OpName =
6243             Context.DeclarationNames.getCXXOperatorName(OO_Call);
6244         LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
6245         LookupQualifiedName(R, DC);
6246         R.suppressDiagnostics();
6247         SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
6248         ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6249                         ArgsWithoutDependentTypes.end());
6250         AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
6251                               /*ExplicitArgs=*/nullptr,
6252                               /*SuppressUserConversions=*/false,
6253                               /*PartialOverloading=*/true);
6254       }
6255     } else {
6256       // Lastly we check whether expression's type is function pointer or
6257       // function.
6258 
6259       FunctionProtoTypeLoc P = GetPrototypeLoc(NakedFn);
6260       QualType T = NakedFn->getType();
6261       if (!T->getPointeeType().isNull())
6262         T = T->getPointeeType();
6263 
6264       if (auto FP = T->getAs<FunctionProtoType>()) {
6265         if (!TooManyArguments(FP->getNumParams(),
6266                               ArgsWithoutDependentTypes.size(),
6267                               /*PartialOverloading=*/true) ||
6268             FP->isVariadic()) {
6269           if (P) {
6270             Results.push_back(ResultCandidate(P));
6271           } else {
6272             Results.push_back(ResultCandidate(FP));
6273           }
6274         }
6275       } else if (auto FT = T->getAs<FunctionType>())
6276         // No prototype and declaration, it may be a K & R style function.
6277         Results.push_back(ResultCandidate(FT));
6278     }
6279   }
6280   mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
6281   QualType ParamType = ProduceSignatureHelp(*this, Results, Args.size(),
6282                                             OpenParLoc, /*Braced=*/false);
6283   return !CandidateSet.empty() ? ParamType : QualType();
6284 }
6285 
6286 // Determine which param to continue aggregate initialization from after
6287 // a designated initializer.
6288 //
6289 // Given struct S { int a,b,c,d,e; }:
6290 //   after `S{.b=1,`       we want to suggest c to continue
6291 //   after `S{.b=1, 2,`    we continue with d (this is legal C and ext in C++)
6292 //   after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
6293 //
6294 // Possible outcomes:
6295 //   - we saw a designator for a field, and continue from the returned index.
6296 //     Only aggregate initialization is allowed.
6297 //   - we saw a designator, but it was complex or we couldn't find the field.
6298 //     Only aggregate initialization is possible, but we can't assist with it.
6299 //     Returns an out-of-range index.
6300 //   - we saw no designators, just positional arguments.
6301 //     Returns std::nullopt.
6302 static std::optional<unsigned>
6303 getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate,
6304                                          ArrayRef<Expr *> Args) {
6305   static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max();
6306   assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate);
6307 
6308   // Look for designated initializers.
6309   // They're in their syntactic form, not yet resolved to fields.
6310   const IdentifierInfo *DesignatedFieldName = nullptr;
6311   unsigned ArgsAfterDesignator = 0;
6312   for (const Expr *Arg : Args) {
6313     if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) {
6314       if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) {
6315         DesignatedFieldName = DIE->getDesignator(0)->getFieldName();
6316         ArgsAfterDesignator = 0;
6317       } else {
6318         return Invalid; // Complicated designator.
6319       }
6320     } else if (isa<DesignatedInitUpdateExpr>(Arg)) {
6321       return Invalid; // Unsupported.
6322     } else {
6323       ++ArgsAfterDesignator;
6324     }
6325   }
6326   if (!DesignatedFieldName)
6327     return std::nullopt;
6328 
6329   // Find the index within the class's fields.
6330   // (Probing getParamDecl() directly would be quadratic in number of fields).
6331   unsigned DesignatedIndex = 0;
6332   const FieldDecl *DesignatedField = nullptr;
6333   for (const auto *Field : Aggregate.getAggregate()->fields()) {
6334     if (Field->getIdentifier() == DesignatedFieldName) {
6335       DesignatedField = Field;
6336       break;
6337     }
6338     ++DesignatedIndex;
6339   }
6340   if (!DesignatedField)
6341     return Invalid; // Designator referred to a missing field, give up.
6342 
6343   // Find the index within the aggregate (which may have leading bases).
6344   unsigned AggregateSize = Aggregate.getNumParams();
6345   while (DesignatedIndex < AggregateSize &&
6346          Aggregate.getParamDecl(DesignatedIndex) != DesignatedField)
6347     ++DesignatedIndex;
6348 
6349   // Continue from the index after the last named field.
6350   return DesignatedIndex + ArgsAfterDesignator + 1;
6351 }
6352 
6353 QualType Sema::ProduceConstructorSignatureHelp(QualType Type,
6354                                                SourceLocation Loc,
6355                                                ArrayRef<Expr *> Args,
6356                                                SourceLocation OpenParLoc,
6357                                                bool Braced) {
6358   if (!CodeCompleter)
6359     return QualType();
6360   SmallVector<ResultCandidate, 8> Results;
6361 
6362   // A complete type is needed to lookup for constructors.
6363   RecordDecl *RD =
6364       isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr;
6365   if (!RD)
6366     return Type;
6367   CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD);
6368 
6369   // Consider aggregate initialization.
6370   // We don't check that types so far are correct.
6371   // We also don't handle C99/C++17 brace-elision, we assume init-list elements
6372   // are 1:1 with fields.
6373   // FIXME: it would be nice to support "unwrapping" aggregates that contain
6374   // a single subaggregate, like std::array<T, N> -> T __elements[N].
6375   if (Braced && !RD->isUnion() &&
6376       (!LangOpts.CPlusPlus || (CRD && CRD->isAggregate()))) {
6377     ResultCandidate AggregateSig(RD);
6378     unsigned AggregateSize = AggregateSig.getNumParams();
6379 
6380     if (auto NextIndex =
6381             getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) {
6382       // A designator was used, only aggregate init is possible.
6383       if (*NextIndex >= AggregateSize)
6384         return Type;
6385       Results.push_back(AggregateSig);
6386       return ProduceSignatureHelp(*this, Results, *NextIndex, OpenParLoc,
6387                                   Braced);
6388     }
6389 
6390     // Describe aggregate initialization, but also constructors below.
6391     if (Args.size() < AggregateSize)
6392       Results.push_back(AggregateSig);
6393   }
6394 
6395   // FIXME: Provide support for member initializers.
6396   // FIXME: Provide support for variadic template constructors.
6397 
6398   if (CRD) {
6399     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6400     for (NamedDecl *C : LookupConstructors(CRD)) {
6401       if (auto *FD = dyn_cast<FunctionDecl>(C)) {
6402         // FIXME: we can't yet provide correct signature help for initializer
6403         //        list constructors, so skip them entirely.
6404         if (Braced && LangOpts.CPlusPlus && isInitListConstructor(FD))
6405           continue;
6406         AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args,
6407                              CandidateSet,
6408                              /*SuppressUserConversions=*/false,
6409                              /*PartialOverloading=*/true,
6410                              /*AllowExplicit*/ true);
6411       } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) {
6412         if (Braced && LangOpts.CPlusPlus &&
6413             isInitListConstructor(FTD->getTemplatedDecl()))
6414           continue;
6415 
6416         AddTemplateOverloadCandidate(
6417             FTD, DeclAccessPair::make(FTD, C->getAccess()),
6418             /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet,
6419             /*SuppressUserConversions=*/false,
6420             /*PartialOverloading=*/true);
6421       }
6422     }
6423     mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
6424   }
6425 
6426   return ProduceSignatureHelp(*this, Results, Args.size(), OpenParLoc, Braced);
6427 }
6428 
6429 QualType Sema::ProduceCtorInitMemberSignatureHelp(
6430     Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
6431     ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
6432     bool Braced) {
6433   if (!CodeCompleter)
6434     return QualType();
6435 
6436   CXXConstructorDecl *Constructor =
6437       dyn_cast<CXXConstructorDecl>(ConstructorDecl);
6438   if (!Constructor)
6439     return QualType();
6440   // FIXME: Add support for Base class constructors as well.
6441   if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl(
6442           Constructor->getParent(), SS, TemplateTypeTy, II))
6443     return ProduceConstructorSignatureHelp(MemberDecl->getType(),
6444                                            MemberDecl->getLocation(), ArgExprs,
6445                                            OpenParLoc, Braced);
6446   return QualType();
6447 }
6448 
6449 static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg,
6450                                      unsigned Index,
6451                                      const TemplateParameterList &Params) {
6452   const NamedDecl *Param;
6453   if (Index < Params.size())
6454     Param = Params.getParam(Index);
6455   else if (Params.hasParameterPack())
6456     Param = Params.asArray().back();
6457   else
6458     return false; // too many args
6459 
6460   switch (Arg.getKind()) {
6461   case ParsedTemplateArgument::Type:
6462     return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked
6463   case ParsedTemplateArgument::NonType:
6464     return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked
6465   case ParsedTemplateArgument::Template:
6466     return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked
6467   }
6468   llvm_unreachable("Unhandled switch case");
6469 }
6470 
6471 QualType Sema::ProduceTemplateArgumentSignatureHelp(
6472     TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args,
6473     SourceLocation LAngleLoc) {
6474   if (!CodeCompleter || !ParsedTemplate)
6475     return QualType();
6476 
6477   SmallVector<ResultCandidate, 8> Results;
6478   auto Consider = [&](const TemplateDecl *TD) {
6479     // Only add if the existing args are compatible with the template.
6480     bool Matches = true;
6481     for (unsigned I = 0; I < Args.size(); ++I) {
6482       if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) {
6483         Matches = false;
6484         break;
6485       }
6486     }
6487     if (Matches)
6488       Results.emplace_back(TD);
6489   };
6490 
6491   TemplateName Template = ParsedTemplate.get();
6492   if (const auto *TD = Template.getAsTemplateDecl()) {
6493     Consider(TD);
6494   } else if (const auto *OTS = Template.getAsOverloadedTemplate()) {
6495     for (const NamedDecl *ND : *OTS)
6496       if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND))
6497         Consider(TD);
6498   }
6499   return ProduceSignatureHelp(*this, Results, Args.size(), LAngleLoc,
6500                               /*Braced=*/false);
6501 }
6502 
6503 static QualType getDesignatedType(QualType BaseType, const Designation &Desig) {
6504   for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) {
6505     if (BaseType.isNull())
6506       break;
6507     QualType NextType;
6508     const auto &D = Desig.getDesignator(I);
6509     if (D.isArrayDesignator() || D.isArrayRangeDesignator()) {
6510       if (BaseType->isArrayType())
6511         NextType = BaseType->getAsArrayTypeUnsafe()->getElementType();
6512     } else {
6513       assert(D.isFieldDesignator());
6514       auto *RD = getAsRecordDecl(BaseType);
6515       if (RD && RD->isCompleteDefinition()) {
6516         for (const auto *Member : RD->lookup(D.getFieldDecl()))
6517           if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) {
6518             NextType = FD->getType();
6519             break;
6520           }
6521       }
6522     }
6523     BaseType = NextType;
6524   }
6525   return BaseType;
6526 }
6527 
6528 void Sema::CodeCompleteDesignator(QualType BaseType,
6529                                   llvm::ArrayRef<Expr *> InitExprs,
6530                                   const Designation &D) {
6531   BaseType = getDesignatedType(BaseType, D);
6532   if (BaseType.isNull())
6533     return;
6534   const auto *RD = getAsRecordDecl(BaseType);
6535   if (!RD || RD->fields().empty())
6536     return;
6537 
6538   CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess,
6539                             BaseType);
6540   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6541                         CodeCompleter->getCodeCompletionTUInfo(), CCC);
6542 
6543   Results.EnterNewScope();
6544   for (const Decl *D : RD->decls()) {
6545     const FieldDecl *FD;
6546     if (auto *IFD = dyn_cast<IndirectFieldDecl>(D))
6547       FD = IFD->getAnonField();
6548     else if (auto *DFD = dyn_cast<FieldDecl>(D))
6549       FD = DFD;
6550     else
6551       continue;
6552 
6553     // FIXME: Make use of previous designators to mark any fields before those
6554     // inaccessible, and also compute the next initializer priority.
6555     ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
6556     Results.AddResult(Result, CurContext, /*Hiding=*/nullptr);
6557   }
6558   Results.ExitScope();
6559   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6560                             Results.data(), Results.size());
6561 }
6562 
6563 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
6564   ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
6565   if (!VD) {
6566     CodeCompleteOrdinaryName(S, PCC_Expression);
6567     return;
6568   }
6569 
6570   CodeCompleteExpressionData Data;
6571   Data.PreferredType = VD->getType();
6572   // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
6573   Data.IgnoreDecls.push_back(VD);
6574 
6575   CodeCompleteExpression(S, Data);
6576 }
6577 
6578 void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) {
6579   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6580                         CodeCompleter->getCodeCompletionTUInfo(),
6581                         mapCodeCompletionContext(*this, PCC_Statement));
6582   Results.setFilter(&ResultBuilder::IsOrdinaryName);
6583   Results.EnterNewScope();
6584 
6585   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6586   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6587                      CodeCompleter->includeGlobals(),
6588                      CodeCompleter->loadExternal());
6589 
6590   AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
6591 
6592   // "else" block
6593   CodeCompletionBuilder Builder(Results.getAllocator(),
6594                                 Results.getCodeCompletionTUInfo());
6595 
6596   auto AddElseBodyPattern = [&] {
6597     if (IsBracedThen) {
6598       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6599       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6600       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6601       Builder.AddPlaceholderChunk("statements");
6602       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6603       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
6604     } else {
6605       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6606       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6607       Builder.AddPlaceholderChunk("statement");
6608       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
6609     }
6610   };
6611   Builder.AddTypedTextChunk("else");
6612   if (Results.includeCodePatterns())
6613     AddElseBodyPattern();
6614   Results.AddResult(Builder.TakeString());
6615 
6616   // "else if" block
6617   Builder.AddTypedTextChunk("else if");
6618   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6619   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6620   if (getLangOpts().CPlusPlus)
6621     Builder.AddPlaceholderChunk("condition");
6622   else
6623     Builder.AddPlaceholderChunk("expression");
6624   Builder.AddChunk(CodeCompletionString::CK_RightParen);
6625   if (Results.includeCodePatterns()) {
6626     AddElseBodyPattern();
6627   }
6628   Results.AddResult(Builder.TakeString());
6629 
6630   Results.ExitScope();
6631 
6632   if (S->getFnParent())
6633     AddPrettyFunctionResults(getLangOpts(), Results);
6634 
6635   if (CodeCompleter->includeMacros())
6636     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6637 
6638   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6639                             Results.data(), Results.size());
6640 }
6641 
6642 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
6643                                    bool EnteringContext,
6644                                    bool IsUsingDeclaration, QualType BaseType,
6645                                    QualType PreferredType) {
6646   if (SS.isEmpty() || !CodeCompleter)
6647     return;
6648 
6649   CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType);
6650   CC.setIsUsingDeclaration(IsUsingDeclaration);
6651   CC.setCXXScopeSpecifier(SS);
6652 
6653   // We want to keep the scope specifier even if it's invalid (e.g. the scope
6654   // "a::b::" is not corresponding to any context/namespace in the AST), since
6655   // it can be useful for global code completion which have information about
6656   // contexts/symbols that are not in the AST.
6657   if (SS.isInvalid()) {
6658     // As SS is invalid, we try to collect accessible contexts from the current
6659     // scope with a dummy lookup so that the completion consumer can try to
6660     // guess what the specified scope is.
6661     ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(),
6662                                CodeCompleter->getCodeCompletionTUInfo(), CC);
6663     if (!PreferredType.isNull())
6664       DummyResults.setPreferredType(PreferredType);
6665     if (S->getEntity()) {
6666       CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
6667                                           BaseType);
6668       LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6669                          /*IncludeGlobalScope=*/false,
6670                          /*LoadExternal=*/false);
6671     }
6672     HandleCodeCompleteResults(this, CodeCompleter,
6673                               DummyResults.getCompletionContext(), nullptr, 0);
6674     return;
6675   }
6676   // Always pretend to enter a context to ensure that a dependent type
6677   // resolves to a dependent record.
6678   DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
6679 
6680   // Try to instantiate any non-dependent declaration contexts before
6681   // we look in them. Bail out if we fail.
6682   NestedNameSpecifier *NNS = SS.getScopeRep();
6683   if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) {
6684     if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx))
6685       return;
6686   }
6687 
6688   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6689                         CodeCompleter->getCodeCompletionTUInfo(), CC);
6690   if (!PreferredType.isNull())
6691     Results.setPreferredType(PreferredType);
6692   Results.EnterNewScope();
6693 
6694   // The "template" keyword can follow "::" in the grammar, but only
6695   // put it into the grammar if the nested-name-specifier is dependent.
6696   // FIXME: results is always empty, this appears to be dead.
6697   if (!Results.empty() && NNS && NNS->isDependent())
6698     Results.AddResult("template");
6699 
6700   // If the scope is a concept-constrained type parameter, infer nested
6701   // members based on the constraints.
6702   if (const auto *TTPT =
6703           dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) {
6704     for (const auto &R : ConceptInfo(*TTPT, S).members()) {
6705       if (R.Operator != ConceptInfo::Member::Colons)
6706         continue;
6707       Results.AddResult(CodeCompletionResult(
6708           R.render(*this, CodeCompleter->getAllocator(),
6709                    CodeCompleter->getCodeCompletionTUInfo())));
6710     }
6711   }
6712 
6713   // Add calls to overridden virtual functions, if there are any.
6714   //
6715   // FIXME: This isn't wonderful, because we don't know whether we're actually
6716   // in a context that permits expressions. This is a general issue with
6717   // qualified-id completions.
6718   if (Ctx && !EnteringContext)
6719     MaybeAddOverrideCalls(*this, Ctx, Results);
6720   Results.ExitScope();
6721 
6722   if (Ctx &&
6723       (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) {
6724     CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
6725     LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
6726                        /*IncludeGlobalScope=*/true,
6727                        /*IncludeDependentBases=*/true,
6728                        CodeCompleter->loadExternal());
6729   }
6730 
6731   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6732                             Results.data(), Results.size());
6733 }
6734 
6735 void Sema::CodeCompleteUsing(Scope *S) {
6736   if (!CodeCompleter)
6737     return;
6738 
6739   // This can be both a using alias or using declaration, in the former we
6740   // expect a new name and a symbol in the latter case.
6741   CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName);
6742   Context.setIsUsingDeclaration(true);
6743 
6744   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6745                         CodeCompleter->getCodeCompletionTUInfo(), Context,
6746                         &ResultBuilder::IsNestedNameSpecifier);
6747   Results.EnterNewScope();
6748 
6749   // If we aren't in class scope, we could see the "namespace" keyword.
6750   if (!S->isClassScope())
6751     Results.AddResult(CodeCompletionResult("namespace"));
6752 
6753   // After "using", we can see anything that would start a
6754   // nested-name-specifier.
6755   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6756   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6757                      CodeCompleter->includeGlobals(),
6758                      CodeCompleter->loadExternal());
6759   Results.ExitScope();
6760 
6761   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6762                             Results.data(), Results.size());
6763 }
6764 
6765 void Sema::CodeCompleteUsingDirective(Scope *S) {
6766   if (!CodeCompleter)
6767     return;
6768 
6769   // After "using namespace", we expect to see a namespace name or namespace
6770   // alias.
6771   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6772                         CodeCompleter->getCodeCompletionTUInfo(),
6773                         CodeCompletionContext::CCC_Namespace,
6774                         &ResultBuilder::IsNamespaceOrAlias);
6775   Results.EnterNewScope();
6776   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6777   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6778                      CodeCompleter->includeGlobals(),
6779                      CodeCompleter->loadExternal());
6780   Results.ExitScope();
6781   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6782                             Results.data(), Results.size());
6783 }
6784 
6785 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
6786   if (!CodeCompleter)
6787     return;
6788 
6789   DeclContext *Ctx = S->getEntity();
6790   if (!S->getParent())
6791     Ctx = Context.getTranslationUnitDecl();
6792 
6793   bool SuppressedGlobalResults =
6794       Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
6795 
6796   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6797                         CodeCompleter->getCodeCompletionTUInfo(),
6798                         SuppressedGlobalResults
6799                             ? CodeCompletionContext::CCC_Namespace
6800                             : CodeCompletionContext::CCC_Other,
6801                         &ResultBuilder::IsNamespace);
6802 
6803   if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
6804     // We only want to see those namespaces that have already been defined
6805     // within this scope, because its likely that the user is creating an
6806     // extended namespace declaration. Keep track of the most recent
6807     // definition of each namespace.
6808     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
6809     for (DeclContext::specific_decl_iterator<NamespaceDecl>
6810              NS(Ctx->decls_begin()),
6811          NSEnd(Ctx->decls_end());
6812          NS != NSEnd; ++NS)
6813       OrigToLatest[NS->getOriginalNamespace()] = *NS;
6814 
6815     // Add the most recent definition (or extended definition) of each
6816     // namespace to the list of results.
6817     Results.EnterNewScope();
6818     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
6819              NS = OrigToLatest.begin(),
6820              NSEnd = OrigToLatest.end();
6821          NS != NSEnd; ++NS)
6822       Results.AddResult(
6823           CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
6824                                nullptr),
6825           CurContext, nullptr, false);
6826     Results.ExitScope();
6827   }
6828 
6829   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6830                             Results.data(), Results.size());
6831 }
6832 
6833 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
6834   if (!CodeCompleter)
6835     return;
6836 
6837   // After "namespace", we expect to see a namespace or alias.
6838   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6839                         CodeCompleter->getCodeCompletionTUInfo(),
6840                         CodeCompletionContext::CCC_Namespace,
6841                         &ResultBuilder::IsNamespaceOrAlias);
6842   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6843   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6844                      CodeCompleter->includeGlobals(),
6845                      CodeCompleter->loadExternal());
6846   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6847                             Results.data(), Results.size());
6848 }
6849 
6850 void Sema::CodeCompleteOperatorName(Scope *S) {
6851   if (!CodeCompleter)
6852     return;
6853 
6854   typedef CodeCompletionResult Result;
6855   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6856                         CodeCompleter->getCodeCompletionTUInfo(),
6857                         CodeCompletionContext::CCC_Type,
6858                         &ResultBuilder::IsType);
6859   Results.EnterNewScope();
6860 
6861   // Add the names of overloadable operators. Note that OO_Conditional is not
6862   // actually overloadable.
6863 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
6864   if (OO_##Name != OO_Conditional)                                             \
6865     Results.AddResult(Result(Spelling));
6866 #include "clang/Basic/OperatorKinds.def"
6867 
6868   // Add any type names visible from the current scope
6869   Results.allowNestedNameSpecifiers();
6870   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6871   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6872                      CodeCompleter->includeGlobals(),
6873                      CodeCompleter->loadExternal());
6874 
6875   // Add any type specifiers
6876   AddTypeSpecifierResults(getLangOpts(), Results);
6877   Results.ExitScope();
6878 
6879   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6880                             Results.data(), Results.size());
6881 }
6882 
6883 void Sema::CodeCompleteConstructorInitializer(
6884     Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
6885   if (!ConstructorD)
6886     return;
6887 
6888   AdjustDeclIfTemplate(ConstructorD);
6889 
6890   auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
6891   if (!Constructor)
6892     return;
6893 
6894   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6895                         CodeCompleter->getCodeCompletionTUInfo(),
6896                         CodeCompletionContext::CCC_Symbol);
6897   Results.EnterNewScope();
6898 
6899   // Fill in any already-initialized fields or base classes.
6900   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
6901   llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
6902   for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
6903     if (Initializers[I]->isBaseInitializer())
6904       InitializedBases.insert(Context.getCanonicalType(
6905           QualType(Initializers[I]->getBaseClass(), 0)));
6906     else
6907       InitializedFields.insert(
6908           cast<FieldDecl>(Initializers[I]->getAnyMember()));
6909   }
6910 
6911   // Add completions for base classes.
6912   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6913   bool SawLastInitializer = Initializers.empty();
6914   CXXRecordDecl *ClassDecl = Constructor->getParent();
6915 
6916   auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
6917     CodeCompletionBuilder Builder(Results.getAllocator(),
6918                                   Results.getCodeCompletionTUInfo());
6919     Builder.AddTypedTextChunk(Name);
6920     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6921     if (const auto *Function = dyn_cast<FunctionDecl>(ND))
6922       AddFunctionParameterChunks(PP, Policy, Function, Builder);
6923     else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
6924       AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(),
6925                                  Builder);
6926     Builder.AddChunk(CodeCompletionString::CK_RightParen);
6927     return Builder.TakeString();
6928   };
6929   auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
6930                                 const NamedDecl *ND) {
6931     CodeCompletionBuilder Builder(Results.getAllocator(),
6932                                   Results.getCodeCompletionTUInfo());
6933     Builder.AddTypedTextChunk(Name);
6934     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6935     Builder.AddPlaceholderChunk(Type);
6936     Builder.AddChunk(CodeCompletionString::CK_RightParen);
6937     if (ND) {
6938       auto CCR = CodeCompletionResult(
6939           Builder.TakeString(), ND,
6940           SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
6941       if (isa<FieldDecl>(ND))
6942         CCR.CursorKind = CXCursor_MemberRef;
6943       return Results.AddResult(CCR);
6944     }
6945     return Results.AddResult(CodeCompletionResult(
6946         Builder.TakeString(),
6947         SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
6948   };
6949   auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
6950                               const char *Name, const FieldDecl *FD) {
6951     if (!RD)
6952       return AddDefaultCtorInit(Name,
6953                                 FD ? Results.getAllocator().CopyString(
6954                                          FD->getType().getAsString(Policy))
6955                                    : Name,
6956                                 FD);
6957     auto Ctors = getConstructors(Context, RD);
6958     if (Ctors.begin() == Ctors.end())
6959       return AddDefaultCtorInit(Name, Name, RD);
6960     for (const NamedDecl *Ctor : Ctors) {
6961       auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
6962       CCR.CursorKind = getCursorKindForDecl(Ctor);
6963       Results.AddResult(CCR);
6964     }
6965   };
6966   auto AddBase = [&](const CXXBaseSpecifier &Base) {
6967     const char *BaseName =
6968         Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
6969     const auto *RD = Base.getType()->getAsCXXRecordDecl();
6970     AddCtorsWithName(
6971         RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
6972         BaseName, nullptr);
6973   };
6974   auto AddField = [&](const FieldDecl *FD) {
6975     const char *FieldName =
6976         Results.getAllocator().CopyString(FD->getIdentifier()->getName());
6977     const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6978     AddCtorsWithName(
6979         RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
6980         FieldName, FD);
6981   };
6982 
6983   for (const auto &Base : ClassDecl->bases()) {
6984     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
6985              .second) {
6986       SawLastInitializer =
6987           !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
6988           Context.hasSameUnqualifiedType(
6989               Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
6990       continue;
6991     }
6992 
6993     AddBase(Base);
6994     SawLastInitializer = false;
6995   }
6996 
6997   // Add completions for virtual base classes.
6998   for (const auto &Base : ClassDecl->vbases()) {
6999     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
7000              .second) {
7001       SawLastInitializer =
7002           !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
7003           Context.hasSameUnqualifiedType(
7004               Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
7005       continue;
7006     }
7007 
7008     AddBase(Base);
7009     SawLastInitializer = false;
7010   }
7011 
7012   // Add completions for members.
7013   for (auto *Field : ClassDecl->fields()) {
7014     if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
7015              .second) {
7016       SawLastInitializer = !Initializers.empty() &&
7017                            Initializers.back()->isAnyMemberInitializer() &&
7018                            Initializers.back()->getAnyMember() == Field;
7019       continue;
7020     }
7021 
7022     if (!Field->getDeclName())
7023       continue;
7024 
7025     AddField(Field);
7026     SawLastInitializer = false;
7027   }
7028   Results.ExitScope();
7029 
7030   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7031                             Results.data(), Results.size());
7032 }
7033 
7034 /// Determine whether this scope denotes a namespace.
7035 static bool isNamespaceScope(Scope *S) {
7036   DeclContext *DC = S->getEntity();
7037   if (!DC)
7038     return false;
7039 
7040   return DC->isFileContext();
7041 }
7042 
7043 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7044                                         bool AfterAmpersand) {
7045   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7046                         CodeCompleter->getCodeCompletionTUInfo(),
7047                         CodeCompletionContext::CCC_Other);
7048   Results.EnterNewScope();
7049 
7050   // Note what has already been captured.
7051   llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
7052   bool IncludedThis = false;
7053   for (const auto &C : Intro.Captures) {
7054     if (C.Kind == LCK_This) {
7055       IncludedThis = true;
7056       continue;
7057     }
7058 
7059     Known.insert(C.Id);
7060   }
7061 
7062   // Look for other capturable variables.
7063   for (; S && !isNamespaceScope(S); S = S->getParent()) {
7064     for (const auto *D : S->decls()) {
7065       const auto *Var = dyn_cast<VarDecl>(D);
7066       if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
7067         continue;
7068 
7069       if (Known.insert(Var->getIdentifier()).second)
7070         Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
7071                           CurContext, nullptr, false);
7072     }
7073   }
7074 
7075   // Add 'this', if it would be valid.
7076   if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
7077     addThisCompletion(*this, Results);
7078 
7079   Results.ExitScope();
7080 
7081   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7082                             Results.data(), Results.size());
7083 }
7084 
7085 void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) {
7086   if (!LangOpts.CPlusPlus11)
7087     return;
7088   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7089                         CodeCompleter->getCodeCompletionTUInfo(),
7090                         CodeCompletionContext::CCC_Other);
7091   auto ShouldAddDefault = [&D, this]() {
7092     if (!D.isFunctionDeclarator())
7093       return false;
7094     auto &Id = D.getName();
7095     if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName)
7096       return true;
7097     // FIXME(liuhui): Ideally, we should check the constructor parameter list to
7098     // verify that it is the default, copy or move constructor?
7099     if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName &&
7100         D.getFunctionTypeInfo().NumParams <= 1)
7101       return true;
7102     if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) {
7103       auto Op = Id.OperatorFunctionId.Operator;
7104       // FIXME(liuhui): Ideally, we should check the function parameter list to
7105       // verify that it is the copy or move assignment?
7106       if (Op == OverloadedOperatorKind::OO_Equal)
7107         return true;
7108       if (LangOpts.CPlusPlus20 &&
7109           (Op == OverloadedOperatorKind::OO_EqualEqual ||
7110            Op == OverloadedOperatorKind::OO_ExclaimEqual ||
7111            Op == OverloadedOperatorKind::OO_Less ||
7112            Op == OverloadedOperatorKind::OO_LessEqual ||
7113            Op == OverloadedOperatorKind::OO_Greater ||
7114            Op == OverloadedOperatorKind::OO_GreaterEqual ||
7115            Op == OverloadedOperatorKind::OO_Spaceship))
7116         return true;
7117     }
7118     return false;
7119   };
7120 
7121   Results.EnterNewScope();
7122   if (ShouldAddDefault())
7123     Results.AddResult("default");
7124   // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
7125   // first function declaration.
7126   Results.AddResult("delete");
7127   Results.ExitScope();
7128   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7129                             Results.data(), Results.size());
7130 }
7131 
7132 /// Macro that optionally prepends an "@" to the string literal passed in via
7133 /// Keyword, depending on whether NeedAt is true or false.
7134 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
7135 
7136 static void AddObjCImplementationResults(const LangOptions &LangOpts,
7137                                          ResultBuilder &Results, bool NeedAt) {
7138   typedef CodeCompletionResult Result;
7139   // Since we have an implementation, we can end it.
7140   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7141 
7142   CodeCompletionBuilder Builder(Results.getAllocator(),
7143                                 Results.getCodeCompletionTUInfo());
7144   if (LangOpts.ObjC) {
7145     // @dynamic
7146     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
7147     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7148     Builder.AddPlaceholderChunk("property");
7149     Results.AddResult(Result(Builder.TakeString()));
7150 
7151     // @synthesize
7152     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize"));
7153     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7154     Builder.AddPlaceholderChunk("property");
7155     Results.AddResult(Result(Builder.TakeString()));
7156   }
7157 }
7158 
7159 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
7160                                     ResultBuilder &Results, bool NeedAt) {
7161   typedef CodeCompletionResult Result;
7162 
7163   // Since we have an interface or protocol, we can end it.
7164   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7165 
7166   if (LangOpts.ObjC) {
7167     // @property
7168     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
7169 
7170     // @required
7171     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
7172 
7173     // @optional
7174     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
7175   }
7176 }
7177 
7178 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
7179   typedef CodeCompletionResult Result;
7180   CodeCompletionBuilder Builder(Results.getAllocator(),
7181                                 Results.getCodeCompletionTUInfo());
7182 
7183   // @class name ;
7184   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
7185   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7186   Builder.AddPlaceholderChunk("name");
7187   Results.AddResult(Result(Builder.TakeString()));
7188 
7189   if (Results.includeCodePatterns()) {
7190     // @interface name
7191     // FIXME: Could introduce the whole pattern, including superclasses and
7192     // such.
7193     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
7194     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7195     Builder.AddPlaceholderChunk("class");
7196     Results.AddResult(Result(Builder.TakeString()));
7197 
7198     // @protocol name
7199     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7200     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7201     Builder.AddPlaceholderChunk("protocol");
7202     Results.AddResult(Result(Builder.TakeString()));
7203 
7204     // @implementation name
7205     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
7206     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7207     Builder.AddPlaceholderChunk("class");
7208     Results.AddResult(Result(Builder.TakeString()));
7209   }
7210 
7211   // @compatibility_alias name
7212   Builder.AddTypedTextChunk(
7213       OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
7214   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7215   Builder.AddPlaceholderChunk("alias");
7216   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7217   Builder.AddPlaceholderChunk("class");
7218   Results.AddResult(Result(Builder.TakeString()));
7219 
7220   if (Results.getSema().getLangOpts().Modules) {
7221     // @import name
7222     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
7223     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7224     Builder.AddPlaceholderChunk("module");
7225     Results.AddResult(Result(Builder.TakeString()));
7226   }
7227 }
7228 
7229 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
7230   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7231                         CodeCompleter->getCodeCompletionTUInfo(),
7232                         CodeCompletionContext::CCC_Other);
7233   Results.EnterNewScope();
7234   if (isa<ObjCImplDecl>(CurContext))
7235     AddObjCImplementationResults(getLangOpts(), Results, false);
7236   else if (CurContext->isObjCContainer())
7237     AddObjCInterfaceResults(getLangOpts(), Results, false);
7238   else
7239     AddObjCTopLevelResults(Results, false);
7240   Results.ExitScope();
7241   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7242                             Results.data(), Results.size());
7243 }
7244 
7245 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
7246   typedef CodeCompletionResult Result;
7247   CodeCompletionBuilder Builder(Results.getAllocator(),
7248                                 Results.getCodeCompletionTUInfo());
7249 
7250   // @encode ( type-name )
7251   const char *EncodeType = "char[]";
7252   if (Results.getSema().getLangOpts().CPlusPlus ||
7253       Results.getSema().getLangOpts().ConstStrings)
7254     EncodeType = "const char[]";
7255   Builder.AddResultTypeChunk(EncodeType);
7256   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode"));
7257   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7258   Builder.AddPlaceholderChunk("type-name");
7259   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7260   Results.AddResult(Result(Builder.TakeString()));
7261 
7262   // @protocol ( protocol-name )
7263   Builder.AddResultTypeChunk("Protocol *");
7264   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7265   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7266   Builder.AddPlaceholderChunk("protocol-name");
7267   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7268   Results.AddResult(Result(Builder.TakeString()));
7269 
7270   // @selector ( selector )
7271   Builder.AddResultTypeChunk("SEL");
7272   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector"));
7273   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7274   Builder.AddPlaceholderChunk("selector");
7275   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7276   Results.AddResult(Result(Builder.TakeString()));
7277 
7278   // @"string"
7279   Builder.AddResultTypeChunk("NSString *");
7280   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\""));
7281   Builder.AddPlaceholderChunk("string");
7282   Builder.AddTextChunk("\"");
7283   Results.AddResult(Result(Builder.TakeString()));
7284 
7285   // @[objects, ...]
7286   Builder.AddResultTypeChunk("NSArray *");
7287   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "["));
7288   Builder.AddPlaceholderChunk("objects, ...");
7289   Builder.AddChunk(CodeCompletionString::CK_RightBracket);
7290   Results.AddResult(Result(Builder.TakeString()));
7291 
7292   // @{key : object, ...}
7293   Builder.AddResultTypeChunk("NSDictionary *");
7294   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{"));
7295   Builder.AddPlaceholderChunk("key");
7296   Builder.AddChunk(CodeCompletionString::CK_Colon);
7297   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7298   Builder.AddPlaceholderChunk("object, ...");
7299   Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7300   Results.AddResult(Result(Builder.TakeString()));
7301 
7302   // @(expression)
7303   Builder.AddResultTypeChunk("id");
7304   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
7305   Builder.AddPlaceholderChunk("expression");
7306   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7307   Results.AddResult(Result(Builder.TakeString()));
7308 }
7309 
7310 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
7311   typedef CodeCompletionResult Result;
7312   CodeCompletionBuilder Builder(Results.getAllocator(),
7313                                 Results.getCodeCompletionTUInfo());
7314 
7315   if (Results.includeCodePatterns()) {
7316     // @try { statements } @catch ( declaration ) { statements } @finally
7317     //   { statements }
7318     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try"));
7319     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7320     Builder.AddPlaceholderChunk("statements");
7321     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7322     Builder.AddTextChunk("@catch");
7323     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7324     Builder.AddPlaceholderChunk("parameter");
7325     Builder.AddChunk(CodeCompletionString::CK_RightParen);
7326     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7327     Builder.AddPlaceholderChunk("statements");
7328     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7329     Builder.AddTextChunk("@finally");
7330     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7331     Builder.AddPlaceholderChunk("statements");
7332     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7333     Results.AddResult(Result(Builder.TakeString()));
7334   }
7335 
7336   // @throw
7337   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw"));
7338   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7339   Builder.AddPlaceholderChunk("expression");
7340   Results.AddResult(Result(Builder.TakeString()));
7341 
7342   if (Results.includeCodePatterns()) {
7343     // @synchronized ( expression ) { statements }
7344     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized"));
7345     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7346     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7347     Builder.AddPlaceholderChunk("expression");
7348     Builder.AddChunk(CodeCompletionString::CK_RightParen);
7349     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7350     Builder.AddPlaceholderChunk("statements");
7351     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7352     Results.AddResult(Result(Builder.TakeString()));
7353   }
7354 }
7355 
7356 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
7357                                      ResultBuilder &Results, bool NeedAt) {
7358   typedef CodeCompletionResult Result;
7359   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")));
7360   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")));
7361   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")));
7362   if (LangOpts.ObjC)
7363     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")));
7364 }
7365 
7366 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
7367   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7368                         CodeCompleter->getCodeCompletionTUInfo(),
7369                         CodeCompletionContext::CCC_Other);
7370   Results.EnterNewScope();
7371   AddObjCVisibilityResults(getLangOpts(), Results, false);
7372   Results.ExitScope();
7373   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7374                             Results.data(), Results.size());
7375 }
7376 
7377 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
7378   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7379                         CodeCompleter->getCodeCompletionTUInfo(),
7380                         CodeCompletionContext::CCC_Other);
7381   Results.EnterNewScope();
7382   AddObjCStatementResults(Results, false);
7383   AddObjCExpressionResults(Results, false);
7384   Results.ExitScope();
7385   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7386                             Results.data(), Results.size());
7387 }
7388 
7389 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
7390   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7391                         CodeCompleter->getCodeCompletionTUInfo(),
7392                         CodeCompletionContext::CCC_Other);
7393   Results.EnterNewScope();
7394   AddObjCExpressionResults(Results, false);
7395   Results.ExitScope();
7396   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7397                             Results.data(), Results.size());
7398 }
7399 
7400 /// Determine whether the addition of the given flag to an Objective-C
7401 /// property's attributes will cause a conflict.
7402 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
7403   // Check if we've already added this flag.
7404   if (Attributes & NewFlag)
7405     return true;
7406 
7407   Attributes |= NewFlag;
7408 
7409   // Check for collisions with "readonly".
7410   if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
7411       (Attributes & ObjCPropertyAttribute::kind_readwrite))
7412     return true;
7413 
7414   // Check for more than one of { assign, copy, retain, strong, weak }.
7415   unsigned AssignCopyRetMask =
7416       Attributes &
7417       (ObjCPropertyAttribute::kind_assign |
7418        ObjCPropertyAttribute::kind_unsafe_unretained |
7419        ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain |
7420        ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak);
7421   if (AssignCopyRetMask &&
7422       AssignCopyRetMask != ObjCPropertyAttribute::kind_assign &&
7423       AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained &&
7424       AssignCopyRetMask != ObjCPropertyAttribute::kind_copy &&
7425       AssignCopyRetMask != ObjCPropertyAttribute::kind_retain &&
7426       AssignCopyRetMask != ObjCPropertyAttribute::kind_strong &&
7427       AssignCopyRetMask != ObjCPropertyAttribute::kind_weak)
7428     return true;
7429 
7430   return false;
7431 }
7432 
7433 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
7434   if (!CodeCompleter)
7435     return;
7436 
7437   unsigned Attributes = ODS.getPropertyAttributes();
7438 
7439   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7440                         CodeCompleter->getCodeCompletionTUInfo(),
7441                         CodeCompletionContext::CCC_Other);
7442   Results.EnterNewScope();
7443   if (!ObjCPropertyFlagConflicts(Attributes,
7444                                  ObjCPropertyAttribute::kind_readonly))
7445     Results.AddResult(CodeCompletionResult("readonly"));
7446   if (!ObjCPropertyFlagConflicts(Attributes,
7447                                  ObjCPropertyAttribute::kind_assign))
7448     Results.AddResult(CodeCompletionResult("assign"));
7449   if (!ObjCPropertyFlagConflicts(Attributes,
7450                                  ObjCPropertyAttribute::kind_unsafe_unretained))
7451     Results.AddResult(CodeCompletionResult("unsafe_unretained"));
7452   if (!ObjCPropertyFlagConflicts(Attributes,
7453                                  ObjCPropertyAttribute::kind_readwrite))
7454     Results.AddResult(CodeCompletionResult("readwrite"));
7455   if (!ObjCPropertyFlagConflicts(Attributes,
7456                                  ObjCPropertyAttribute::kind_retain))
7457     Results.AddResult(CodeCompletionResult("retain"));
7458   if (!ObjCPropertyFlagConflicts(Attributes,
7459                                  ObjCPropertyAttribute::kind_strong))
7460     Results.AddResult(CodeCompletionResult("strong"));
7461   if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy))
7462     Results.AddResult(CodeCompletionResult("copy"));
7463   if (!ObjCPropertyFlagConflicts(Attributes,
7464                                  ObjCPropertyAttribute::kind_nonatomic))
7465     Results.AddResult(CodeCompletionResult("nonatomic"));
7466   if (!ObjCPropertyFlagConflicts(Attributes,
7467                                  ObjCPropertyAttribute::kind_atomic))
7468     Results.AddResult(CodeCompletionResult("atomic"));
7469 
7470   // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
7471   if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
7472     if (!ObjCPropertyFlagConflicts(Attributes,
7473                                    ObjCPropertyAttribute::kind_weak))
7474       Results.AddResult(CodeCompletionResult("weak"));
7475 
7476   if (!ObjCPropertyFlagConflicts(Attributes,
7477                                  ObjCPropertyAttribute::kind_setter)) {
7478     CodeCompletionBuilder Setter(Results.getAllocator(),
7479                                  Results.getCodeCompletionTUInfo());
7480     Setter.AddTypedTextChunk("setter");
7481     Setter.AddTextChunk("=");
7482     Setter.AddPlaceholderChunk("method");
7483     Results.AddResult(CodeCompletionResult(Setter.TakeString()));
7484   }
7485   if (!ObjCPropertyFlagConflicts(Attributes,
7486                                  ObjCPropertyAttribute::kind_getter)) {
7487     CodeCompletionBuilder Getter(Results.getAllocator(),
7488                                  Results.getCodeCompletionTUInfo());
7489     Getter.AddTypedTextChunk("getter");
7490     Getter.AddTextChunk("=");
7491     Getter.AddPlaceholderChunk("method");
7492     Results.AddResult(CodeCompletionResult(Getter.TakeString()));
7493   }
7494   if (!ObjCPropertyFlagConflicts(Attributes,
7495                                  ObjCPropertyAttribute::kind_nullability)) {
7496     Results.AddResult(CodeCompletionResult("nonnull"));
7497     Results.AddResult(CodeCompletionResult("nullable"));
7498     Results.AddResult(CodeCompletionResult("null_unspecified"));
7499     Results.AddResult(CodeCompletionResult("null_resettable"));
7500   }
7501   Results.ExitScope();
7502   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7503                             Results.data(), Results.size());
7504 }
7505 
7506 /// Describes the kind of Objective-C method that we want to find
7507 /// via code completion.
7508 enum ObjCMethodKind {
7509   MK_Any, ///< Any kind of method, provided it means other specified criteria.
7510   MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
7511   MK_OneArgSelector   ///< One-argument selector.
7512 };
7513 
7514 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind,
7515                                      ArrayRef<IdentifierInfo *> SelIdents,
7516                                      bool AllowSameLength = true) {
7517   unsigned NumSelIdents = SelIdents.size();
7518   if (NumSelIdents > Sel.getNumArgs())
7519     return false;
7520 
7521   switch (WantKind) {
7522   case MK_Any:
7523     break;
7524   case MK_ZeroArgSelector:
7525     return Sel.isUnarySelector();
7526   case MK_OneArgSelector:
7527     return Sel.getNumArgs() == 1;
7528   }
7529 
7530   if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
7531     return false;
7532 
7533   for (unsigned I = 0; I != NumSelIdents; ++I)
7534     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
7535       return false;
7536 
7537   return true;
7538 }
7539 
7540 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
7541                                    ObjCMethodKind WantKind,
7542                                    ArrayRef<IdentifierInfo *> SelIdents,
7543                                    bool AllowSameLength = true) {
7544   return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
7545                                   AllowSameLength);
7546 }
7547 
7548 /// A set of selectors, which is used to avoid introducing multiple
7549 /// completions with the same selector into the result set.
7550 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
7551 
7552 /// Add all of the Objective-C methods in the given Objective-C
7553 /// container to the set of results.
7554 ///
7555 /// The container will be a class, protocol, category, or implementation of
7556 /// any of the above. This mether will recurse to include methods from
7557 /// the superclasses of classes along with their categories, protocols, and
7558 /// implementations.
7559 ///
7560 /// \param Container the container in which we'll look to find methods.
7561 ///
7562 /// \param WantInstanceMethods Whether to add instance methods (only); if
7563 /// false, this routine will add factory methods (only).
7564 ///
7565 /// \param CurContext the context in which we're performing the lookup that
7566 /// finds methods.
7567 ///
7568 /// \param AllowSameLength Whether we allow a method to be added to the list
7569 /// when it has the same number of parameters as we have selector identifiers.
7570 ///
7571 /// \param Results the structure into which we'll add results.
7572 static void AddObjCMethods(ObjCContainerDecl *Container,
7573                            bool WantInstanceMethods, ObjCMethodKind WantKind,
7574                            ArrayRef<IdentifierInfo *> SelIdents,
7575                            DeclContext *CurContext,
7576                            VisitedSelectorSet &Selectors, bool AllowSameLength,
7577                            ResultBuilder &Results, bool InOriginalClass = true,
7578                            bool IsRootClass = false) {
7579   typedef CodeCompletionResult Result;
7580   Container = getContainerDef(Container);
7581   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
7582   IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
7583   for (ObjCMethodDecl *M : Container->methods()) {
7584     // The instance methods on the root class can be messaged via the
7585     // metaclass.
7586     if (M->isInstanceMethod() == WantInstanceMethods ||
7587         (IsRootClass && !WantInstanceMethods)) {
7588       // Check whether the selector identifiers we've been given are a
7589       // subset of the identifiers for this particular method.
7590       if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
7591         continue;
7592 
7593       if (!Selectors.insert(M->getSelector()).second)
7594         continue;
7595 
7596       Result R = Result(M, Results.getBasePriority(M), nullptr);
7597       R.StartParameter = SelIdents.size();
7598       R.AllParametersAreInformative = (WantKind != MK_Any);
7599       if (!InOriginalClass)
7600         setInBaseClass(R);
7601       Results.MaybeAddResult(R, CurContext);
7602     }
7603   }
7604 
7605   // Visit the protocols of protocols.
7606   if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
7607     if (Protocol->hasDefinition()) {
7608       const ObjCList<ObjCProtocolDecl> &Protocols =
7609           Protocol->getReferencedProtocols();
7610       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7611                                                 E = Protocols.end();
7612            I != E; ++I)
7613         AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7614                        Selectors, AllowSameLength, Results, false, IsRootClass);
7615     }
7616   }
7617 
7618   if (!IFace || !IFace->hasDefinition())
7619     return;
7620 
7621   // Add methods in protocols.
7622   for (ObjCProtocolDecl *I : IFace->protocols())
7623     AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7624                    Selectors, AllowSameLength, Results, false, IsRootClass);
7625 
7626   // Add methods in categories.
7627   for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) {
7628     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
7629                    CurContext, Selectors, AllowSameLength, Results,
7630                    InOriginalClass, IsRootClass);
7631 
7632     // Add a categories protocol methods.
7633     const ObjCList<ObjCProtocolDecl> &Protocols =
7634         CatDecl->getReferencedProtocols();
7635     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7636                                               E = Protocols.end();
7637          I != E; ++I)
7638       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7639                      Selectors, AllowSameLength, Results, false, IsRootClass);
7640 
7641     // Add methods in category implementations.
7642     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
7643       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7644                      Selectors, AllowSameLength, Results, InOriginalClass,
7645                      IsRootClass);
7646   }
7647 
7648   // Add methods in superclass.
7649   // Avoid passing in IsRootClass since root classes won't have super classes.
7650   if (IFace->getSuperClass())
7651     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
7652                    SelIdents, CurContext, Selectors, AllowSameLength, Results,
7653                    /*IsRootClass=*/false);
7654 
7655   // Add methods in our implementation, if any.
7656   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
7657     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7658                    Selectors, AllowSameLength, Results, InOriginalClass,
7659                    IsRootClass);
7660 }
7661 
7662 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
7663   // Try to find the interface where getters might live.
7664   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
7665   if (!Class) {
7666     if (ObjCCategoryDecl *Category =
7667             dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
7668       Class = Category->getClassInterface();
7669 
7670     if (!Class)
7671       return;
7672   }
7673 
7674   // Find all of the potential getters.
7675   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7676                         CodeCompleter->getCodeCompletionTUInfo(),
7677                         CodeCompletionContext::CCC_Other);
7678   Results.EnterNewScope();
7679 
7680   VisitedSelectorSet Selectors;
7681   AddObjCMethods(Class, true, MK_ZeroArgSelector, std::nullopt, CurContext,
7682                  Selectors,
7683                  /*AllowSameLength=*/true, Results);
7684   Results.ExitScope();
7685   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7686                             Results.data(), Results.size());
7687 }
7688 
7689 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
7690   // Try to find the interface where setters might live.
7691   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
7692   if (!Class) {
7693     if (ObjCCategoryDecl *Category =
7694             dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
7695       Class = Category->getClassInterface();
7696 
7697     if (!Class)
7698       return;
7699   }
7700 
7701   // Find all of the potential getters.
7702   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7703                         CodeCompleter->getCodeCompletionTUInfo(),
7704                         CodeCompletionContext::CCC_Other);
7705   Results.EnterNewScope();
7706 
7707   VisitedSelectorSet Selectors;
7708   AddObjCMethods(Class, true, MK_OneArgSelector, std::nullopt, CurContext,
7709                  Selectors,
7710                  /*AllowSameLength=*/true, Results);
7711 
7712   Results.ExitScope();
7713   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7714                             Results.data(), Results.size());
7715 }
7716 
7717 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7718                                        bool IsParameter) {
7719   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7720                         CodeCompleter->getCodeCompletionTUInfo(),
7721                         CodeCompletionContext::CCC_Type);
7722   Results.EnterNewScope();
7723 
7724   // Add context-sensitive, Objective-C parameter-passing keywords.
7725   bool AddedInOut = false;
7726   if ((DS.getObjCDeclQualifier() &
7727        (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
7728     Results.AddResult("in");
7729     Results.AddResult("inout");
7730     AddedInOut = true;
7731   }
7732   if ((DS.getObjCDeclQualifier() &
7733        (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
7734     Results.AddResult("out");
7735     if (!AddedInOut)
7736       Results.AddResult("inout");
7737   }
7738   if ((DS.getObjCDeclQualifier() &
7739        (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
7740         ObjCDeclSpec::DQ_Oneway)) == 0) {
7741     Results.AddResult("bycopy");
7742     Results.AddResult("byref");
7743     Results.AddResult("oneway");
7744   }
7745   if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
7746     Results.AddResult("nonnull");
7747     Results.AddResult("nullable");
7748     Results.AddResult("null_unspecified");
7749   }
7750 
7751   // If we're completing the return type of an Objective-C method and the
7752   // identifier IBAction refers to a macro, provide a completion item for
7753   // an action, e.g.,
7754   //   IBAction)<#selector#>:(id)sender
7755   if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
7756       PP.isMacroDefined("IBAction")) {
7757     CodeCompletionBuilder Builder(Results.getAllocator(),
7758                                   Results.getCodeCompletionTUInfo(),
7759                                   CCP_CodePattern, CXAvailability_Available);
7760     Builder.AddTypedTextChunk("IBAction");
7761     Builder.AddChunk(CodeCompletionString::CK_RightParen);
7762     Builder.AddPlaceholderChunk("selector");
7763     Builder.AddChunk(CodeCompletionString::CK_Colon);
7764     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7765     Builder.AddTextChunk("id");
7766     Builder.AddChunk(CodeCompletionString::CK_RightParen);
7767     Builder.AddTextChunk("sender");
7768     Results.AddResult(CodeCompletionResult(Builder.TakeString()));
7769   }
7770 
7771   // If we're completing the return type, provide 'instancetype'.
7772   if (!IsParameter) {
7773     Results.AddResult(CodeCompletionResult("instancetype"));
7774   }
7775 
7776   // Add various builtin type names and specifiers.
7777   AddOrdinaryNameResults(PCC_Type, S, *this, Results);
7778   Results.ExitScope();
7779 
7780   // Add the various type names
7781   Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
7782   CodeCompletionDeclConsumer Consumer(Results, CurContext);
7783   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
7784                      CodeCompleter->includeGlobals(),
7785                      CodeCompleter->loadExternal());
7786 
7787   if (CodeCompleter->includeMacros())
7788     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
7789 
7790   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7791                             Results.data(), Results.size());
7792 }
7793 
7794 /// When we have an expression with type "id", we may assume
7795 /// that it has some more-specific class type based on knowledge of
7796 /// common uses of Objective-C. This routine returns that class type,
7797 /// or NULL if no better result could be determined.
7798 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
7799   auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
7800   if (!Msg)
7801     return nullptr;
7802 
7803   Selector Sel = Msg->getSelector();
7804   if (Sel.isNull())
7805     return nullptr;
7806 
7807   IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
7808   if (!Id)
7809     return nullptr;
7810 
7811   ObjCMethodDecl *Method = Msg->getMethodDecl();
7812   if (!Method)
7813     return nullptr;
7814 
7815   // Determine the class that we're sending the message to.
7816   ObjCInterfaceDecl *IFace = nullptr;
7817   switch (Msg->getReceiverKind()) {
7818   case ObjCMessageExpr::Class:
7819     if (const ObjCObjectType *ObjType =
7820             Msg->getClassReceiver()->getAs<ObjCObjectType>())
7821       IFace = ObjType->getInterface();
7822     break;
7823 
7824   case ObjCMessageExpr::Instance: {
7825     QualType T = Msg->getInstanceReceiver()->getType();
7826     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
7827       IFace = Ptr->getInterfaceDecl();
7828     break;
7829   }
7830 
7831   case ObjCMessageExpr::SuperInstance:
7832   case ObjCMessageExpr::SuperClass:
7833     break;
7834   }
7835 
7836   if (!IFace)
7837     return nullptr;
7838 
7839   ObjCInterfaceDecl *Super = IFace->getSuperClass();
7840   if (Method->isInstanceMethod())
7841     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7842         .Case("retain", IFace)
7843         .Case("strong", IFace)
7844         .Case("autorelease", IFace)
7845         .Case("copy", IFace)
7846         .Case("copyWithZone", IFace)
7847         .Case("mutableCopy", IFace)
7848         .Case("mutableCopyWithZone", IFace)
7849         .Case("awakeFromCoder", IFace)
7850         .Case("replacementObjectFromCoder", IFace)
7851         .Case("class", IFace)
7852         .Case("classForCoder", IFace)
7853         .Case("superclass", Super)
7854         .Default(nullptr);
7855 
7856   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7857       .Case("new", IFace)
7858       .Case("alloc", IFace)
7859       .Case("allocWithZone", IFace)
7860       .Case("class", IFace)
7861       .Case("superclass", Super)
7862       .Default(nullptr);
7863 }
7864 
7865 // Add a special completion for a message send to "super", which fills in the
7866 // most likely case of forwarding all of our arguments to the superclass
7867 // function.
7868 ///
7869 /// \param S The semantic analysis object.
7870 ///
7871 /// \param NeedSuperKeyword Whether we need to prefix this completion with
7872 /// the "super" keyword. Otherwise, we just need to provide the arguments.
7873 ///
7874 /// \param SelIdents The identifiers in the selector that have already been
7875 /// provided as arguments for a send to "super".
7876 ///
7877 /// \param Results The set of results to augment.
7878 ///
7879 /// \returns the Objective-C method declaration that would be invoked by
7880 /// this "super" completion. If NULL, no completion was added.
7881 static ObjCMethodDecl *
7882 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
7883                        ArrayRef<IdentifierInfo *> SelIdents,
7884                        ResultBuilder &Results) {
7885   ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
7886   if (!CurMethod)
7887     return nullptr;
7888 
7889   ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
7890   if (!Class)
7891     return nullptr;
7892 
7893   // Try to find a superclass method with the same selector.
7894   ObjCMethodDecl *SuperMethod = nullptr;
7895   while ((Class = Class->getSuperClass()) && !SuperMethod) {
7896     // Check in the class
7897     SuperMethod = Class->getMethod(CurMethod->getSelector(),
7898                                    CurMethod->isInstanceMethod());
7899 
7900     // Check in categories or class extensions.
7901     if (!SuperMethod) {
7902       for (const auto *Cat : Class->known_categories()) {
7903         if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
7904                                           CurMethod->isInstanceMethod())))
7905           break;
7906       }
7907     }
7908   }
7909 
7910   if (!SuperMethod)
7911     return nullptr;
7912 
7913   // Check whether the superclass method has the same signature.
7914   if (CurMethod->param_size() != SuperMethod->param_size() ||
7915       CurMethod->isVariadic() != SuperMethod->isVariadic())
7916     return nullptr;
7917 
7918   for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
7919                                       CurPEnd = CurMethod->param_end(),
7920                                       SuperP = SuperMethod->param_begin();
7921        CurP != CurPEnd; ++CurP, ++SuperP) {
7922     // Make sure the parameter types are compatible.
7923     if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
7924                                           (*SuperP)->getType()))
7925       return nullptr;
7926 
7927     // Make sure we have a parameter name to forward!
7928     if (!(*CurP)->getIdentifier())
7929       return nullptr;
7930   }
7931 
7932   // We have a superclass method. Now, form the send-to-super completion.
7933   CodeCompletionBuilder Builder(Results.getAllocator(),
7934                                 Results.getCodeCompletionTUInfo());
7935 
7936   // Give this completion a return type.
7937   AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
7938                      Results.getCompletionContext().getBaseType(), Builder);
7939 
7940   // If we need the "super" keyword, add it (plus some spacing).
7941   if (NeedSuperKeyword) {
7942     Builder.AddTypedTextChunk("super");
7943     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7944   }
7945 
7946   Selector Sel = CurMethod->getSelector();
7947   if (Sel.isUnarySelector()) {
7948     if (NeedSuperKeyword)
7949       Builder.AddTextChunk(
7950           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7951     else
7952       Builder.AddTypedTextChunk(
7953           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7954   } else {
7955     ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
7956     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
7957       if (I > SelIdents.size())
7958         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7959 
7960       if (I < SelIdents.size())
7961         Builder.AddInformativeChunk(
7962             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7963       else if (NeedSuperKeyword || I > SelIdents.size()) {
7964         Builder.AddTextChunk(
7965             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7966         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
7967             (*CurP)->getIdentifier()->getName()));
7968       } else {
7969         Builder.AddTypedTextChunk(
7970             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7971         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
7972             (*CurP)->getIdentifier()->getName()));
7973       }
7974     }
7975   }
7976 
7977   Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
7978                                          CCP_SuperCompletion));
7979   return SuperMethod;
7980 }
7981 
7982 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
7983   typedef CodeCompletionResult Result;
7984   ResultBuilder Results(
7985       *this, CodeCompleter->getAllocator(),
7986       CodeCompleter->getCodeCompletionTUInfo(),
7987       CodeCompletionContext::CCC_ObjCMessageReceiver,
7988       getLangOpts().CPlusPlus11
7989           ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
7990           : &ResultBuilder::IsObjCMessageReceiver);
7991 
7992   CodeCompletionDeclConsumer Consumer(Results, CurContext);
7993   Results.EnterNewScope();
7994   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
7995                      CodeCompleter->includeGlobals(),
7996                      CodeCompleter->loadExternal());
7997 
7998   // If we are in an Objective-C method inside a class that has a superclass,
7999   // add "super" as an option.
8000   if (ObjCMethodDecl *Method = getCurMethodDecl())
8001     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
8002       if (Iface->getSuperClass()) {
8003         Results.AddResult(Result("super"));
8004 
8005         AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, std::nullopt,
8006                                Results);
8007       }
8008 
8009   if (getLangOpts().CPlusPlus11)
8010     addThisCompletion(*this, Results);
8011 
8012   Results.ExitScope();
8013 
8014   if (CodeCompleter->includeMacros())
8015     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
8016   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8017                             Results.data(), Results.size());
8018 }
8019 
8020 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
8021                                         ArrayRef<IdentifierInfo *> SelIdents,
8022                                         bool AtArgumentExpression) {
8023   ObjCInterfaceDecl *CDecl = nullptr;
8024   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
8025     // Figure out which interface we're in.
8026     CDecl = CurMethod->getClassInterface();
8027     if (!CDecl)
8028       return;
8029 
8030     // Find the superclass of this class.
8031     CDecl = CDecl->getSuperClass();
8032     if (!CDecl)
8033       return;
8034 
8035     if (CurMethod->isInstanceMethod()) {
8036       // We are inside an instance method, which means that the message
8037       // send [super ...] is actually calling an instance method on the
8038       // current object.
8039       return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
8040                                              AtArgumentExpression, CDecl);
8041     }
8042 
8043     // Fall through to send to the superclass in CDecl.
8044   } else {
8045     // "super" may be the name of a type or variable. Figure out which
8046     // it is.
8047     IdentifierInfo *Super = getSuperIdentifier();
8048     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName);
8049     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
8050       // "super" names an interface. Use it.
8051     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
8052       if (const ObjCObjectType *Iface =
8053               Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
8054         CDecl = Iface->getInterface();
8055     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
8056       // "super" names an unresolved type; we can't be more specific.
8057     } else {
8058       // Assume that "super" names some kind of value and parse that way.
8059       CXXScopeSpec SS;
8060       SourceLocation TemplateKWLoc;
8061       UnqualifiedId id;
8062       id.setIdentifier(Super, SuperLoc);
8063       ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
8064                                                /*HasTrailingLParen=*/false,
8065                                                /*IsAddressOfOperand=*/false);
8066       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
8067                                              SelIdents, AtArgumentExpression);
8068     }
8069 
8070     // Fall through
8071   }
8072 
8073   ParsedType Receiver;
8074   if (CDecl)
8075     Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
8076   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
8077                                       AtArgumentExpression,
8078                                       /*IsSuper=*/true);
8079 }
8080 
8081 /// Given a set of code-completion results for the argument of a message
8082 /// send, determine the preferred type (if any) for that argument expression.
8083 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
8084                                                        unsigned NumSelIdents) {
8085   typedef CodeCompletionResult Result;
8086   ASTContext &Context = Results.getSema().Context;
8087 
8088   QualType PreferredType;
8089   unsigned BestPriority = CCP_Unlikely * 2;
8090   Result *ResultsData = Results.data();
8091   for (unsigned I = 0, N = Results.size(); I != N; ++I) {
8092     Result &R = ResultsData[I];
8093     if (R.Kind == Result::RK_Declaration &&
8094         isa<ObjCMethodDecl>(R.Declaration)) {
8095       if (R.Priority <= BestPriority) {
8096         const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
8097         if (NumSelIdents <= Method->param_size()) {
8098           QualType MyPreferredType =
8099               Method->parameters()[NumSelIdents - 1]->getType();
8100           if (R.Priority < BestPriority || PreferredType.isNull()) {
8101             BestPriority = R.Priority;
8102             PreferredType = MyPreferredType;
8103           } else if (!Context.hasSameUnqualifiedType(PreferredType,
8104                                                      MyPreferredType)) {
8105             PreferredType = QualType();
8106           }
8107         }
8108       }
8109     }
8110   }
8111 
8112   return PreferredType;
8113 }
8114 
8115 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
8116                                        ParsedType Receiver,
8117                                        ArrayRef<IdentifierInfo *> SelIdents,
8118                                        bool AtArgumentExpression, bool IsSuper,
8119                                        ResultBuilder &Results) {
8120   typedef CodeCompletionResult Result;
8121   ObjCInterfaceDecl *CDecl = nullptr;
8122 
8123   // If the given name refers to an interface type, retrieve the
8124   // corresponding declaration.
8125   if (Receiver) {
8126     QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
8127     if (!T.isNull())
8128       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
8129         CDecl = Interface->getInterface();
8130   }
8131 
8132   // Add all of the factory methods in this Objective-C class, its protocols,
8133   // superclasses, categories, implementation, etc.
8134   Results.EnterNewScope();
8135 
8136   // If this is a send-to-super, try to add the special "super" send
8137   // completion.
8138   if (IsSuper) {
8139     if (ObjCMethodDecl *SuperMethod =
8140             AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
8141       Results.Ignore(SuperMethod);
8142   }
8143 
8144   // If we're inside an Objective-C method definition, prefer its selector to
8145   // others.
8146   if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
8147     Results.setPreferredSelector(CurMethod->getSelector());
8148 
8149   VisitedSelectorSet Selectors;
8150   if (CDecl)
8151     AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
8152                    Selectors, AtArgumentExpression, Results);
8153   else {
8154     // We're messaging "id" as a type; provide all class/factory methods.
8155 
8156     // If we have an external source, load the entire class method
8157     // pool from the AST file.
8158     if (SemaRef.getExternalSource()) {
8159       for (uint32_t I = 0,
8160                     N = SemaRef.getExternalSource()->GetNumExternalSelectors();
8161            I != N; ++I) {
8162         Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
8163         if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
8164           continue;
8165 
8166         SemaRef.ReadMethodPool(Sel);
8167       }
8168     }
8169 
8170     for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
8171                                           MEnd = SemaRef.MethodPool.end();
8172          M != MEnd; ++M) {
8173       for (ObjCMethodList *MethList = &M->second.second;
8174            MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8175         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8176           continue;
8177 
8178         Result R(MethList->getMethod(),
8179                  Results.getBasePriority(MethList->getMethod()), nullptr);
8180         R.StartParameter = SelIdents.size();
8181         R.AllParametersAreInformative = false;
8182         Results.MaybeAddResult(R, SemaRef.CurContext);
8183       }
8184     }
8185   }
8186 
8187   Results.ExitScope();
8188 }
8189 
8190 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8191                                         ArrayRef<IdentifierInfo *> SelIdents,
8192                                         bool AtArgumentExpression,
8193                                         bool IsSuper) {
8194 
8195   QualType T = this->GetTypeFromParser(Receiver);
8196 
8197   ResultBuilder Results(
8198       *this, CodeCompleter->getAllocator(),
8199       CodeCompleter->getCodeCompletionTUInfo(),
8200       CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T,
8201                             SelIdents));
8202 
8203   AddClassMessageCompletions(*this, S, Receiver, SelIdents,
8204                              AtArgumentExpression, IsSuper, Results);
8205 
8206   // If we're actually at the argument expression (rather than prior to the
8207   // selector), we're actually performing code completion for an expression.
8208   // Determine whether we have a single, best method. If so, we can
8209   // code-complete the expression using the corresponding parameter type as
8210   // our preferred type, improving completion results.
8211   if (AtArgumentExpression) {
8212     QualType PreferredType =
8213         getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8214     if (PreferredType.isNull())
8215       CodeCompleteOrdinaryName(S, PCC_Expression);
8216     else
8217       CodeCompleteExpression(S, PreferredType);
8218     return;
8219   }
8220 
8221   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8222                             Results.data(), Results.size());
8223 }
8224 
8225 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8226                                            ArrayRef<IdentifierInfo *> SelIdents,
8227                                            bool AtArgumentExpression,
8228                                            ObjCInterfaceDecl *Super) {
8229   typedef CodeCompletionResult Result;
8230 
8231   Expr *RecExpr = static_cast<Expr *>(Receiver);
8232 
8233   // If necessary, apply function/array conversion to the receiver.
8234   // C99 6.7.5.3p[7,8].
8235   if (RecExpr) {
8236     ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
8237     if (Conv.isInvalid()) // conversion failed. bail.
8238       return;
8239     RecExpr = Conv.get();
8240   }
8241   QualType ReceiverType = RecExpr
8242                               ? RecExpr->getType()
8243                               : Super ? Context.getObjCObjectPointerType(
8244                                             Context.getObjCInterfaceType(Super))
8245                                       : Context.getObjCIdType();
8246 
8247   // If we're messaging an expression with type "id" or "Class", check
8248   // whether we know something special about the receiver that allows
8249   // us to assume a more-specific receiver type.
8250   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
8251     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
8252       if (ReceiverType->isObjCClassType())
8253         return CodeCompleteObjCClassMessage(
8254             S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents,
8255             AtArgumentExpression, Super);
8256 
8257       ReceiverType =
8258           Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace));
8259     }
8260   } else if (RecExpr && getLangOpts().CPlusPlus) {
8261     ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
8262     if (Conv.isUsable()) {
8263       RecExpr = Conv.get();
8264       ReceiverType = RecExpr->getType();
8265     }
8266   }
8267 
8268   // Build the set of methods we can see.
8269   ResultBuilder Results(
8270       *this, CodeCompleter->getAllocator(),
8271       CodeCompleter->getCodeCompletionTUInfo(),
8272       CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
8273                             ReceiverType, SelIdents));
8274 
8275   Results.EnterNewScope();
8276 
8277   // If this is a send-to-super, try to add the special "super" send
8278   // completion.
8279   if (Super) {
8280     if (ObjCMethodDecl *SuperMethod =
8281             AddSuperSendCompletion(*this, false, SelIdents, Results))
8282       Results.Ignore(SuperMethod);
8283   }
8284 
8285   // If we're inside an Objective-C method definition, prefer its selector to
8286   // others.
8287   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
8288     Results.setPreferredSelector(CurMethod->getSelector());
8289 
8290   // Keep track of the selectors we've already added.
8291   VisitedSelectorSet Selectors;
8292 
8293   // Handle messages to Class. This really isn't a message to an instance
8294   // method, so we treat it the same way we would treat a message send to a
8295   // class method.
8296   if (ReceiverType->isObjCClassType() ||
8297       ReceiverType->isObjCQualifiedClassType()) {
8298     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
8299       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
8300         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext,
8301                        Selectors, AtArgumentExpression, Results);
8302     }
8303   }
8304   // Handle messages to a qualified ID ("id<foo>").
8305   else if (const ObjCObjectPointerType *QualID =
8306                ReceiverType->getAsObjCQualifiedIdType()) {
8307     // Search protocols for instance methods.
8308     for (auto *I : QualID->quals())
8309       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
8310                      AtArgumentExpression, Results);
8311   }
8312   // Handle messages to a pointer to interface type.
8313   else if (const ObjCObjectPointerType *IFacePtr =
8314                ReceiverType->getAsObjCInterfacePointerType()) {
8315     // Search the class, its superclasses, etc., for instance methods.
8316     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
8317                    CurContext, Selectors, AtArgumentExpression, Results);
8318 
8319     // Search protocols for instance methods.
8320     for (auto *I : IFacePtr->quals())
8321       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
8322                      AtArgumentExpression, Results);
8323   }
8324   // Handle messages to "id".
8325   else if (ReceiverType->isObjCIdType()) {
8326     // We're messaging "id", so provide all instance methods we know
8327     // about as code-completion results.
8328 
8329     // If we have an external source, load the entire class method
8330     // pool from the AST file.
8331     if (ExternalSource) {
8332       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
8333            I != N; ++I) {
8334         Selector Sel = ExternalSource->GetExternalSelector(I);
8335         if (Sel.isNull() || MethodPool.count(Sel))
8336           continue;
8337 
8338         ReadMethodPool(Sel);
8339       }
8340     }
8341 
8342     for (GlobalMethodPool::iterator M = MethodPool.begin(),
8343                                     MEnd = MethodPool.end();
8344          M != MEnd; ++M) {
8345       for (ObjCMethodList *MethList = &M->second.first;
8346            MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8347         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8348           continue;
8349 
8350         if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
8351           continue;
8352 
8353         Result R(MethList->getMethod(),
8354                  Results.getBasePriority(MethList->getMethod()), nullptr);
8355         R.StartParameter = SelIdents.size();
8356         R.AllParametersAreInformative = false;
8357         Results.MaybeAddResult(R, CurContext);
8358       }
8359     }
8360   }
8361   Results.ExitScope();
8362 
8363   // If we're actually at the argument expression (rather than prior to the
8364   // selector), we're actually performing code completion for an expression.
8365   // Determine whether we have a single, best method. If so, we can
8366   // code-complete the expression using the corresponding parameter type as
8367   // our preferred type, improving completion results.
8368   if (AtArgumentExpression) {
8369     QualType PreferredType =
8370         getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8371     if (PreferredType.isNull())
8372       CodeCompleteOrdinaryName(S, PCC_Expression);
8373     else
8374       CodeCompleteExpression(S, PreferredType);
8375     return;
8376   }
8377 
8378   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8379                             Results.data(), Results.size());
8380 }
8381 
8382 void Sema::CodeCompleteObjCForCollection(Scope *S,
8383                                          DeclGroupPtrTy IterationVar) {
8384   CodeCompleteExpressionData Data;
8385   Data.ObjCCollection = true;
8386 
8387   if (IterationVar.getAsOpaquePtr()) {
8388     DeclGroupRef DG = IterationVar.get();
8389     for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
8390       if (*I)
8391         Data.IgnoreDecls.push_back(*I);
8392     }
8393   }
8394 
8395   CodeCompleteExpression(S, Data);
8396 }
8397 
8398 void Sema::CodeCompleteObjCSelector(Scope *S,
8399                                     ArrayRef<IdentifierInfo *> SelIdents) {
8400   // If we have an external source, load the entire class method
8401   // pool from the AST file.
8402   if (ExternalSource) {
8403     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
8404          ++I) {
8405       Selector Sel = ExternalSource->GetExternalSelector(I);
8406       if (Sel.isNull() || MethodPool.count(Sel))
8407         continue;
8408 
8409       ReadMethodPool(Sel);
8410     }
8411   }
8412 
8413   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8414                         CodeCompleter->getCodeCompletionTUInfo(),
8415                         CodeCompletionContext::CCC_SelectorName);
8416   Results.EnterNewScope();
8417   for (GlobalMethodPool::iterator M = MethodPool.begin(),
8418                                   MEnd = MethodPool.end();
8419        M != MEnd; ++M) {
8420 
8421     Selector Sel = M->first;
8422     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
8423       continue;
8424 
8425     CodeCompletionBuilder Builder(Results.getAllocator(),
8426                                   Results.getCodeCompletionTUInfo());
8427     if (Sel.isUnarySelector()) {
8428       Builder.AddTypedTextChunk(
8429           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
8430       Results.AddResult(Builder.TakeString());
8431       continue;
8432     }
8433 
8434     std::string Accumulator;
8435     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
8436       if (I == SelIdents.size()) {
8437         if (!Accumulator.empty()) {
8438           Builder.AddInformativeChunk(
8439               Builder.getAllocator().CopyString(Accumulator));
8440           Accumulator.clear();
8441         }
8442       }
8443 
8444       Accumulator += Sel.getNameForSlot(I);
8445       Accumulator += ':';
8446     }
8447     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator));
8448     Results.AddResult(Builder.TakeString());
8449   }
8450   Results.ExitScope();
8451 
8452   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8453                             Results.data(), Results.size());
8454 }
8455 
8456 /// Add all of the protocol declarations that we find in the given
8457 /// (translation unit) context.
8458 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
8459                                bool OnlyForwardDeclarations,
8460                                ResultBuilder &Results) {
8461   typedef CodeCompletionResult Result;
8462 
8463   for (const auto *D : Ctx->decls()) {
8464     // Record any protocols we find.
8465     if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
8466       if (!OnlyForwardDeclarations || !Proto->hasDefinition())
8467         Results.AddResult(
8468             Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext,
8469             nullptr, false);
8470   }
8471 }
8472 
8473 void Sema::CodeCompleteObjCProtocolReferences(
8474     ArrayRef<IdentifierLocPair> Protocols) {
8475   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8476                         CodeCompleter->getCodeCompletionTUInfo(),
8477                         CodeCompletionContext::CCC_ObjCProtocolName);
8478 
8479   if (CodeCompleter->includeGlobals()) {
8480     Results.EnterNewScope();
8481 
8482     // Tell the result set to ignore all of the protocols we have
8483     // already seen.
8484     // FIXME: This doesn't work when caching code-completion results.
8485     for (const IdentifierLocPair &Pair : Protocols)
8486       if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second))
8487         Results.Ignore(Protocol);
8488 
8489     // Add all protocols.
8490     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
8491                        Results);
8492 
8493     Results.ExitScope();
8494   }
8495 
8496   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8497                             Results.data(), Results.size());
8498 }
8499 
8500 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
8501   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8502                         CodeCompleter->getCodeCompletionTUInfo(),
8503                         CodeCompletionContext::CCC_ObjCProtocolName);
8504 
8505   if (CodeCompleter->includeGlobals()) {
8506     Results.EnterNewScope();
8507 
8508     // Add all protocols.
8509     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
8510                        Results);
8511 
8512     Results.ExitScope();
8513   }
8514 
8515   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8516                             Results.data(), Results.size());
8517 }
8518 
8519 /// Add all of the Objective-C interface declarations that we find in
8520 /// the given (translation unit) context.
8521 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
8522                                 bool OnlyForwardDeclarations,
8523                                 bool OnlyUnimplemented,
8524                                 ResultBuilder &Results) {
8525   typedef CodeCompletionResult Result;
8526 
8527   for (const auto *D : Ctx->decls()) {
8528     // Record any interfaces we find.
8529     if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
8530       if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
8531           (!OnlyUnimplemented || !Class->getImplementation()))
8532         Results.AddResult(
8533             Result(Class, Results.getBasePriority(Class), nullptr), CurContext,
8534             nullptr, false);
8535   }
8536 }
8537 
8538 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
8539   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8540                         CodeCompleter->getCodeCompletionTUInfo(),
8541                         CodeCompletionContext::CCC_ObjCInterfaceName);
8542   Results.EnterNewScope();
8543 
8544   if (CodeCompleter->includeGlobals()) {
8545     // Add all classes.
8546     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8547                         false, Results);
8548   }
8549 
8550   Results.ExitScope();
8551 
8552   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8553                             Results.data(), Results.size());
8554 }
8555 
8556 void Sema::CodeCompleteObjCClassForwardDecl(Scope *S) {
8557   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8558                         CodeCompleter->getCodeCompletionTUInfo(),
8559                         CodeCompletionContext::CCC_ObjCClassForwardDecl);
8560   Results.EnterNewScope();
8561 
8562   if (CodeCompleter->includeGlobals()) {
8563     // Add all classes.
8564     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8565                         false, Results);
8566   }
8567 
8568   Results.ExitScope();
8569 
8570   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8571                             Results.data(), Results.size());
8572 }
8573 
8574 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
8575                                       SourceLocation ClassNameLoc) {
8576   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8577                         CodeCompleter->getCodeCompletionTUInfo(),
8578                         CodeCompletionContext::CCC_ObjCInterfaceName);
8579   Results.EnterNewScope();
8580 
8581   // Make sure that we ignore the class we're currently defining.
8582   NamedDecl *CurClass =
8583       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8584   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
8585     Results.Ignore(CurClass);
8586 
8587   if (CodeCompleter->includeGlobals()) {
8588     // Add all classes.
8589     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8590                         false, Results);
8591   }
8592 
8593   Results.ExitScope();
8594 
8595   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8596                             Results.data(), Results.size());
8597 }
8598 
8599 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
8600   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8601                         CodeCompleter->getCodeCompletionTUInfo(),
8602                         CodeCompletionContext::CCC_ObjCImplementation);
8603   Results.EnterNewScope();
8604 
8605   if (CodeCompleter->includeGlobals()) {
8606     // Add all unimplemented classes.
8607     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8608                         true, Results);
8609   }
8610 
8611   Results.ExitScope();
8612 
8613   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8614                             Results.data(), Results.size());
8615 }
8616 
8617 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
8618                                              IdentifierInfo *ClassName,
8619                                              SourceLocation ClassNameLoc) {
8620   typedef CodeCompletionResult Result;
8621 
8622   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8623                         CodeCompleter->getCodeCompletionTUInfo(),
8624                         CodeCompletionContext::CCC_ObjCCategoryName);
8625 
8626   // Ignore any categories we find that have already been implemented by this
8627   // interface.
8628   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
8629   NamedDecl *CurClass =
8630       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8631   if (ObjCInterfaceDecl *Class =
8632           dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) {
8633     for (const auto *Cat : Class->visible_categories())
8634       CategoryNames.insert(Cat->getIdentifier());
8635   }
8636 
8637   // Add all of the categories we know about.
8638   Results.EnterNewScope();
8639   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
8640   for (const auto *D : TU->decls())
8641     if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
8642       if (CategoryNames.insert(Category->getIdentifier()).second)
8643         Results.AddResult(
8644             Result(Category, Results.getBasePriority(Category), nullptr),
8645             CurContext, nullptr, false);
8646   Results.ExitScope();
8647 
8648   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8649                             Results.data(), Results.size());
8650 }
8651 
8652 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
8653                                                   IdentifierInfo *ClassName,
8654                                                   SourceLocation ClassNameLoc) {
8655   typedef CodeCompletionResult Result;
8656 
8657   // Find the corresponding interface. If we couldn't find the interface, the
8658   // program itself is ill-formed. However, we'll try to be helpful still by
8659   // providing the list of all of the categories we know about.
8660   NamedDecl *CurClass =
8661       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8662   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
8663   if (!Class)
8664     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
8665 
8666   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8667                         CodeCompleter->getCodeCompletionTUInfo(),
8668                         CodeCompletionContext::CCC_ObjCCategoryName);
8669 
8670   // Add all of the categories that have corresponding interface
8671   // declarations in this class and any of its superclasses, except for
8672   // already-implemented categories in the class itself.
8673   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
8674   Results.EnterNewScope();
8675   bool IgnoreImplemented = true;
8676   while (Class) {
8677     for (const auto *Cat : Class->visible_categories()) {
8678       if ((!IgnoreImplemented || !Cat->getImplementation()) &&
8679           CategoryNames.insert(Cat->getIdentifier()).second)
8680         Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
8681                           CurContext, nullptr, false);
8682     }
8683 
8684     Class = Class->getSuperClass();
8685     IgnoreImplemented = false;
8686   }
8687   Results.ExitScope();
8688 
8689   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8690                             Results.data(), Results.size());
8691 }
8692 
8693 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
8694   CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
8695   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8696                         CodeCompleter->getCodeCompletionTUInfo(), CCContext);
8697 
8698   // Figure out where this @synthesize lives.
8699   ObjCContainerDecl *Container =
8700       dyn_cast_or_null<ObjCContainerDecl>(CurContext);
8701   if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8702                      !isa<ObjCCategoryImplDecl>(Container)))
8703     return;
8704 
8705   // Ignore any properties that have already been implemented.
8706   Container = getContainerDef(Container);
8707   for (const auto *D : Container->decls())
8708     if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
8709       Results.Ignore(PropertyImpl->getPropertyDecl());
8710 
8711   // Add any properties that we find.
8712   AddedPropertiesSet AddedProperties;
8713   Results.EnterNewScope();
8714   if (ObjCImplementationDecl *ClassImpl =
8715           dyn_cast<ObjCImplementationDecl>(Container))
8716     AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
8717                       /*AllowNullaryMethods=*/false, CurContext,
8718                       AddedProperties, Results);
8719   else
8720     AddObjCProperties(CCContext,
8721                       cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
8722                       false, /*AllowNullaryMethods=*/false, CurContext,
8723                       AddedProperties, Results);
8724   Results.ExitScope();
8725 
8726   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8727                             Results.data(), Results.size());
8728 }
8729 
8730 void Sema::CodeCompleteObjCPropertySynthesizeIvar(
8731     Scope *S, IdentifierInfo *PropertyName) {
8732   typedef CodeCompletionResult Result;
8733   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8734                         CodeCompleter->getCodeCompletionTUInfo(),
8735                         CodeCompletionContext::CCC_Other);
8736 
8737   // Figure out where this @synthesize lives.
8738   ObjCContainerDecl *Container =
8739       dyn_cast_or_null<ObjCContainerDecl>(CurContext);
8740   if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8741                      !isa<ObjCCategoryImplDecl>(Container)))
8742     return;
8743 
8744   // Figure out which interface we're looking into.
8745   ObjCInterfaceDecl *Class = nullptr;
8746   if (ObjCImplementationDecl *ClassImpl =
8747           dyn_cast<ObjCImplementationDecl>(Container))
8748     Class = ClassImpl->getClassInterface();
8749   else
8750     Class = cast<ObjCCategoryImplDecl>(Container)
8751                 ->getCategoryDecl()
8752                 ->getClassInterface();
8753 
8754   // Determine the type of the property we're synthesizing.
8755   QualType PropertyType = Context.getObjCIdType();
8756   if (Class) {
8757     if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
8758             PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
8759       PropertyType =
8760           Property->getType().getNonReferenceType().getUnqualifiedType();
8761 
8762       // Give preference to ivars
8763       Results.setPreferredType(PropertyType);
8764     }
8765   }
8766 
8767   // Add all of the instance variables in this class and its superclasses.
8768   Results.EnterNewScope();
8769   bool SawSimilarlyNamedIvar = false;
8770   std::string NameWithPrefix;
8771   NameWithPrefix += '_';
8772   NameWithPrefix += PropertyName->getName();
8773   std::string NameWithSuffix = PropertyName->getName().str();
8774   NameWithSuffix += '_';
8775   for (; Class; Class = Class->getSuperClass()) {
8776     for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
8777          Ivar = Ivar->getNextIvar()) {
8778       Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
8779                         CurContext, nullptr, false);
8780 
8781       // Determine whether we've seen an ivar with a name similar to the
8782       // property.
8783       if ((PropertyName == Ivar->getIdentifier() ||
8784            NameWithPrefix == Ivar->getName() ||
8785            NameWithSuffix == Ivar->getName())) {
8786         SawSimilarlyNamedIvar = true;
8787 
8788         // Reduce the priority of this result by one, to give it a slight
8789         // advantage over other results whose names don't match so closely.
8790         if (Results.size() &&
8791             Results.data()[Results.size() - 1].Kind ==
8792                 CodeCompletionResult::RK_Declaration &&
8793             Results.data()[Results.size() - 1].Declaration == Ivar)
8794           Results.data()[Results.size() - 1].Priority--;
8795       }
8796     }
8797   }
8798 
8799   if (!SawSimilarlyNamedIvar) {
8800     // Create ivar result _propName, that the user can use to synthesize
8801     // an ivar of the appropriate type.
8802     unsigned Priority = CCP_MemberDeclaration + 1;
8803     typedef CodeCompletionResult Result;
8804     CodeCompletionAllocator &Allocator = Results.getAllocator();
8805     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
8806                                   Priority, CXAvailability_Available);
8807 
8808     PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
8809     Builder.AddResultTypeChunk(
8810         GetCompletionTypeString(PropertyType, Context, Policy, Allocator));
8811     Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
8812     Results.AddResult(
8813         Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl));
8814   }
8815 
8816   Results.ExitScope();
8817 
8818   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8819                             Results.data(), Results.size());
8820 }
8821 
8822 // Mapping from selectors to the methods that implement that selector, along
8823 // with the "in original class" flag.
8824 typedef llvm::DenseMap<Selector,
8825                        llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>>
8826     KnownMethodsMap;
8827 
8828 /// Find all of the methods that reside in the given container
8829 /// (and its superclasses, protocols, etc.) that meet the given
8830 /// criteria. Insert those methods into the map of known methods,
8831 /// indexed by selector so they can be easily found.
8832 static void FindImplementableMethods(ASTContext &Context,
8833                                      ObjCContainerDecl *Container,
8834                                      std::optional<bool> WantInstanceMethods,
8835                                      QualType ReturnType,
8836                                      KnownMethodsMap &KnownMethods,
8837                                      bool InOriginalClass = true) {
8838   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
8839     // Make sure we have a definition; that's what we'll walk.
8840     if (!IFace->hasDefinition())
8841       return;
8842 
8843     IFace = IFace->getDefinition();
8844     Container = IFace;
8845 
8846     const ObjCList<ObjCProtocolDecl> &Protocols =
8847         IFace->getReferencedProtocols();
8848     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8849                                               E = Protocols.end();
8850          I != E; ++I)
8851       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8852                                KnownMethods, InOriginalClass);
8853 
8854     // Add methods from any class extensions and categories.
8855     for (auto *Cat : IFace->visible_categories()) {
8856       FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
8857                                KnownMethods, false);
8858     }
8859 
8860     // Visit the superclass.
8861     if (IFace->getSuperClass())
8862       FindImplementableMethods(Context, IFace->getSuperClass(),
8863                                WantInstanceMethods, ReturnType, KnownMethods,
8864                                false);
8865   }
8866 
8867   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
8868     // Recurse into protocols.
8869     const ObjCList<ObjCProtocolDecl> &Protocols =
8870         Category->getReferencedProtocols();
8871     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8872                                               E = Protocols.end();
8873          I != E; ++I)
8874       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8875                                KnownMethods, InOriginalClass);
8876 
8877     // If this category is the original class, jump to the interface.
8878     if (InOriginalClass && Category->getClassInterface())
8879       FindImplementableMethods(Context, Category->getClassInterface(),
8880                                WantInstanceMethods, ReturnType, KnownMethods,
8881                                false);
8882   }
8883 
8884   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
8885     // Make sure we have a definition; that's what we'll walk.
8886     if (!Protocol->hasDefinition())
8887       return;
8888     Protocol = Protocol->getDefinition();
8889     Container = Protocol;
8890 
8891     // Recurse into protocols.
8892     const ObjCList<ObjCProtocolDecl> &Protocols =
8893         Protocol->getReferencedProtocols();
8894     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8895                                               E = Protocols.end();
8896          I != E; ++I)
8897       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8898                                KnownMethods, false);
8899   }
8900 
8901   // Add methods in this container. This operation occurs last because
8902   // we want the methods from this container to override any methods
8903   // we've previously seen with the same selector.
8904   for (auto *M : Container->methods()) {
8905     if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
8906       if (!ReturnType.isNull() &&
8907           !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
8908         continue;
8909 
8910       KnownMethods[M->getSelector()] =
8911           KnownMethodsMap::mapped_type(M, InOriginalClass);
8912     }
8913   }
8914 }
8915 
8916 /// Add the parenthesized return or parameter type chunk to a code
8917 /// completion string.
8918 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals,
8919                                     ASTContext &Context,
8920                                     const PrintingPolicy &Policy,
8921                                     CodeCompletionBuilder &Builder) {
8922   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8923   std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
8924   if (!Quals.empty())
8925     Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
8926   Builder.AddTextChunk(
8927       GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator()));
8928   Builder.AddChunk(CodeCompletionString::CK_RightParen);
8929 }
8930 
8931 /// Determine whether the given class is or inherits from a class by
8932 /// the given name.
8933 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) {
8934   if (!Class)
8935     return false;
8936 
8937   if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
8938     return true;
8939 
8940   return InheritsFromClassNamed(Class->getSuperClass(), Name);
8941 }
8942 
8943 /// Add code completions for Objective-C Key-Value Coding (KVC) and
8944 /// Key-Value Observing (KVO).
8945 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
8946                                        bool IsInstanceMethod,
8947                                        QualType ReturnType, ASTContext &Context,
8948                                        VisitedSelectorSet &KnownSelectors,
8949                                        ResultBuilder &Results) {
8950   IdentifierInfo *PropName = Property->getIdentifier();
8951   if (!PropName || PropName->getLength() == 0)
8952     return;
8953 
8954   PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
8955 
8956   // Builder that will create each code completion.
8957   typedef CodeCompletionResult Result;
8958   CodeCompletionAllocator &Allocator = Results.getAllocator();
8959   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
8960 
8961   // The selector table.
8962   SelectorTable &Selectors = Context.Selectors;
8963 
8964   // The property name, copied into the code completion allocation region
8965   // on demand.
8966   struct KeyHolder {
8967     CodeCompletionAllocator &Allocator;
8968     StringRef Key;
8969     const char *CopiedKey;
8970 
8971     KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
8972         : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
8973 
8974     operator const char *() {
8975       if (CopiedKey)
8976         return CopiedKey;
8977 
8978       return CopiedKey = Allocator.CopyString(Key);
8979     }
8980   } Key(Allocator, PropName->getName());
8981 
8982   // The uppercased name of the property name.
8983   std::string UpperKey = std::string(PropName->getName());
8984   if (!UpperKey.empty())
8985     UpperKey[0] = toUppercase(UpperKey[0]);
8986 
8987   bool ReturnTypeMatchesProperty =
8988       ReturnType.isNull() ||
8989       Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
8990                                      Property->getType());
8991   bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType();
8992 
8993   // Add the normal accessor -(type)key.
8994   if (IsInstanceMethod &&
8995       KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
8996       ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
8997     if (ReturnType.isNull())
8998       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
8999                               Builder);
9000 
9001     Builder.AddTypedTextChunk(Key);
9002     Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9003                              CXCursor_ObjCInstanceMethodDecl));
9004   }
9005 
9006   // If we have an integral or boolean property (or the user has provided
9007   // an integral or boolean return type), add the accessor -(type)isKey.
9008   if (IsInstanceMethod &&
9009       ((!ReturnType.isNull() &&
9010         (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
9011        (ReturnType.isNull() && (Property->getType()->isIntegerType() ||
9012                                 Property->getType()->isBooleanType())))) {
9013     std::string SelectorName = (Twine("is") + UpperKey).str();
9014     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9015     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9016             .second) {
9017       if (ReturnType.isNull()) {
9018         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9019         Builder.AddTextChunk("BOOL");
9020         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9021       }
9022 
9023       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9024       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9025                                CXCursor_ObjCInstanceMethodDecl));
9026     }
9027   }
9028 
9029   // Add the normal mutator.
9030   if (IsInstanceMethod && ReturnTypeMatchesVoid &&
9031       !Property->getSetterMethodDecl()) {
9032     std::string SelectorName = (Twine("set") + UpperKey).str();
9033     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9034     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9035       if (ReturnType.isNull()) {
9036         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9037         Builder.AddTextChunk("void");
9038         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9039       }
9040 
9041       Builder.AddTypedTextChunk(
9042           Allocator.CopyString(SelectorId->getName() + ":"));
9043       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
9044                               Builder);
9045       Builder.AddTextChunk(Key);
9046       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9047                                CXCursor_ObjCInstanceMethodDecl));
9048     }
9049   }
9050 
9051   // Indexed and unordered accessors
9052   unsigned IndexedGetterPriority = CCP_CodePattern;
9053   unsigned IndexedSetterPriority = CCP_CodePattern;
9054   unsigned UnorderedGetterPriority = CCP_CodePattern;
9055   unsigned UnorderedSetterPriority = CCP_CodePattern;
9056   if (const auto *ObjCPointer =
9057           Property->getType()->getAs<ObjCObjectPointerType>()) {
9058     if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
9059       // If this interface type is not provably derived from a known
9060       // collection, penalize the corresponding completions.
9061       if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
9062         IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
9063         if (!InheritsFromClassNamed(IFace, "NSArray"))
9064           IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
9065       }
9066 
9067       if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
9068         UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
9069         if (!InheritsFromClassNamed(IFace, "NSSet"))
9070           UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
9071       }
9072     }
9073   } else {
9074     IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
9075     IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
9076     UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
9077     UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
9078   }
9079 
9080   // Add -(NSUInteger)countOf<key>
9081   if (IsInstanceMethod &&
9082       (ReturnType.isNull() || ReturnType->isIntegerType())) {
9083     std::string SelectorName = (Twine("countOf") + UpperKey).str();
9084     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9085     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9086             .second) {
9087       if (ReturnType.isNull()) {
9088         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9089         Builder.AddTextChunk("NSUInteger");
9090         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9091       }
9092 
9093       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9094       Results.AddResult(
9095           Result(Builder.TakeString(),
9096                  std::min(IndexedGetterPriority, UnorderedGetterPriority),
9097                  CXCursor_ObjCInstanceMethodDecl));
9098     }
9099   }
9100 
9101   // Indexed getters
9102   // Add -(id)objectInKeyAtIndex:(NSUInteger)index
9103   if (IsInstanceMethod &&
9104       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9105     std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str();
9106     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9107     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9108       if (ReturnType.isNull()) {
9109         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9110         Builder.AddTextChunk("id");
9111         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9112       }
9113 
9114       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9115       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9116       Builder.AddTextChunk("NSUInteger");
9117       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9118       Builder.AddTextChunk("index");
9119       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9120                                CXCursor_ObjCInstanceMethodDecl));
9121     }
9122   }
9123 
9124   // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
9125   if (IsInstanceMethod &&
9126       (ReturnType.isNull() ||
9127        (ReturnType->isObjCObjectPointerType() &&
9128         ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9129         ReturnType->castAs<ObjCObjectPointerType>()
9130                 ->getInterfaceDecl()
9131                 ->getName() == "NSArray"))) {
9132     std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str();
9133     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9134     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9135       if (ReturnType.isNull()) {
9136         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9137         Builder.AddTextChunk("NSArray *");
9138         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9139       }
9140 
9141       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9142       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9143       Builder.AddTextChunk("NSIndexSet *");
9144       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9145       Builder.AddTextChunk("indexes");
9146       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9147                                CXCursor_ObjCInstanceMethodDecl));
9148     }
9149   }
9150 
9151   // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
9152   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9153     std::string SelectorName = (Twine("get") + UpperKey).str();
9154     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9155                                       &Context.Idents.get("range")};
9156 
9157     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9158       if (ReturnType.isNull()) {
9159         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9160         Builder.AddTextChunk("void");
9161         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9162       }
9163 
9164       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9165       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9166       Builder.AddPlaceholderChunk("object-type");
9167       Builder.AddTextChunk(" **");
9168       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9169       Builder.AddTextChunk("buffer");
9170       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9171       Builder.AddTypedTextChunk("range:");
9172       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9173       Builder.AddTextChunk("NSRange");
9174       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9175       Builder.AddTextChunk("inRange");
9176       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9177                                CXCursor_ObjCInstanceMethodDecl));
9178     }
9179   }
9180 
9181   // Mutable indexed accessors
9182 
9183   // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
9184   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9185     std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
9186     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"),
9187                                       &Context.Idents.get(SelectorName)};
9188 
9189     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9190       if (ReturnType.isNull()) {
9191         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9192         Builder.AddTextChunk("void");
9193         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9194       }
9195 
9196       Builder.AddTypedTextChunk("insertObject:");
9197       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9198       Builder.AddPlaceholderChunk("object-type");
9199       Builder.AddTextChunk(" *");
9200       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9201       Builder.AddTextChunk("object");
9202       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9203       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9204       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9205       Builder.AddPlaceholderChunk("NSUInteger");
9206       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9207       Builder.AddTextChunk("index");
9208       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9209                                CXCursor_ObjCInstanceMethodDecl));
9210     }
9211   }
9212 
9213   // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
9214   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9215     std::string SelectorName = (Twine("insert") + UpperKey).str();
9216     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9217                                       &Context.Idents.get("atIndexes")};
9218 
9219     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9220       if (ReturnType.isNull()) {
9221         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9222         Builder.AddTextChunk("void");
9223         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9224       }
9225 
9226       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9227       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9228       Builder.AddTextChunk("NSArray *");
9229       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9230       Builder.AddTextChunk("array");
9231       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9232       Builder.AddTypedTextChunk("atIndexes:");
9233       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9234       Builder.AddPlaceholderChunk("NSIndexSet *");
9235       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9236       Builder.AddTextChunk("indexes");
9237       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9238                                CXCursor_ObjCInstanceMethodDecl));
9239     }
9240   }
9241 
9242   // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
9243   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9244     std::string SelectorName =
9245         (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
9246     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9247     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9248       if (ReturnType.isNull()) {
9249         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9250         Builder.AddTextChunk("void");
9251         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9252       }
9253 
9254       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9255       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9256       Builder.AddTextChunk("NSUInteger");
9257       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9258       Builder.AddTextChunk("index");
9259       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9260                                CXCursor_ObjCInstanceMethodDecl));
9261     }
9262   }
9263 
9264   // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
9265   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9266     std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str();
9267     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9268     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9269       if (ReturnType.isNull()) {
9270         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9271         Builder.AddTextChunk("void");
9272         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9273       }
9274 
9275       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9276       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9277       Builder.AddTextChunk("NSIndexSet *");
9278       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9279       Builder.AddTextChunk("indexes");
9280       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9281                                CXCursor_ObjCInstanceMethodDecl));
9282     }
9283   }
9284 
9285   // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
9286   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9287     std::string SelectorName =
9288         (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
9289     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9290                                       &Context.Idents.get("withObject")};
9291 
9292     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9293       if (ReturnType.isNull()) {
9294         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9295         Builder.AddTextChunk("void");
9296         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9297       }
9298 
9299       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9300       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9301       Builder.AddPlaceholderChunk("NSUInteger");
9302       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9303       Builder.AddTextChunk("index");
9304       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9305       Builder.AddTypedTextChunk("withObject:");
9306       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9307       Builder.AddTextChunk("id");
9308       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9309       Builder.AddTextChunk("object");
9310       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9311                                CXCursor_ObjCInstanceMethodDecl));
9312     }
9313   }
9314 
9315   // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
9316   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9317     std::string SelectorName1 =
9318         (Twine("replace") + UpperKey + "AtIndexes").str();
9319     std::string SelectorName2 = (Twine("with") + UpperKey).str();
9320     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1),
9321                                       &Context.Idents.get(SelectorName2)};
9322 
9323     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9324       if (ReturnType.isNull()) {
9325         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9326         Builder.AddTextChunk("void");
9327         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9328       }
9329 
9330       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
9331       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9332       Builder.AddPlaceholderChunk("NSIndexSet *");
9333       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9334       Builder.AddTextChunk("indexes");
9335       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9336       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
9337       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9338       Builder.AddTextChunk("NSArray *");
9339       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9340       Builder.AddTextChunk("array");
9341       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9342                                CXCursor_ObjCInstanceMethodDecl));
9343     }
9344   }
9345 
9346   // Unordered getters
9347   // - (NSEnumerator *)enumeratorOfKey
9348   if (IsInstanceMethod &&
9349       (ReturnType.isNull() ||
9350        (ReturnType->isObjCObjectPointerType() &&
9351         ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9352         ReturnType->castAs<ObjCObjectPointerType>()
9353                 ->getInterfaceDecl()
9354                 ->getName() == "NSEnumerator"))) {
9355     std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
9356     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9357     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9358             .second) {
9359       if (ReturnType.isNull()) {
9360         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9361         Builder.AddTextChunk("NSEnumerator *");
9362         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9363       }
9364 
9365       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9366       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9367                                CXCursor_ObjCInstanceMethodDecl));
9368     }
9369   }
9370 
9371   // - (type *)memberOfKey:(type *)object
9372   if (IsInstanceMethod &&
9373       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9374     std::string SelectorName = (Twine("memberOf") + UpperKey).str();
9375     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9376     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9377       if (ReturnType.isNull()) {
9378         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9379         Builder.AddPlaceholderChunk("object-type");
9380         Builder.AddTextChunk(" *");
9381         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9382       }
9383 
9384       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9385       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9386       if (ReturnType.isNull()) {
9387         Builder.AddPlaceholderChunk("object-type");
9388         Builder.AddTextChunk(" *");
9389       } else {
9390         Builder.AddTextChunk(GetCompletionTypeString(
9391             ReturnType, Context, Policy, Builder.getAllocator()));
9392       }
9393       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9394       Builder.AddTextChunk("object");
9395       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9396                                CXCursor_ObjCInstanceMethodDecl));
9397     }
9398   }
9399 
9400   // Mutable unordered accessors
9401   // - (void)addKeyObject:(type *)object
9402   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9403     std::string SelectorName =
9404         (Twine("add") + UpperKey + Twine("Object")).str();
9405     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9406     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9407       if (ReturnType.isNull()) {
9408         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9409         Builder.AddTextChunk("void");
9410         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9411       }
9412 
9413       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9414       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9415       Builder.AddPlaceholderChunk("object-type");
9416       Builder.AddTextChunk(" *");
9417       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9418       Builder.AddTextChunk("object");
9419       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9420                                CXCursor_ObjCInstanceMethodDecl));
9421     }
9422   }
9423 
9424   // - (void)addKey:(NSSet *)objects
9425   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9426     std::string SelectorName = (Twine("add") + UpperKey).str();
9427     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9428     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9429       if (ReturnType.isNull()) {
9430         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9431         Builder.AddTextChunk("void");
9432         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9433       }
9434 
9435       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9436       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9437       Builder.AddTextChunk("NSSet *");
9438       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9439       Builder.AddTextChunk("objects");
9440       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9441                                CXCursor_ObjCInstanceMethodDecl));
9442     }
9443   }
9444 
9445   // - (void)removeKeyObject:(type *)object
9446   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9447     std::string SelectorName =
9448         (Twine("remove") + UpperKey + Twine("Object")).str();
9449     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9450     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9451       if (ReturnType.isNull()) {
9452         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9453         Builder.AddTextChunk("void");
9454         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9455       }
9456 
9457       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9458       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9459       Builder.AddPlaceholderChunk("object-type");
9460       Builder.AddTextChunk(" *");
9461       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9462       Builder.AddTextChunk("object");
9463       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9464                                CXCursor_ObjCInstanceMethodDecl));
9465     }
9466   }
9467 
9468   // - (void)removeKey:(NSSet *)objects
9469   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9470     std::string SelectorName = (Twine("remove") + UpperKey).str();
9471     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9472     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9473       if (ReturnType.isNull()) {
9474         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9475         Builder.AddTextChunk("void");
9476         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9477       }
9478 
9479       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9480       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9481       Builder.AddTextChunk("NSSet *");
9482       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9483       Builder.AddTextChunk("objects");
9484       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9485                                CXCursor_ObjCInstanceMethodDecl));
9486     }
9487   }
9488 
9489   // - (void)intersectKey:(NSSet *)objects
9490   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9491     std::string SelectorName = (Twine("intersect") + UpperKey).str();
9492     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9493     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9494       if (ReturnType.isNull()) {
9495         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9496         Builder.AddTextChunk("void");
9497         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9498       }
9499 
9500       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9501       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9502       Builder.AddTextChunk("NSSet *");
9503       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9504       Builder.AddTextChunk("objects");
9505       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9506                                CXCursor_ObjCInstanceMethodDecl));
9507     }
9508   }
9509 
9510   // Key-Value Observing
9511   // + (NSSet *)keyPathsForValuesAffectingKey
9512   if (!IsInstanceMethod &&
9513       (ReturnType.isNull() ||
9514        (ReturnType->isObjCObjectPointerType() &&
9515         ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9516         ReturnType->castAs<ObjCObjectPointerType>()
9517                 ->getInterfaceDecl()
9518                 ->getName() == "NSSet"))) {
9519     std::string SelectorName =
9520         (Twine("keyPathsForValuesAffecting") + UpperKey).str();
9521     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9522     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9523             .second) {
9524       if (ReturnType.isNull()) {
9525         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9526         Builder.AddTextChunk("NSSet<NSString *> *");
9527         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9528       }
9529 
9530       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9531       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9532                                CXCursor_ObjCClassMethodDecl));
9533     }
9534   }
9535 
9536   // + (BOOL)automaticallyNotifiesObserversForKey
9537   if (!IsInstanceMethod &&
9538       (ReturnType.isNull() || ReturnType->isIntegerType() ||
9539        ReturnType->isBooleanType())) {
9540     std::string SelectorName =
9541         (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
9542     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9543     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9544             .second) {
9545       if (ReturnType.isNull()) {
9546         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9547         Builder.AddTextChunk("BOOL");
9548         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9549       }
9550 
9551       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9552       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9553                                CXCursor_ObjCClassMethodDecl));
9554     }
9555   }
9556 }
9557 
9558 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
9559                                       std::optional<bool> IsInstanceMethod,
9560                                       ParsedType ReturnTy) {
9561   // Determine the return type of the method we're declaring, if
9562   // provided.
9563   QualType ReturnType = GetTypeFromParser(ReturnTy);
9564   Decl *IDecl = nullptr;
9565   if (CurContext->isObjCContainer()) {
9566     ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
9567     IDecl = OCD;
9568   }
9569   // Determine where we should start searching for methods.
9570   ObjCContainerDecl *SearchDecl = nullptr;
9571   bool IsInImplementation = false;
9572   if (Decl *D = IDecl) {
9573     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
9574       SearchDecl = Impl->getClassInterface();
9575       IsInImplementation = true;
9576     } else if (ObjCCategoryImplDecl *CatImpl =
9577                    dyn_cast<ObjCCategoryImplDecl>(D)) {
9578       SearchDecl = CatImpl->getCategoryDecl();
9579       IsInImplementation = true;
9580     } else
9581       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
9582   }
9583 
9584   if (!SearchDecl && S) {
9585     if (DeclContext *DC = S->getEntity())
9586       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
9587   }
9588 
9589   if (!SearchDecl) {
9590     HandleCodeCompleteResults(this, CodeCompleter,
9591                               CodeCompletionContext::CCC_Other, nullptr, 0);
9592     return;
9593   }
9594 
9595   // Find all of the methods that we could declare/implement here.
9596   KnownMethodsMap KnownMethods;
9597   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType,
9598                            KnownMethods);
9599 
9600   // Add declarations or definitions for each of the known methods.
9601   typedef CodeCompletionResult Result;
9602   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9603                         CodeCompleter->getCodeCompletionTUInfo(),
9604                         CodeCompletionContext::CCC_Other);
9605   Results.EnterNewScope();
9606   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
9607   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9608                                  MEnd = KnownMethods.end();
9609        M != MEnd; ++M) {
9610     ObjCMethodDecl *Method = M->second.getPointer();
9611     CodeCompletionBuilder Builder(Results.getAllocator(),
9612                                   Results.getCodeCompletionTUInfo());
9613 
9614     // Add the '-'/'+' prefix if it wasn't provided yet.
9615     if (!IsInstanceMethod) {
9616       Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
9617       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9618     }
9619 
9620     // If the result type was not already provided, add it to the
9621     // pattern as (type).
9622     if (ReturnType.isNull()) {
9623       QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
9624       AttributedType::stripOuterNullability(ResTy);
9625       AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context,
9626                               Policy, Builder);
9627     }
9628 
9629     Selector Sel = Method->getSelector();
9630 
9631     if (Sel.isUnarySelector()) {
9632       // Unary selectors have no arguments.
9633       Builder.AddTypedTextChunk(
9634           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
9635     } else {
9636       // Add all parameters to the pattern.
9637       unsigned I = 0;
9638       for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
9639                                           PEnd = Method->param_end();
9640            P != PEnd; (void)++P, ++I) {
9641         // Add the part of the selector name.
9642         if (I == 0)
9643           Builder.AddTypedTextChunk(
9644               Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9645         else if (I < Sel.getNumArgs()) {
9646           Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9647           Builder.AddTypedTextChunk(
9648               Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9649         } else
9650           break;
9651 
9652         // Add the parameter type.
9653         QualType ParamType;
9654         if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
9655           ParamType = (*P)->getType();
9656         else
9657           ParamType = (*P)->getOriginalType();
9658         ParamType = ParamType.substObjCTypeArgs(
9659             Context, {}, ObjCSubstitutionContext::Parameter);
9660         AttributedType::stripOuterNullability(ParamType);
9661         AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(),
9662                                 Context, Policy, Builder);
9663 
9664         if (IdentifierInfo *Id = (*P)->getIdentifier())
9665           Builder.AddTextChunk(
9666               Builder.getAllocator().CopyString(Id->getName()));
9667       }
9668     }
9669 
9670     if (Method->isVariadic()) {
9671       if (Method->param_size() > 0)
9672         Builder.AddChunk(CodeCompletionString::CK_Comma);
9673       Builder.AddTextChunk("...");
9674     }
9675 
9676     if (IsInImplementation && Results.includeCodePatterns()) {
9677       // We will be defining the method here, so add a compound statement.
9678       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9679       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
9680       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
9681       if (!Method->getReturnType()->isVoidType()) {
9682         // If the result type is not void, add a return clause.
9683         Builder.AddTextChunk("return");
9684         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9685         Builder.AddPlaceholderChunk("expression");
9686         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
9687       } else
9688         Builder.AddPlaceholderChunk("statements");
9689 
9690       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
9691       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
9692     }
9693 
9694     unsigned Priority = CCP_CodePattern;
9695     auto R = Result(Builder.TakeString(), Method, Priority);
9696     if (!M->second.getInt())
9697       setInBaseClass(R);
9698     Results.AddResult(std::move(R));
9699   }
9700 
9701   // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
9702   // the properties in this class and its categories.
9703   if (Context.getLangOpts().ObjC) {
9704     SmallVector<ObjCContainerDecl *, 4> Containers;
9705     Containers.push_back(SearchDecl);
9706 
9707     VisitedSelectorSet KnownSelectors;
9708     for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9709                                    MEnd = KnownMethods.end();
9710          M != MEnd; ++M)
9711       KnownSelectors.insert(M->first);
9712 
9713     ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
9714     if (!IFace)
9715       if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
9716         IFace = Category->getClassInterface();
9717 
9718     if (IFace)
9719       llvm::append_range(Containers, IFace->visible_categories());
9720 
9721     if (IsInstanceMethod) {
9722       for (unsigned I = 0, N = Containers.size(); I != N; ++I)
9723         for (auto *P : Containers[I]->instance_properties())
9724           AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
9725                                      KnownSelectors, Results);
9726     }
9727   }
9728 
9729   Results.ExitScope();
9730 
9731   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9732                             Results.data(), Results.size());
9733 }
9734 
9735 void Sema::CodeCompleteObjCMethodDeclSelector(
9736     Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy,
9737     ArrayRef<IdentifierInfo *> SelIdents) {
9738   // If we have an external source, load the entire class method
9739   // pool from the AST file.
9740   if (ExternalSource) {
9741     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
9742          ++I) {
9743       Selector Sel = ExternalSource->GetExternalSelector(I);
9744       if (Sel.isNull() || MethodPool.count(Sel))
9745         continue;
9746 
9747       ReadMethodPool(Sel);
9748     }
9749   }
9750 
9751   // Build the set of methods we can see.
9752   typedef CodeCompletionResult Result;
9753   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9754                         CodeCompleter->getCodeCompletionTUInfo(),
9755                         CodeCompletionContext::CCC_Other);
9756 
9757   if (ReturnTy)
9758     Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
9759 
9760   Results.EnterNewScope();
9761   for (GlobalMethodPool::iterator M = MethodPool.begin(),
9762                                   MEnd = MethodPool.end();
9763        M != MEnd; ++M) {
9764     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first
9765                                                      : &M->second.second;
9766          MethList && MethList->getMethod(); MethList = MethList->getNext()) {
9767       if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
9768         continue;
9769 
9770       if (AtParameterName) {
9771         // Suggest parameter names we've seen before.
9772         unsigned NumSelIdents = SelIdents.size();
9773         if (NumSelIdents &&
9774             NumSelIdents <= MethList->getMethod()->param_size()) {
9775           ParmVarDecl *Param =
9776               MethList->getMethod()->parameters()[NumSelIdents - 1];
9777           if (Param->getIdentifier()) {
9778             CodeCompletionBuilder Builder(Results.getAllocator(),
9779                                           Results.getCodeCompletionTUInfo());
9780             Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
9781                 Param->getIdentifier()->getName()));
9782             Results.AddResult(Builder.TakeString());
9783           }
9784         }
9785 
9786         continue;
9787       }
9788 
9789       Result R(MethList->getMethod(),
9790                Results.getBasePriority(MethList->getMethod()), nullptr);
9791       R.StartParameter = SelIdents.size();
9792       R.AllParametersAreInformative = false;
9793       R.DeclaringEntity = true;
9794       Results.MaybeAddResult(R, CurContext);
9795     }
9796   }
9797 
9798   Results.ExitScope();
9799 
9800   if (!AtParameterName && !SelIdents.empty() &&
9801       SelIdents.front()->getName().starts_with("init")) {
9802     for (const auto &M : PP.macros()) {
9803       if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
9804         continue;
9805       Results.EnterNewScope();
9806       CodeCompletionBuilder Builder(Results.getAllocator(),
9807                                     Results.getCodeCompletionTUInfo());
9808       Builder.AddTypedTextChunk(
9809           Builder.getAllocator().CopyString(M.first->getName()));
9810       Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
9811                                              CXCursor_MacroDefinition));
9812       Results.ExitScope();
9813     }
9814   }
9815 
9816   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9817                             Results.data(), Results.size());
9818 }
9819 
9820 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
9821   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9822                         CodeCompleter->getCodeCompletionTUInfo(),
9823                         CodeCompletionContext::CCC_PreprocessorDirective);
9824   Results.EnterNewScope();
9825 
9826   // #if <condition>
9827   CodeCompletionBuilder Builder(Results.getAllocator(),
9828                                 Results.getCodeCompletionTUInfo());
9829   Builder.AddTypedTextChunk("if");
9830   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9831   Builder.AddPlaceholderChunk("condition");
9832   Results.AddResult(Builder.TakeString());
9833 
9834   // #ifdef <macro>
9835   Builder.AddTypedTextChunk("ifdef");
9836   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9837   Builder.AddPlaceholderChunk("macro");
9838   Results.AddResult(Builder.TakeString());
9839 
9840   // #ifndef <macro>
9841   Builder.AddTypedTextChunk("ifndef");
9842   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9843   Builder.AddPlaceholderChunk("macro");
9844   Results.AddResult(Builder.TakeString());
9845 
9846   if (InConditional) {
9847     // #elif <condition>
9848     Builder.AddTypedTextChunk("elif");
9849     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9850     Builder.AddPlaceholderChunk("condition");
9851     Results.AddResult(Builder.TakeString());
9852 
9853     // #elifdef <macro>
9854     Builder.AddTypedTextChunk("elifdef");
9855     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9856     Builder.AddPlaceholderChunk("macro");
9857     Results.AddResult(Builder.TakeString());
9858 
9859     // #elifndef <macro>
9860     Builder.AddTypedTextChunk("elifndef");
9861     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9862     Builder.AddPlaceholderChunk("macro");
9863     Results.AddResult(Builder.TakeString());
9864 
9865     // #else
9866     Builder.AddTypedTextChunk("else");
9867     Results.AddResult(Builder.TakeString());
9868 
9869     // #endif
9870     Builder.AddTypedTextChunk("endif");
9871     Results.AddResult(Builder.TakeString());
9872   }
9873 
9874   // #include "header"
9875   Builder.AddTypedTextChunk("include");
9876   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9877   Builder.AddTextChunk("\"");
9878   Builder.AddPlaceholderChunk("header");
9879   Builder.AddTextChunk("\"");
9880   Results.AddResult(Builder.TakeString());
9881 
9882   // #include <header>
9883   Builder.AddTypedTextChunk("include");
9884   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9885   Builder.AddTextChunk("<");
9886   Builder.AddPlaceholderChunk("header");
9887   Builder.AddTextChunk(">");
9888   Results.AddResult(Builder.TakeString());
9889 
9890   // #define <macro>
9891   Builder.AddTypedTextChunk("define");
9892   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9893   Builder.AddPlaceholderChunk("macro");
9894   Results.AddResult(Builder.TakeString());
9895 
9896   // #define <macro>(<args>)
9897   Builder.AddTypedTextChunk("define");
9898   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9899   Builder.AddPlaceholderChunk("macro");
9900   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9901   Builder.AddPlaceholderChunk("args");
9902   Builder.AddChunk(CodeCompletionString::CK_RightParen);
9903   Results.AddResult(Builder.TakeString());
9904 
9905   // #undef <macro>
9906   Builder.AddTypedTextChunk("undef");
9907   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9908   Builder.AddPlaceholderChunk("macro");
9909   Results.AddResult(Builder.TakeString());
9910 
9911   // #line <number>
9912   Builder.AddTypedTextChunk("line");
9913   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9914   Builder.AddPlaceholderChunk("number");
9915   Results.AddResult(Builder.TakeString());
9916 
9917   // #line <number> "filename"
9918   Builder.AddTypedTextChunk("line");
9919   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9920   Builder.AddPlaceholderChunk("number");
9921   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9922   Builder.AddTextChunk("\"");
9923   Builder.AddPlaceholderChunk("filename");
9924   Builder.AddTextChunk("\"");
9925   Results.AddResult(Builder.TakeString());
9926 
9927   // #error <message>
9928   Builder.AddTypedTextChunk("error");
9929   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9930   Builder.AddPlaceholderChunk("message");
9931   Results.AddResult(Builder.TakeString());
9932 
9933   // #pragma <arguments>
9934   Builder.AddTypedTextChunk("pragma");
9935   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9936   Builder.AddPlaceholderChunk("arguments");
9937   Results.AddResult(Builder.TakeString());
9938 
9939   if (getLangOpts().ObjC) {
9940     // #import "header"
9941     Builder.AddTypedTextChunk("import");
9942     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9943     Builder.AddTextChunk("\"");
9944     Builder.AddPlaceholderChunk("header");
9945     Builder.AddTextChunk("\"");
9946     Results.AddResult(Builder.TakeString());
9947 
9948     // #import <header>
9949     Builder.AddTypedTextChunk("import");
9950     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9951     Builder.AddTextChunk("<");
9952     Builder.AddPlaceholderChunk("header");
9953     Builder.AddTextChunk(">");
9954     Results.AddResult(Builder.TakeString());
9955   }
9956 
9957   // #include_next "header"
9958   Builder.AddTypedTextChunk("include_next");
9959   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9960   Builder.AddTextChunk("\"");
9961   Builder.AddPlaceholderChunk("header");
9962   Builder.AddTextChunk("\"");
9963   Results.AddResult(Builder.TakeString());
9964 
9965   // #include_next <header>
9966   Builder.AddTypedTextChunk("include_next");
9967   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9968   Builder.AddTextChunk("<");
9969   Builder.AddPlaceholderChunk("header");
9970   Builder.AddTextChunk(">");
9971   Results.AddResult(Builder.TakeString());
9972 
9973   // #warning <message>
9974   Builder.AddTypedTextChunk("warning");
9975   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9976   Builder.AddPlaceholderChunk("message");
9977   Results.AddResult(Builder.TakeString());
9978 
9979   // Note: #ident and #sccs are such crazy anachronisms that we don't provide
9980   // completions for them. And __include_macros is a Clang-internal extension
9981   // that we don't want to encourage anyone to use.
9982 
9983   // FIXME: we don't support #assert or #unassert, so don't suggest them.
9984   Results.ExitScope();
9985 
9986   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9987                             Results.data(), Results.size());
9988 }
9989 
9990 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
9991   CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction
9992                                                : Sema::PCC_Namespace);
9993 }
9994 
9995 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
9996   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9997                         CodeCompleter->getCodeCompletionTUInfo(),
9998                         IsDefinition ? CodeCompletionContext::CCC_MacroName
9999                                      : CodeCompletionContext::CCC_MacroNameUse);
10000   if (!IsDefinition && CodeCompleter->includeMacros()) {
10001     // Add just the names of macros, not their arguments.
10002     CodeCompletionBuilder Builder(Results.getAllocator(),
10003                                   Results.getCodeCompletionTUInfo());
10004     Results.EnterNewScope();
10005     for (Preprocessor::macro_iterator M = PP.macro_begin(),
10006                                       MEnd = PP.macro_end();
10007          M != MEnd; ++M) {
10008       Builder.AddTypedTextChunk(
10009           Builder.getAllocator().CopyString(M->first->getName()));
10010       Results.AddResult(CodeCompletionResult(
10011           Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition));
10012     }
10013     Results.ExitScope();
10014   } else if (IsDefinition) {
10015     // FIXME: Can we detect when the user just wrote an include guard above?
10016   }
10017 
10018   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10019                             Results.data(), Results.size());
10020 }
10021 
10022 void Sema::CodeCompletePreprocessorExpression() {
10023   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10024                         CodeCompleter->getCodeCompletionTUInfo(),
10025                         CodeCompletionContext::CCC_PreprocessorExpression);
10026 
10027   if (CodeCompleter->includeMacros())
10028     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), true);
10029 
10030   // defined (<macro>)
10031   Results.EnterNewScope();
10032   CodeCompletionBuilder Builder(Results.getAllocator(),
10033                                 Results.getCodeCompletionTUInfo());
10034   Builder.AddTypedTextChunk("defined");
10035   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
10036   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
10037   Builder.AddPlaceholderChunk("macro");
10038   Builder.AddChunk(CodeCompletionString::CK_RightParen);
10039   Results.AddResult(Builder.TakeString());
10040   Results.ExitScope();
10041 
10042   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10043                             Results.data(), Results.size());
10044 }
10045 
10046 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
10047                                                  IdentifierInfo *Macro,
10048                                                  MacroInfo *MacroInfo,
10049                                                  unsigned Argument) {
10050   // FIXME: In the future, we could provide "overload" results, much like we
10051   // do for function calls.
10052 
10053   // Now just ignore this. There will be another code-completion callback
10054   // for the expanded tokens.
10055 }
10056 
10057 // This handles completion inside an #include filename, e.g. #include <foo/ba
10058 // We look for the directory "foo" under each directory on the include path,
10059 // list its files, and reassemble the appropriate #include.
10060 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) {
10061   // RelDir should use /, but unescaped \ is possible on windows!
10062   // Our completions will normalize to / for simplicity, this case is rare.
10063   std::string RelDir = llvm::sys::path::convert_to_slash(Dir);
10064   // We need the native slashes for the actual file system interactions.
10065   SmallString<128> NativeRelDir = StringRef(RelDir);
10066   llvm::sys::path::native(NativeRelDir);
10067   llvm::vfs::FileSystem &FS =
10068       getSourceManager().getFileManager().getVirtualFileSystem();
10069 
10070   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10071                         CodeCompleter->getCodeCompletionTUInfo(),
10072                         CodeCompletionContext::CCC_IncludedFile);
10073   llvm::DenseSet<StringRef> SeenResults; // To deduplicate results.
10074 
10075   // Helper: adds one file or directory completion result.
10076   auto AddCompletion = [&](StringRef Filename, bool IsDirectory) {
10077     SmallString<64> TypedChunk = Filename;
10078     // Directory completion is up to the slash, e.g. <sys/
10079     TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"');
10080     auto R = SeenResults.insert(TypedChunk);
10081     if (R.second) { // New completion
10082       const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk);
10083       *R.first = InternedTyped; // Avoid dangling StringRef.
10084       CodeCompletionBuilder Builder(CodeCompleter->getAllocator(),
10085                                     CodeCompleter->getCodeCompletionTUInfo());
10086       Builder.AddTypedTextChunk(InternedTyped);
10087       // The result is a "Pattern", which is pretty opaque.
10088       // We may want to include the real filename to allow smart ranking.
10089       Results.AddResult(CodeCompletionResult(Builder.TakeString()));
10090     }
10091   };
10092 
10093   // Helper: scans IncludeDir for nice files, and adds results for each.
10094   auto AddFilesFromIncludeDir = [&](StringRef IncludeDir,
10095                                     bool IsSystem,
10096                                     DirectoryLookup::LookupType_t LookupType) {
10097     llvm::SmallString<128> Dir = IncludeDir;
10098     if (!NativeRelDir.empty()) {
10099       if (LookupType == DirectoryLookup::LT_Framework) {
10100         // For a framework dir, #include <Foo/Bar/> actually maps to
10101         // a path of Foo.framework/Headers/Bar/.
10102         auto Begin = llvm::sys::path::begin(NativeRelDir);
10103         auto End = llvm::sys::path::end(NativeRelDir);
10104 
10105         llvm::sys::path::append(Dir, *Begin + ".framework", "Headers");
10106         llvm::sys::path::append(Dir, ++Begin, End);
10107       } else {
10108         llvm::sys::path::append(Dir, NativeRelDir);
10109       }
10110     }
10111 
10112     const StringRef &Dirname = llvm::sys::path::filename(Dir);
10113     const bool isQt = Dirname.starts_with("Qt") || Dirname == "ActiveQt";
10114     const bool ExtensionlessHeaders =
10115         IsSystem || isQt || Dir.ends_with(".framework/Headers");
10116     std::error_code EC;
10117     unsigned Count = 0;
10118     for (auto It = FS.dir_begin(Dir, EC);
10119          !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
10120       if (++Count == 2500) // If we happen to hit a huge directory,
10121         break;             // bail out early so we're not too slow.
10122       StringRef Filename = llvm::sys::path::filename(It->path());
10123 
10124       // To know whether a symlink should be treated as file or a directory, we
10125       // have to stat it. This should be cheap enough as there shouldn't be many
10126       // symlinks.
10127       llvm::sys::fs::file_type Type = It->type();
10128       if (Type == llvm::sys::fs::file_type::symlink_file) {
10129         if (auto FileStatus = FS.status(It->path()))
10130           Type = FileStatus->getType();
10131       }
10132       switch (Type) {
10133       case llvm::sys::fs::file_type::directory_file:
10134         // All entries in a framework directory must have a ".framework" suffix,
10135         // but the suffix does not appear in the source code's include/import.
10136         if (LookupType == DirectoryLookup::LT_Framework &&
10137             NativeRelDir.empty() && !Filename.consume_back(".framework"))
10138           break;
10139 
10140         AddCompletion(Filename, /*IsDirectory=*/true);
10141         break;
10142       case llvm::sys::fs::file_type::regular_file: {
10143         // Only files that really look like headers. (Except in special dirs).
10144         const bool IsHeader = Filename.ends_with_insensitive(".h") ||
10145                               Filename.ends_with_insensitive(".hh") ||
10146                               Filename.ends_with_insensitive(".hpp") ||
10147                               Filename.ends_with_insensitive(".hxx") ||
10148                               Filename.ends_with_insensitive(".inc") ||
10149                               (ExtensionlessHeaders && !Filename.contains('.'));
10150         if (!IsHeader)
10151           break;
10152         AddCompletion(Filename, /*IsDirectory=*/false);
10153         break;
10154       }
10155       default:
10156         break;
10157       }
10158     }
10159   };
10160 
10161   // Helper: adds results relative to IncludeDir, if possible.
10162   auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir,
10163                                    bool IsSystem) {
10164     switch (IncludeDir.getLookupType()) {
10165     case DirectoryLookup::LT_HeaderMap:
10166       // header maps are not (currently) enumerable.
10167       break;
10168     case DirectoryLookup::LT_NormalDir:
10169       AddFilesFromIncludeDir(IncludeDir.getDirRef()->getName(), IsSystem,
10170                              DirectoryLookup::LT_NormalDir);
10171       break;
10172     case DirectoryLookup::LT_Framework:
10173       AddFilesFromIncludeDir(IncludeDir.getFrameworkDirRef()->getName(),
10174                              IsSystem, DirectoryLookup::LT_Framework);
10175       break;
10176     }
10177   };
10178 
10179   // Finally with all our helpers, we can scan the include path.
10180   // Do this in standard order so deduplication keeps the right file.
10181   // (In case we decide to add more details to the results later).
10182   const auto &S = PP.getHeaderSearchInfo();
10183   using llvm::make_range;
10184   if (!Angled) {
10185     // The current directory is on the include path for "quoted" includes.
10186     if (auto CurFile = PP.getCurrentFileLexer()->getFileEntry())
10187       AddFilesFromIncludeDir(CurFile->getDir().getName(), false,
10188                              DirectoryLookup::LT_NormalDir);
10189     for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end()))
10190       AddFilesFromDirLookup(D, false);
10191   }
10192   for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end()))
10193     AddFilesFromDirLookup(D, false);
10194   for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end()))
10195     AddFilesFromDirLookup(D, true);
10196 
10197   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10198                             Results.data(), Results.size());
10199 }
10200 
10201 void Sema::CodeCompleteNaturalLanguage() {
10202   HandleCodeCompleteResults(this, CodeCompleter,
10203                             CodeCompletionContext::CCC_NaturalLanguage, nullptr,
10204                             0);
10205 }
10206 
10207 void Sema::CodeCompleteAvailabilityPlatformName() {
10208   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10209                         CodeCompleter->getCodeCompletionTUInfo(),
10210                         CodeCompletionContext::CCC_Other);
10211   Results.EnterNewScope();
10212   static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
10213   for (const char *Platform : llvm::ArrayRef(Platforms)) {
10214     Results.AddResult(CodeCompletionResult(Platform));
10215     Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
10216         Twine(Platform) + "ApplicationExtension")));
10217   }
10218   Results.ExitScope();
10219   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10220                             Results.data(), Results.size());
10221 }
10222 
10223 void Sema::GatherGlobalCodeCompletions(
10224     CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
10225     SmallVectorImpl<CodeCompletionResult> &Results) {
10226   ResultBuilder Builder(*this, Allocator, CCTUInfo,
10227                         CodeCompletionContext::CCC_Recovery);
10228   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
10229     CodeCompletionDeclConsumer Consumer(Builder,
10230                                         Context.getTranslationUnitDecl());
10231     LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
10232                        Consumer,
10233                        !CodeCompleter || CodeCompleter->loadExternal());
10234   }
10235 
10236   if (!CodeCompleter || CodeCompleter->includeMacros())
10237     AddMacroResults(PP, Builder,
10238                     !CodeCompleter || CodeCompleter->loadExternal(), true);
10239 
10240   Results.clear();
10241   Results.insert(Results.end(), Builder.data(),
10242                  Builder.data() + Builder.size());
10243 }
10244