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