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