Bug Summary

File:clang/lib/Sema/SemaCodeComplete.cpp
Warning:line 8857, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaCodeComplete.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaCodeComplete.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaCodeComplete.cpp

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

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class TemplateParameterList;
65class Type;
66
67enum {
68 TypeAlignmentInBits = 4,
69 TypeAlignment = 1 << TypeAlignmentInBits
70};
71
72namespace serialization {
73 template <class T> class AbstractTypeReader;
74 template <class T> class AbstractTypeWriter;
75}
76
77} // namespace clang
78
79namespace llvm {
80
81 template <typename T>
82 struct PointerLikeTypeTraits;
83 template<>
84 struct PointerLikeTypeTraits< ::clang::Type*> {
85 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
86
87 static inline ::clang::Type *getFromVoidPointer(void *P) {
88 return static_cast< ::clang::Type*>(P);
89 }
90
91 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
92 };
93
94 template<>
95 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
96 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
97
98 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
99 return static_cast< ::clang::ExtQuals*>(P);
100 }
101
102 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
103 };
104
105} // namespace llvm
106
107namespace clang {
108
109class ASTContext;
110template <typename> class CanQual;
111class CXXRecordDecl;
112class DeclContext;
113class EnumDecl;
114class Expr;
115class ExtQualsTypeCommonBase;
116class FunctionDecl;
117class IdentifierInfo;
118class NamedDecl;
119class ObjCInterfaceDecl;
120class ObjCProtocolDecl;
121class ObjCTypeParamDecl;
122struct PrintingPolicy;
123class RecordDecl;
124class Stmt;
125class TagDecl;
126class TemplateArgument;
127class TemplateArgumentListInfo;
128class TemplateArgumentLoc;
129class TemplateTypeParmDecl;
130class TypedefNameDecl;
131class UnresolvedUsingTypenameDecl;
132
133using CanQualType = CanQual<Type>;
134
135// Provide forward declarations for all of the *Type classes.
136#define TYPE(Class, Base) class Class##Type;
137#include "clang/AST/TypeNodes.inc"
138
139/// The collection of all-type qualifiers we support.
140/// Clang supports five independent qualifiers:
141/// * C99: const, volatile, and restrict
142/// * MS: __unaligned
143/// * Embedded C (TR18037): address spaces
144/// * Objective C: the GC attributes (none, weak, or strong)
145class Qualifiers {
146public:
147 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
148 Const = 0x1,
149 Restrict = 0x2,
150 Volatile = 0x4,
151 CVRMask = Const | Volatile | Restrict
152 };
153
154 enum GC {
155 GCNone = 0,
156 Weak,
157 Strong
158 };
159
160 enum ObjCLifetime {
161 /// There is no lifetime qualification on this type.
162 OCL_None,
163
164 /// This object can be modified without requiring retains or
165 /// releases.
166 OCL_ExplicitNone,
167
168 /// Assigning into this object requires the old value to be
169 /// released and the new value to be retained. The timing of the
170 /// release of the old value is inexact: it may be moved to
171 /// immediately after the last known point where the value is
172 /// live.
173 OCL_Strong,
174
175 /// Reading or writing from this object requires a barrier call.
176 OCL_Weak,
177
178 /// Assigning into this object requires a lifetime extension.
179 OCL_Autoreleasing
180 };
181
182 enum {
183 /// The maximum supported address space number.
184 /// 23 bits should be enough for anyone.
185 MaxAddressSpace = 0x7fffffu,
186
187 /// The width of the "fast" qualifier mask.
188 FastWidth = 3,
189
190 /// The fast qualifier mask.
191 FastMask = (1 << FastWidth) - 1
192 };
193
194 /// Returns the common set of qualifiers while removing them from
195 /// the given sets.
196 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
197 // If both are only CVR-qualified, bit operations are sufficient.
198 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
199 Qualifiers Q;
200 Q.Mask = L.Mask & R.Mask;
201 L.Mask &= ~Q.Mask;
202 R.Mask &= ~Q.Mask;
203 return Q;
204 }
205
206 Qualifiers Q;
207 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
208 Q.addCVRQualifiers(CommonCRV);
209 L.removeCVRQualifiers(CommonCRV);
210 R.removeCVRQualifiers(CommonCRV);
211
212 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
213 Q.setObjCGCAttr(L.getObjCGCAttr());
214 L.removeObjCGCAttr();
215 R.removeObjCGCAttr();
216 }
217
218 if (L.getObjCLifetime() == R.getObjCLifetime()) {
219 Q.setObjCLifetime(L.getObjCLifetime());
220 L.removeObjCLifetime();
221 R.removeObjCLifetime();
222 }
223
224 if (L.getAddressSpace() == R.getAddressSpace()) {
225 Q.setAddressSpace(L.getAddressSpace());
226 L.removeAddressSpace();
227 R.removeAddressSpace();
228 }
229 return Q;
230 }
231
232 static Qualifiers fromFastMask(unsigned Mask) {
233 Qualifiers Qs;
234 Qs.addFastQualifiers(Mask);
235 return Qs;
236 }
237
238 static Qualifiers fromCVRMask(unsigned CVR) {
239 Qualifiers Qs;
240 Qs.addCVRQualifiers(CVR);
241 return Qs;
242 }
243
244 static Qualifiers fromCVRUMask(unsigned CVRU) {
245 Qualifiers Qs;
246 Qs.addCVRUQualifiers(CVRU);
247 return Qs;
248 }
249
250 // Deserialize qualifiers from an opaque representation.
251 static Qualifiers fromOpaqueValue(unsigned opaque) {
252 Qualifiers Qs;
253 Qs.Mask = opaque;
254 return Qs;
255 }
256
257 // Serialize these qualifiers into an opaque representation.
258 unsigned getAsOpaqueValue() const {
259 return Mask;
260 }
261
262 bool hasConst() const { return Mask & Const; }
263 bool hasOnlyConst() const { return Mask == Const; }
264 void removeConst() { Mask &= ~Const; }
265 void addConst() { Mask |= Const; }
266
267 bool hasVolatile() const { return Mask & Volatile; }
268 bool hasOnlyVolatile() const { return Mask == Volatile; }
269 void removeVolatile() { Mask &= ~Volatile; }
270 void addVolatile() { Mask |= Volatile; }
271
272 bool hasRestrict() const { return Mask & Restrict; }
273 bool hasOnlyRestrict() const { return Mask == Restrict; }
274 void removeRestrict() { Mask &= ~Restrict; }
275 void addRestrict() { Mask |= Restrict; }
276
277 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
278 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
279 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
280
281 void setCVRQualifiers(unsigned mask) {
282 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast<void> (0));
283 Mask = (Mask & ~CVRMask) | mask;
284 }
285 void removeCVRQualifiers(unsigned mask) {
286 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast<void> (0));
287 Mask &= ~mask;
288 }
289 void removeCVRQualifiers() {
290 removeCVRQualifiers(CVRMask);
291 }
292 void addCVRQualifiers(unsigned mask) {
293 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast<void> (0));
294 Mask |= mask;
295 }
296 void addCVRUQualifiers(unsigned mask) {
297 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")(static_cast<void> (0));
298 Mask |= mask;
299 }
300
301 bool hasUnaligned() const { return Mask & UMask; }
302 void setUnaligned(bool flag) {
303 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
304 }
305 void removeUnaligned() { Mask &= ~UMask; }
306 void addUnaligned() { Mask |= UMask; }
307
308 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
309 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
310 void setObjCGCAttr(GC type) {
311 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
312 }
313 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
314 void addObjCGCAttr(GC type) {
315 assert(type)(static_cast<void> (0));
316 setObjCGCAttr(type);
317 }
318 Qualifiers withoutObjCGCAttr() const {
319 Qualifiers qs = *this;
320 qs.removeObjCGCAttr();
321 return qs;
322 }
323 Qualifiers withoutObjCLifetime() const {
324 Qualifiers qs = *this;
325 qs.removeObjCLifetime();
326 return qs;
327 }
328 Qualifiers withoutAddressSpace() const {
329 Qualifiers qs = *this;
330 qs.removeAddressSpace();
331 return qs;
332 }
333
334 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
335 ObjCLifetime getObjCLifetime() const {
336 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
337 }
338 void setObjCLifetime(ObjCLifetime type) {
339 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
340 }
341 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
342 void addObjCLifetime(ObjCLifetime type) {
343 assert(type)(static_cast<void> (0));
344 assert(!hasObjCLifetime())(static_cast<void> (0));
345 Mask |= (type << LifetimeShift);
346 }
347
348 /// True if the lifetime is neither None or ExplicitNone.
349 bool hasNonTrivialObjCLifetime() const {
350 ObjCLifetime lifetime = getObjCLifetime();
351 return (lifetime > OCL_ExplicitNone);
352 }
353
354 /// True if the lifetime is either strong or weak.
355 bool hasStrongOrWeakObjCLifetime() const {
356 ObjCLifetime lifetime = getObjCLifetime();
357 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
358 }
359
360 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
361 LangAS getAddressSpace() const {
362 return static_cast<LangAS>(Mask >> AddressSpaceShift);
363 }
364 bool hasTargetSpecificAddressSpace() const {
365 return isTargetAddressSpace(getAddressSpace());
366 }
367 /// Get the address space attribute value to be printed by diagnostics.
368 unsigned getAddressSpaceAttributePrintValue() const {
369 auto Addr = getAddressSpace();
370 // This function is not supposed to be used with language specific
371 // address spaces. If that happens, the diagnostic message should consider
372 // printing the QualType instead of the address space value.
373 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())(static_cast<void> (0));
374 if (Addr != LangAS::Default)
375 return toTargetAddressSpace(Addr);
376 // TODO: The diagnostic messages where Addr may be 0 should be fixed
377 // since it cannot differentiate the situation where 0 denotes the default
378 // address space or user specified __attribute__((address_space(0))).
379 return 0;
380 }
381 void setAddressSpace(LangAS space) {
382 assert((unsigned)space <= MaxAddressSpace)(static_cast<void> (0));
383 Mask = (Mask & ~AddressSpaceMask)
384 | (((uint32_t) space) << AddressSpaceShift);
385 }
386 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
387 void addAddressSpace(LangAS space) {
388 assert(space != LangAS::Default)(static_cast<void> (0));
389 setAddressSpace(space);
390 }
391
392 // Fast qualifiers are those that can be allocated directly
393 // on a QualType object.
394 bool hasFastQualifiers() const { return getFastQualifiers(); }
395 unsigned getFastQualifiers() const { return Mask & FastMask; }
396 void setFastQualifiers(unsigned mask) {
397 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast<void> (0));
398 Mask = (Mask & ~FastMask) | mask;
399 }
400 void removeFastQualifiers(unsigned mask) {
401 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast<void> (0));
402 Mask &= ~mask;
403 }
404 void removeFastQualifiers() {
405 removeFastQualifiers(FastMask);
406 }
407 void addFastQualifiers(unsigned mask) {
408 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast<void> (0));
409 Mask |= mask;
410 }
411
412 /// Return true if the set contains any qualifiers which require an ExtQuals
413 /// node to be allocated.
414 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
415 Qualifiers getNonFastQualifiers() const {
416 Qualifiers Quals = *this;
417 Quals.setFastQualifiers(0);
418 return Quals;
419 }
420
421 /// Return true if the set contains any qualifiers.
422 bool hasQualifiers() const { return Mask; }
423 bool empty() const { return !Mask; }
424
425 /// Add the qualifiers from the given set to this set.
426 void addQualifiers(Qualifiers Q) {
427 // If the other set doesn't have any non-boolean qualifiers, just
428 // bit-or it in.
429 if (!(Q.Mask & ~CVRMask))
430 Mask |= Q.Mask;
431 else {
432 Mask |= (Q.Mask & CVRMask);
433 if (Q.hasAddressSpace())
434 addAddressSpace(Q.getAddressSpace());
435 if (Q.hasObjCGCAttr())
436 addObjCGCAttr(Q.getObjCGCAttr());
437 if (Q.hasObjCLifetime())
438 addObjCLifetime(Q.getObjCLifetime());
439 }
440 }
441
442 /// Remove the qualifiers from the given set from this set.
443 void removeQualifiers(Qualifiers Q) {
444 // If the other set doesn't have any non-boolean qualifiers, just
445 // bit-and the inverse in.
446 if (!(Q.Mask & ~CVRMask))
447 Mask &= ~Q.Mask;
448 else {
449 Mask &= ~(Q.Mask & CVRMask);
450 if (getObjCGCAttr() == Q.getObjCGCAttr())
451 removeObjCGCAttr();
452 if (getObjCLifetime() == Q.getObjCLifetime())
453 removeObjCLifetime();
454 if (getAddressSpace() == Q.getAddressSpace())
455 removeAddressSpace();
456 }
457 }
458
459 /// Add the qualifiers from the given set to this set, given that
460 /// they don't conflict.
461 void addConsistentQualifiers(Qualifiers qs) {
462 assert(getAddressSpace() == qs.getAddressSpace() ||(static_cast<void> (0))
463 !hasAddressSpace() || !qs.hasAddressSpace())(static_cast<void> (0));
464 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||(static_cast<void> (0))
465 !hasObjCGCAttr() || !qs.hasObjCGCAttr())(static_cast<void> (0));
466 assert(getObjCLifetime() == qs.getObjCLifetime() ||(static_cast<void> (0))
467 !hasObjCLifetime() || !qs.hasObjCLifetime())(static_cast<void> (0));
468 Mask |= qs.Mask;
469 }
470
471 /// Returns true if address space A is equal to or a superset of B.
472 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
473 /// overlapping address spaces.
474 /// CL1.1 or CL1.2:
475 /// every address space is a superset of itself.
476 /// CL2.0 adds:
477 /// __generic is a superset of any address space except for __constant.
478 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
479 // Address spaces must match exactly.
480 return A == B ||
481 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
482 // for __constant can be used as __generic.
483 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
484 // We also define global_device and global_host address spaces,
485 // to distinguish global pointers allocated on host from pointers
486 // allocated on device, which are a subset of __global.
487 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
488 B == LangAS::opencl_global_host)) ||
489 (A == LangAS::sycl_global && (B == LangAS::sycl_global_device ||
490 B == LangAS::sycl_global_host)) ||
491 // Consider pointer size address spaces to be equivalent to default.
492 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
493 (isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
494 // Default is a superset of SYCL address spaces.
495 (A == LangAS::Default &&
496 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
497 B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
498 B == LangAS::sycl_global_host)) ||
499 // In HIP device compilation, any cuda address space is allowed
500 // to implicitly cast into the default address space.
501 (A == LangAS::Default &&
502 (B == LangAS::cuda_constant || B == LangAS::cuda_device ||
503 B == LangAS::cuda_shared));
504 }
505
506 /// Returns true if the address space in these qualifiers is equal to or
507 /// a superset of the address space in the argument qualifiers.
508 bool isAddressSpaceSupersetOf(Qualifiers other) const {
509 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
510 }
511
512 /// Determines if these qualifiers compatibly include another set.
513 /// Generally this answers the question of whether an object with the other
514 /// qualifiers can be safely used as an object with these qualifiers.
515 bool compatiblyIncludes(Qualifiers other) const {
516 return isAddressSpaceSupersetOf(other) &&
517 // ObjC GC qualifiers can match, be added, or be removed, but can't
518 // be changed.
519 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
520 !other.hasObjCGCAttr()) &&
521 // ObjC lifetime qualifiers must match exactly.
522 getObjCLifetime() == other.getObjCLifetime() &&
523 // CVR qualifiers may subset.
524 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
525 // U qualifier may superset.
526 (!other.hasUnaligned() || hasUnaligned());
527 }
528
529 /// Determines if these qualifiers compatibly include another set of
530 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
531 ///
532 /// One set of Objective-C lifetime qualifiers compatibly includes the other
533 /// if the lifetime qualifiers match, or if both are non-__weak and the
534 /// including set also contains the 'const' qualifier, or both are non-__weak
535 /// and one is None (which can only happen in non-ARC modes).
536 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
537 if (getObjCLifetime() == other.getObjCLifetime())
538 return true;
539
540 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
541 return false;
542
543 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
544 return true;
545
546 return hasConst();
547 }
548
549 /// Determine whether this set of qualifiers is a strict superset of
550 /// another set of qualifiers, not considering qualifier compatibility.
551 bool isStrictSupersetOf(Qualifiers Other) const;
552
553 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
554 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
555
556 explicit operator bool() const { return hasQualifiers(); }
557
558 Qualifiers &operator+=(Qualifiers R) {
559 addQualifiers(R);
560 return *this;
561 }
562
563 // Union two qualifier sets. If an enumerated qualifier appears
564 // in both sets, use the one from the right.
565 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
566 L += R;
567 return L;
568 }
569
570 Qualifiers &operator-=(Qualifiers R) {
571 removeQualifiers(R);
572 return *this;
573 }
574
575 /// Compute the difference between two qualifier sets.
576 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
577 L -= R;
578 return L;
579 }
580
581 std::string getAsString() const;
582 std::string getAsString(const PrintingPolicy &Policy) const;
583
584 static std::string getAddrSpaceAsString(LangAS AS);
585
586 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
587 void print(raw_ostream &OS, const PrintingPolicy &Policy,
588 bool appendSpaceIfNonEmpty = false) const;
589
590 void Profile(llvm::FoldingSetNodeID &ID) const {
591 ID.AddInteger(Mask);
592 }
593
594private:
595 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
596 // |C R V|U|GCAttr|Lifetime|AddressSpace|
597 uint32_t Mask = 0;
598
599 static const uint32_t UMask = 0x8;
600 static const uint32_t UShift = 3;
601 static const uint32_t GCAttrMask = 0x30;
602 static const uint32_t GCAttrShift = 4;
603 static const uint32_t LifetimeMask = 0x1C0;
604 static const uint32_t LifetimeShift = 6;
605 static const uint32_t AddressSpaceMask =
606 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
607 static const uint32_t AddressSpaceShift = 9;
608};
609
610/// A std::pair-like structure for storing a qualified type split
611/// into its local qualifiers and its locally-unqualified type.
612struct SplitQualType {
613 /// The locally-unqualified type.
614 const Type *Ty = nullptr;
615
616 /// The local qualifiers.
617 Qualifiers Quals;
618
619 SplitQualType() = default;
620 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
621
622 SplitQualType getSingleStepDesugaredType() const; // end of this file
623
624 // Make std::tie work.
625 std::pair<const Type *,Qualifiers> asPair() const {
626 return std::pair<const Type *, Qualifiers>(Ty, Quals);
627 }
628
629 friend bool operator==(SplitQualType a, SplitQualType b) {
630 return a.Ty == b.Ty && a.Quals == b.Quals;
631 }
632 friend bool operator!=(SplitQualType a, SplitQualType b) {
633 return a.Ty != b.Ty || a.Quals != b.Quals;
634 }
635};
636
637/// The kind of type we are substituting Objective-C type arguments into.
638///
639/// The kind of substitution affects the replacement of type parameters when
640/// no concrete type information is provided, e.g., when dealing with an
641/// unspecialized type.
642enum class ObjCSubstitutionContext {
643 /// An ordinary type.
644 Ordinary,
645
646 /// The result type of a method or function.
647 Result,
648
649 /// The parameter type of a method or function.
650 Parameter,
651
652 /// The type of a property.
653 Property,
654
655 /// The superclass of a type.
656 Superclass,
657};
658
659/// A (possibly-)qualified type.
660///
661/// For efficiency, we don't store CV-qualified types as nodes on their
662/// own: instead each reference to a type stores the qualifiers. This
663/// greatly reduces the number of nodes we need to allocate for types (for
664/// example we only need one for 'int', 'const int', 'volatile int',
665/// 'const volatile int', etc).
666///
667/// As an added efficiency bonus, instead of making this a pair, we
668/// just store the two bits we care about in the low bits of the
669/// pointer. To handle the packing/unpacking, we make QualType be a
670/// simple wrapper class that acts like a smart pointer. A third bit
671/// indicates whether there are extended qualifiers present, in which
672/// case the pointer points to a special structure.
673class QualType {
674 friend class QualifierCollector;
675
676 // Thankfully, these are efficiently composable.
677 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
678 Qualifiers::FastWidth> Value;
679
680 const ExtQuals *getExtQualsUnsafe() const {
681 return Value.getPointer().get<const ExtQuals*>();
682 }
683
684 const Type *getTypePtrUnsafe() const {
685 return Value.getPointer().get<const Type*>();
686 }
687
688 const ExtQualsTypeCommonBase *getCommonPtr() const {
689 assert(!isNull() && "Cannot retrieve a NULL type pointer")(static_cast<void> (0));
690 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
691 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
692 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
693 }
694
695public:
696 QualType() = default;
697 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
698 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
699
700 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
701 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
702
703 /// Retrieves a pointer to the underlying (unqualified) type.
704 ///
705 /// This function requires that the type not be NULL. If the type might be
706 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
707 const Type *getTypePtr() const;
708
709 const Type *getTypePtrOrNull() const;
710
711 /// Retrieves a pointer to the name of the base type.
712 const IdentifierInfo *getBaseTypeIdentifier() const;
713
714 /// Divides a QualType into its unqualified type and a set of local
715 /// qualifiers.
716 SplitQualType split() const;
717
718 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
719
720 static QualType getFromOpaquePtr(const void *Ptr) {
721 QualType T;
722 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
723 return T;
724 }
725
726 const Type &operator*() const {
727 return *getTypePtr();
728 }
729
730 const Type *operator->() const {
731 return getTypePtr();
732 }
733
734 bool isCanonical() const;
735 bool isCanonicalAsParam() const;
736
737 /// Return true if this QualType doesn't point to a type yet.
738 bool isNull() const {
739 return Value.getPointer().isNull();
12
Calling 'PointerUnion::isNull'
15
Returning from 'PointerUnion::isNull'
16
Returning zero, which participates in a condition later
740 }
741
742 /// Determine whether this particular QualType instance has the
743 /// "const" qualifier set, without looking through typedefs that may have
744 /// added "const" at a different level.
745 bool isLocalConstQualified() const {
746 return (getLocalFastQualifiers() & Qualifiers::Const);
747 }
748
749 /// Determine whether this type is const-qualified.
750 bool isConstQualified() const;
751
752 /// Determine whether this particular QualType instance has the
753 /// "restrict" qualifier set, without looking through typedefs that may have
754 /// added "restrict" at a different level.
755 bool isLocalRestrictQualified() const {
756 return (getLocalFastQualifiers() & Qualifiers::Restrict);
757 }
758
759 /// Determine whether this type is restrict-qualified.
760 bool isRestrictQualified() const;
761
762 /// Determine whether this particular QualType instance has the
763 /// "volatile" qualifier set, without looking through typedefs that may have
764 /// added "volatile" at a different level.
765 bool isLocalVolatileQualified() const {
766 return (getLocalFastQualifiers() & Qualifiers::Volatile);
767 }
768
769 /// Determine whether this type is volatile-qualified.
770 bool isVolatileQualified() const;
771
772 /// Determine whether this particular QualType instance has any
773 /// qualifiers, without looking through any typedefs that might add
774 /// qualifiers at a different level.
775 bool hasLocalQualifiers() const {
776 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
777 }
778
779 /// Determine whether this type has any qualifiers.
780 bool hasQualifiers() const;
781
782 /// Determine whether this particular QualType instance has any
783 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
784 /// instance.
785 bool hasLocalNonFastQualifiers() const {
786 return Value.getPointer().is<const ExtQuals*>();
787 }
788
789 /// Retrieve the set of qualifiers local to this particular QualType
790 /// instance, not including any qualifiers acquired through typedefs or
791 /// other sugar.
792 Qualifiers getLocalQualifiers() const;
793
794 /// Retrieve the set of qualifiers applied to this type.
795 Qualifiers getQualifiers() const;
796
797 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
798 /// local to this particular QualType instance, not including any qualifiers
799 /// acquired through typedefs or other sugar.
800 unsigned getLocalCVRQualifiers() const {
801 return getLocalFastQualifiers();
802 }
803
804 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
805 /// applied to this type.
806 unsigned getCVRQualifiers() const;
807
808 bool isConstant(const ASTContext& Ctx) const {
809 return QualType::isConstant(*this, Ctx);
810 }
811
812 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
813 bool isPODType(const ASTContext &Context) const;
814
815 /// Return true if this is a POD type according to the rules of the C++98
816 /// standard, regardless of the current compilation's language.
817 bool isCXX98PODType(const ASTContext &Context) const;
818
819 /// Return true if this is a POD type according to the more relaxed rules
820 /// of the C++11 standard, regardless of the current compilation's language.
821 /// (C++0x [basic.types]p9). Note that, unlike
822 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
823 bool isCXX11PODType(const ASTContext &Context) const;
824
825 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
826 bool isTrivialType(const ASTContext &Context) const;
827
828 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
829 bool isTriviallyCopyableType(const ASTContext &Context) const;
830
831
832 /// Returns true if it is a class and it might be dynamic.
833 bool mayBeDynamicClass() const;
834
835 /// Returns true if it is not a class or if the class might not be dynamic.
836 bool mayBeNotDynamicClass() const;
837
838 // Don't promise in the API that anything besides 'const' can be
839 // easily added.
840
841 /// Add the `const` type qualifier to this QualType.
842 void addConst() {
843 addFastQualifiers(Qualifiers::Const);
844 }
845 QualType withConst() const {
846 return withFastQualifiers(Qualifiers::Const);
847 }
848
849 /// Add the `volatile` type qualifier to this QualType.
850 void addVolatile() {
851 addFastQualifiers(Qualifiers::Volatile);
852 }
853 QualType withVolatile() const {
854 return withFastQualifiers(Qualifiers::Volatile);
855 }
856
857 /// Add the `restrict` qualifier to this QualType.
858 void addRestrict() {
859 addFastQualifiers(Qualifiers::Restrict);
860 }
861 QualType withRestrict() const {
862 return withFastQualifiers(Qualifiers::Restrict);
863 }
864
865 QualType withCVRQualifiers(unsigned CVR) const {
866 return withFastQualifiers(CVR);
867 }
868
869 void addFastQualifiers(unsigned TQs) {
870 assert(!(TQs & ~Qualifiers::FastMask)(static_cast<void> (0))
871 && "non-fast qualifier bits set in mask!")(static_cast<void> (0));
872 Value.setInt(Value.getInt() | TQs);
873 }
874
875 void removeLocalConst();
876 void removeLocalVolatile();
877 void removeLocalRestrict();
878 void removeLocalCVRQualifiers(unsigned Mask);
879
880 void removeLocalFastQualifiers() { Value.setInt(0); }
881 void removeLocalFastQualifiers(unsigned Mask) {
882 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")(static_cast<void> (0));
883 Value.setInt(Value.getInt() & ~Mask);
884 }
885
886 // Creates a type with the given qualifiers in addition to any
887 // qualifiers already on this type.
888 QualType withFastQualifiers(unsigned TQs) const {
889 QualType T = *this;
890 T.addFastQualifiers(TQs);
891 return T;
892 }
893
894 // Creates a type with exactly the given fast qualifiers, removing
895 // any existing fast qualifiers.
896 QualType withExactLocalFastQualifiers(unsigned TQs) const {
897 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
898 }
899
900 // Removes fast qualifiers, but leaves any extended qualifiers in place.
901 QualType withoutLocalFastQualifiers() const {
902 QualType T = *this;
903 T.removeLocalFastQualifiers();
904 return T;
905 }
906
907 QualType getCanonicalType() const;
908
909 /// Return this type with all of the instance-specific qualifiers
910 /// removed, but without removing any qualifiers that may have been applied
911 /// through typedefs.
912 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
913
914 /// Retrieve the unqualified variant of the given type,
915 /// removing as little sugar as possible.
916 ///
917 /// This routine looks through various kinds of sugar to find the
918 /// least-desugared type that is unqualified. For example, given:
919 ///
920 /// \code
921 /// typedef int Integer;
922 /// typedef const Integer CInteger;
923 /// typedef CInteger DifferenceType;
924 /// \endcode
925 ///
926 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
927 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
928 ///
929 /// The resulting type might still be qualified if it's sugar for an array
930 /// type. To strip qualifiers even from within a sugared array type, use
931 /// ASTContext::getUnqualifiedArrayType.
932 inline QualType getUnqualifiedType() const;
933
934 /// Retrieve the unqualified variant of the given type, removing as little
935 /// sugar as possible.
936 ///
937 /// Like getUnqualifiedType(), but also returns the set of
938 /// qualifiers that were built up.
939 ///
940 /// The resulting type might still be qualified if it's sugar for an array
941 /// type. To strip qualifiers even from within a sugared array type, use
942 /// ASTContext::getUnqualifiedArrayType.
943 inline SplitQualType getSplitUnqualifiedType() const;
944
945 /// Determine whether this type is more qualified than the other
946 /// given type, requiring exact equality for non-CVR qualifiers.
947 bool isMoreQualifiedThan(QualType Other) const;
948
949 /// Determine whether this type is at least as qualified as the other
950 /// given type, requiring exact equality for non-CVR qualifiers.
951 bool isAtLeastAsQualifiedAs(QualType Other) const;
952
953 QualType getNonReferenceType() const;
954
955 /// Determine the type of a (typically non-lvalue) expression with the
956 /// specified result type.
957 ///
958 /// This routine should be used for expressions for which the return type is
959 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
960 /// an lvalue. It removes a top-level reference (since there are no
961 /// expressions of reference type) and deletes top-level cvr-qualifiers
962 /// from non-class types (in C++) or all types (in C).
963 QualType getNonLValueExprType(const ASTContext &Context) const;
964
965 /// Remove an outer pack expansion type (if any) from this type. Used as part
966 /// of converting the type of a declaration to the type of an expression that
967 /// references that expression. It's meaningless for an expression to have a
968 /// pack expansion type.
969 QualType getNonPackExpansionType() const;
970
971 /// Return the specified type with any "sugar" removed from
972 /// the type. This takes off typedefs, typeof's etc. If the outer level of
973 /// the type is already concrete, it returns it unmodified. This is similar
974 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
975 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
976 /// concrete.
977 ///
978 /// Qualifiers are left in place.
979 QualType getDesugaredType(const ASTContext &Context) const {
980 return getDesugaredType(*this, Context);
981 }
982
983 SplitQualType getSplitDesugaredType() const {
984 return getSplitDesugaredType(*this);
985 }
986
987 /// Return the specified type with one level of "sugar" removed from
988 /// the type.
989 ///
990 /// This routine takes off the first typedef, typeof, etc. If the outer level
991 /// of the type is already concrete, it returns it unmodified.
992 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
993 return getSingleStepDesugaredTypeImpl(*this, Context);
994 }
995
996 /// Returns the specified type after dropping any
997 /// outer-level parentheses.
998 QualType IgnoreParens() const {
999 if (isa<ParenType>(*this))
1000 return QualType::IgnoreParens(*this);
1001 return *this;
1002 }
1003
1004 /// Indicate whether the specified types and qualifiers are identical.
1005 friend bool operator==(const QualType &LHS, const QualType &RHS) {
1006 return LHS.Value == RHS.Value;
1007 }
1008 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1009 return LHS.Value != RHS.Value;
1010 }
1011 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1012 return LHS.Value < RHS.Value;
1013 }
1014
1015 static std::string getAsString(SplitQualType split,
1016 const PrintingPolicy &Policy) {
1017 return getAsString(split.Ty, split.Quals, Policy);
1018 }
1019 static std::string getAsString(const Type *ty, Qualifiers qs,
1020 const PrintingPolicy &Policy);
1021
1022 std::string getAsString() const;
1023 std::string getAsString(const PrintingPolicy &Policy) const;
1024
1025 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1026 const Twine &PlaceHolder = Twine(),
1027 unsigned Indentation = 0) const;
1028
1029 static void print(SplitQualType split, raw_ostream &OS,
1030 const PrintingPolicy &policy, const Twine &PlaceHolder,
1031 unsigned Indentation = 0) {
1032 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1033 }
1034
1035 static void print(const Type *ty, Qualifiers qs,
1036 raw_ostream &OS, const PrintingPolicy &policy,
1037 const Twine &PlaceHolder,
1038 unsigned Indentation = 0);
1039
1040 void getAsStringInternal(std::string &Str,
1041 const PrintingPolicy &Policy) const;
1042
1043 static void getAsStringInternal(SplitQualType split, std::string &out,
1044 const PrintingPolicy &policy) {
1045 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1046 }
1047
1048 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1049 std::string &out,
1050 const PrintingPolicy &policy);
1051
1052 class StreamedQualTypeHelper {
1053 const QualType &T;
1054 const PrintingPolicy &Policy;
1055 const Twine &PlaceHolder;
1056 unsigned Indentation;
1057
1058 public:
1059 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1060 const Twine &PlaceHolder, unsigned Indentation)
1061 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1062 Indentation(Indentation) {}
1063
1064 friend raw_ostream &operator<<(raw_ostream &OS,
1065 const StreamedQualTypeHelper &SQT) {
1066 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1067 return OS;
1068 }
1069 };
1070
1071 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1072 const Twine &PlaceHolder = Twine(),
1073 unsigned Indentation = 0) const {
1074 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1075 }
1076
1077 void dump(const char *s) const;
1078 void dump() const;
1079 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1080
1081 void Profile(llvm::FoldingSetNodeID &ID) const {
1082 ID.AddPointer(getAsOpaquePtr());
1083 }
1084
1085 /// Check if this type has any address space qualifier.
1086 inline bool hasAddressSpace() const;
1087
1088 /// Return the address space of this type.
1089 inline LangAS getAddressSpace() const;
1090
1091 /// Returns true if address space qualifiers overlap with T address space
1092 /// qualifiers.
1093 /// OpenCL C defines conversion rules for pointers to different address spaces
1094 /// and notion of overlapping address spaces.
1095 /// CL1.1 or CL1.2:
1096 /// address spaces overlap iff they are they same.
1097 /// OpenCL C v2.0 s6.5.5 adds:
1098 /// __generic overlaps with any address space except for __constant.
1099 bool isAddressSpaceOverlapping(QualType T) const {
1100 Qualifiers Q = getQualifiers();
1101 Qualifiers TQ = T.getQualifiers();
1102 // Address spaces overlap if at least one of them is a superset of another
1103 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1104 }
1105
1106 /// Returns gc attribute of this type.
1107 inline Qualifiers::GC getObjCGCAttr() const;
1108
1109 /// true when Type is objc's weak.
1110 bool isObjCGCWeak() const {
1111 return getObjCGCAttr() == Qualifiers::Weak;
1112 }
1113
1114 /// true when Type is objc's strong.
1115 bool isObjCGCStrong() const {
1116 return getObjCGCAttr() == Qualifiers::Strong;
1117 }
1118
1119 /// Returns lifetime attribute of this type.
1120 Qualifiers::ObjCLifetime getObjCLifetime() const {
1121 return getQualifiers().getObjCLifetime();
1122 }
1123
1124 bool hasNonTrivialObjCLifetime() const {
1125 return getQualifiers().hasNonTrivialObjCLifetime();
1126 }
1127
1128 bool hasStrongOrWeakObjCLifetime() const {
1129 return getQualifiers().hasStrongOrWeakObjCLifetime();
1130 }
1131
1132 // true when Type is objc's weak and weak is enabled but ARC isn't.
1133 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1134
1135 enum PrimitiveDefaultInitializeKind {
1136 /// The type does not fall into any of the following categories. Note that
1137 /// this case is zero-valued so that values of this enum can be used as a
1138 /// boolean condition for non-triviality.
1139 PDIK_Trivial,
1140
1141 /// The type is an Objective-C retainable pointer type that is qualified
1142 /// with the ARC __strong qualifier.
1143 PDIK_ARCStrong,
1144
1145 /// The type is an Objective-C retainable pointer type that is qualified
1146 /// with the ARC __weak qualifier.
1147 PDIK_ARCWeak,
1148
1149 /// The type is a struct containing a field whose type is not PCK_Trivial.
1150 PDIK_Struct
1151 };
1152
1153 /// Functions to query basic properties of non-trivial C struct types.
1154
1155 /// Check if this is a non-trivial type that would cause a C struct
1156 /// transitively containing this type to be non-trivial to default initialize
1157 /// and return the kind.
1158 PrimitiveDefaultInitializeKind
1159 isNonTrivialToPrimitiveDefaultInitialize() const;
1160
1161 enum PrimitiveCopyKind {
1162 /// The type does not fall into any of the following categories. Note that
1163 /// this case is zero-valued so that values of this enum can be used as a
1164 /// boolean condition for non-triviality.
1165 PCK_Trivial,
1166
1167 /// The type would be trivial except that it is volatile-qualified. Types
1168 /// that fall into one of the other non-trivial cases may additionally be
1169 /// volatile-qualified.
1170 PCK_VolatileTrivial,
1171
1172 /// The type is an Objective-C retainable pointer type that is qualified
1173 /// with the ARC __strong qualifier.
1174 PCK_ARCStrong,
1175
1176 /// The type is an Objective-C retainable pointer type that is qualified
1177 /// with the ARC __weak qualifier.
1178 PCK_ARCWeak,
1179
1180 /// The type is a struct containing a field whose type is neither
1181 /// PCK_Trivial nor PCK_VolatileTrivial.
1182 /// Note that a C++ struct type does not necessarily match this; C++ copying
1183 /// semantics are too complex to express here, in part because they depend
1184 /// on the exact constructor or assignment operator that is chosen by
1185 /// overload resolution to do the copy.
1186 PCK_Struct
1187 };
1188
1189 /// Check if this is a non-trivial type that would cause a C struct
1190 /// transitively containing this type to be non-trivial to copy and return the
1191 /// kind.
1192 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1193
1194 /// Check if this is a non-trivial type that would cause a C struct
1195 /// transitively containing this type to be non-trivial to destructively
1196 /// move and return the kind. Destructive move in this context is a C++-style
1197 /// move in which the source object is placed in a valid but unspecified state
1198 /// after it is moved, as opposed to a truly destructive move in which the
1199 /// source object is placed in an uninitialized state.
1200 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1201
1202 enum DestructionKind {
1203 DK_none,
1204 DK_cxx_destructor,
1205 DK_objc_strong_lifetime,
1206 DK_objc_weak_lifetime,
1207 DK_nontrivial_c_struct
1208 };
1209
1210 /// Returns a nonzero value if objects of this type require
1211 /// non-trivial work to clean up after. Non-zero because it's
1212 /// conceivable that qualifiers (objc_gc(weak)?) could make
1213 /// something require destruction.
1214 DestructionKind isDestructedType() const {
1215 return isDestructedTypeImpl(*this);
1216 }
1217
1218 /// Check if this is or contains a C union that is non-trivial to
1219 /// default-initialize, which is a union that has a member that is non-trivial
1220 /// to default-initialize. If this returns true,
1221 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1222 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1223
1224 /// Check if this is or contains a C union that is non-trivial to destruct,
1225 /// which is a union that has a member that is non-trivial to destruct. If
1226 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1227 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1228
1229 /// Check if this is or contains a C union that is non-trivial to copy, which
1230 /// is a union that has a member that is non-trivial to copy. If this returns
1231 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1232 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1233
1234 /// Determine whether expressions of the given type are forbidden
1235 /// from being lvalues in C.
1236 ///
1237 /// The expression types that are forbidden to be lvalues are:
1238 /// - 'void', but not qualified void
1239 /// - function types
1240 ///
1241 /// The exact rule here is C99 6.3.2.1:
1242 /// An lvalue is an expression with an object type or an incomplete
1243 /// type other than void.
1244 bool isCForbiddenLValueType() const;
1245
1246 /// Substitute type arguments for the Objective-C type parameters used in the
1247 /// subject type.
1248 ///
1249 /// \param ctx ASTContext in which the type exists.
1250 ///
1251 /// \param typeArgs The type arguments that will be substituted for the
1252 /// Objective-C type parameters in the subject type, which are generally
1253 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1254 /// parameters will be replaced with their bounds or id/Class, as appropriate
1255 /// for the context.
1256 ///
1257 /// \param context The context in which the subject type was written.
1258 ///
1259 /// \returns the resulting type.
1260 QualType substObjCTypeArgs(ASTContext &ctx,
1261 ArrayRef<QualType> typeArgs,
1262 ObjCSubstitutionContext context) const;
1263
1264 /// Substitute type arguments from an object type for the Objective-C type
1265 /// parameters used in the subject type.
1266 ///
1267 /// This operation combines the computation of type arguments for
1268 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1269 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1270 /// callers that need to perform a single substitution in isolation.
1271 ///
1272 /// \param objectType The type of the object whose member type we're
1273 /// substituting into. For example, this might be the receiver of a message
1274 /// or the base of a property access.
1275 ///
1276 /// \param dc The declaration context from which the subject type was
1277 /// retrieved, which indicates (for example) which type parameters should
1278 /// be substituted.
1279 ///
1280 /// \param context The context in which the subject type was written.
1281 ///
1282 /// \returns the subject type after replacing all of the Objective-C type
1283 /// parameters with their corresponding arguments.
1284 QualType substObjCMemberType(QualType objectType,
1285 const DeclContext *dc,
1286 ObjCSubstitutionContext context) const;
1287
1288 /// Strip Objective-C "__kindof" types from the given type.
1289 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1290
1291 /// Remove all qualifiers including _Atomic.
1292 QualType getAtomicUnqualifiedType() const;
1293
1294private:
1295 // These methods are implemented in a separate translation unit;
1296 // "static"-ize them to avoid creating temporary QualTypes in the
1297 // caller.
1298 static bool isConstant(QualType T, const ASTContext& Ctx);
1299 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1300 static SplitQualType getSplitDesugaredType(QualType T);
1301 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1302 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1303 const ASTContext &C);
1304 static QualType IgnoreParens(QualType T);
1305 static DestructionKind isDestructedTypeImpl(QualType type);
1306
1307 /// Check if \param RD is or contains a non-trivial C union.
1308 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1309 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1310 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1311};
1312
1313} // namespace clang
1314
1315namespace llvm {
1316
1317/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1318/// to a specific Type class.
1319template<> struct simplify_type< ::clang::QualType> {
1320 using SimpleType = const ::clang::Type *;
1321
1322 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1323 return Val.getTypePtr();
1324 }
1325};
1326
1327// Teach SmallPtrSet that QualType is "basically a pointer".
1328template<>
1329struct PointerLikeTypeTraits<clang::QualType> {
1330 static inline void *getAsVoidPointer(clang::QualType P) {
1331 return P.getAsOpaquePtr();
1332 }
1333
1334 static inline clang::QualType getFromVoidPointer(void *P) {
1335 return clang::QualType::getFromOpaquePtr(P);
1336 }
1337
1338 // Various qualifiers go in low bits.
1339 static constexpr int NumLowBitsAvailable = 0;
1340};
1341
1342} // namespace llvm
1343
1344namespace clang {
1345
1346/// Base class that is common to both the \c ExtQuals and \c Type
1347/// classes, which allows \c QualType to access the common fields between the
1348/// two.
1349class ExtQualsTypeCommonBase {
1350 friend class ExtQuals;
1351 friend class QualType;
1352 friend class Type;
1353
1354 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1355 /// a self-referential pointer (for \c Type).
1356 ///
1357 /// This pointer allows an efficient mapping from a QualType to its
1358 /// underlying type pointer.
1359 const Type *const BaseType;
1360
1361 /// The canonical type of this type. A QualType.
1362 QualType CanonicalType;
1363
1364 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1365 : BaseType(baseType), CanonicalType(canon) {}
1366};
1367
1368/// We can encode up to four bits in the low bits of a
1369/// type pointer, but there are many more type qualifiers that we want
1370/// to be able to apply to an arbitrary type. Therefore we have this
1371/// struct, intended to be heap-allocated and used by QualType to
1372/// store qualifiers.
1373///
1374/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1375/// in three low bits on the QualType pointer; a fourth bit records whether
1376/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1377/// Objective-C GC attributes) are much more rare.
1378class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1379 // NOTE: changing the fast qualifiers should be straightforward as
1380 // long as you don't make 'const' non-fast.
1381 // 1. Qualifiers:
1382 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1383 // Fast qualifiers must occupy the low-order bits.
1384 // b) Update Qualifiers::FastWidth and FastMask.
1385 // 2. QualType:
1386 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1387 // b) Update remove{Volatile,Restrict}, defined near the end of
1388 // this header.
1389 // 3. ASTContext:
1390 // a) Update get{Volatile,Restrict}Type.
1391
1392 /// The immutable set of qualifiers applied by this node. Always contains
1393 /// extended qualifiers.
1394 Qualifiers Quals;
1395
1396 ExtQuals *this_() { return this; }
1397
1398public:
1399 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1400 : ExtQualsTypeCommonBase(baseType,
1401 canon.isNull() ? QualType(this_(), 0) : canon),
1402 Quals(quals) {
1403 assert(Quals.hasNonFastQualifiers()(static_cast<void> (0))
1404 && "ExtQuals created with no fast qualifiers")(static_cast<void> (0));
1405 assert(!Quals.hasFastQualifiers()(static_cast<void> (0))
1406 && "ExtQuals created with fast qualifiers")(static_cast<void> (0));
1407 }
1408
1409 Qualifiers getQualifiers() const { return Quals; }
1410
1411 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1412 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1413
1414 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1415 Qualifiers::ObjCLifetime getObjCLifetime() const {
1416 return Quals.getObjCLifetime();
1417 }
1418
1419 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1420 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1421
1422 const Type *getBaseType() const { return BaseType; }
1423
1424public:
1425 void Profile(llvm::FoldingSetNodeID &ID) const {
1426 Profile(ID, getBaseType(), Quals);
1427 }
1428
1429 static void Profile(llvm::FoldingSetNodeID &ID,
1430 const Type *BaseType,
1431 Qualifiers Quals) {
1432 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")(static_cast<void> (0));
1433 ID.AddPointer(BaseType);
1434 Quals.Profile(ID);
1435 }
1436};
1437
1438/// The kind of C++11 ref-qualifier associated with a function type.
1439/// This determines whether a member function's "this" object can be an
1440/// lvalue, rvalue, or neither.
1441enum RefQualifierKind {
1442 /// No ref-qualifier was provided.
1443 RQ_None = 0,
1444
1445 /// An lvalue ref-qualifier was provided (\c &).
1446 RQ_LValue,
1447
1448 /// An rvalue ref-qualifier was provided (\c &&).
1449 RQ_RValue
1450};
1451
1452/// Which keyword(s) were used to create an AutoType.
1453enum class AutoTypeKeyword {
1454 /// auto
1455 Auto,
1456
1457 /// decltype(auto)
1458 DecltypeAuto,
1459
1460 /// __auto_type (GNU extension)
1461 GNUAutoType
1462};
1463
1464/// The base class of the type hierarchy.
1465///
1466/// A central concept with types is that each type always has a canonical
1467/// type. A canonical type is the type with any typedef names stripped out
1468/// of it or the types it references. For example, consider:
1469///
1470/// typedef int foo;
1471/// typedef foo* bar;
1472/// 'int *' 'foo *' 'bar'
1473///
1474/// There will be a Type object created for 'int'. Since int is canonical, its
1475/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1476/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1477/// there is a PointerType that represents 'int*', which, like 'int', is
1478/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1479/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1480/// is also 'int*'.
1481///
1482/// Non-canonical types are useful for emitting diagnostics, without losing
1483/// information about typedefs being used. Canonical types are useful for type
1484/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1485/// about whether something has a particular form (e.g. is a function type),
1486/// because they implicitly, recursively, strip all typedefs out of a type.
1487///
1488/// Types, once created, are immutable.
1489///
1490class alignas(8) Type : public ExtQualsTypeCommonBase {
1491public:
1492 enum TypeClass {
1493#define TYPE(Class, Base) Class,
1494#define LAST_TYPE(Class) TypeLast = Class
1495#define ABSTRACT_TYPE(Class, Base)
1496#include "clang/AST/TypeNodes.inc"
1497 };
1498
1499private:
1500 /// Bitfields required by the Type class.
1501 class TypeBitfields {
1502 friend class Type;
1503 template <class T> friend class TypePropertyCache;
1504
1505 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1506 unsigned TC : 8;
1507
1508 /// Store information on the type dependency.
1509 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1510
1511 /// True if the cache (i.e. the bitfields here starting with
1512 /// 'Cache') is valid.
1513 mutable unsigned CacheValid : 1;
1514
1515 /// Linkage of this type.
1516 mutable unsigned CachedLinkage : 3;
1517
1518 /// Whether this type involves and local or unnamed types.
1519 mutable unsigned CachedLocalOrUnnamed : 1;
1520
1521 /// Whether this type comes from an AST file.
1522 mutable unsigned FromAST : 1;
1523
1524 bool isCacheValid() const {
1525 return CacheValid;
1526 }
1527
1528 Linkage getLinkage() const {
1529 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast<void> (0));
1530 return static_cast<Linkage>(CachedLinkage);
1531 }
1532
1533 bool hasLocalOrUnnamedType() const {
1534 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast<void> (0));
1535 return CachedLocalOrUnnamed;
1536 }
1537 };
1538 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1539
1540protected:
1541 // These classes allow subclasses to somewhat cleanly pack bitfields
1542 // into Type.
1543
1544 class ArrayTypeBitfields {
1545 friend class ArrayType;
1546
1547 unsigned : NumTypeBits;
1548
1549 /// CVR qualifiers from declarations like
1550 /// 'int X[static restrict 4]'. For function parameters only.
1551 unsigned IndexTypeQuals : 3;
1552
1553 /// Storage class qualifiers from declarations like
1554 /// 'int X[static restrict 4]'. For function parameters only.
1555 /// Actually an ArrayType::ArraySizeModifier.
1556 unsigned SizeModifier : 3;
1557 };
1558
1559 class ConstantArrayTypeBitfields {
1560 friend class ConstantArrayType;
1561
1562 unsigned : NumTypeBits + 3 + 3;
1563
1564 /// Whether we have a stored size expression.
1565 unsigned HasStoredSizeExpr : 1;
1566 };
1567
1568 class BuiltinTypeBitfields {
1569 friend class BuiltinType;
1570
1571 unsigned : NumTypeBits;
1572
1573 /// The kind (BuiltinType::Kind) of builtin type this is.
1574 unsigned Kind : 8;
1575 };
1576
1577 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1578 /// Only common bits are stored here. Additional uncommon bits are stored
1579 /// in a trailing object after FunctionProtoType.
1580 class FunctionTypeBitfields {
1581 friend class FunctionProtoType;
1582 friend class FunctionType;
1583
1584 unsigned : NumTypeBits;
1585
1586 /// Extra information which affects how the function is called, like
1587 /// regparm and the calling convention.
1588 unsigned ExtInfo : 13;
1589
1590 /// The ref-qualifier associated with a \c FunctionProtoType.
1591 ///
1592 /// This is a value of type \c RefQualifierKind.
1593 unsigned RefQualifier : 2;
1594
1595 /// Used only by FunctionProtoType, put here to pack with the
1596 /// other bitfields.
1597 /// The qualifiers are part of FunctionProtoType because...
1598 ///
1599 /// C++ 8.3.5p4: The return type, the parameter type list and the
1600 /// cv-qualifier-seq, [...], are part of the function type.
1601 unsigned FastTypeQuals : Qualifiers::FastWidth;
1602 /// Whether this function has extended Qualifiers.
1603 unsigned HasExtQuals : 1;
1604
1605 /// The number of parameters this function has, not counting '...'.
1606 /// According to [implimits] 8 bits should be enough here but this is
1607 /// somewhat easy to exceed with metaprogramming and so we would like to
1608 /// keep NumParams as wide as reasonably possible.
1609 unsigned NumParams : 16;
1610
1611 /// The type of exception specification this function has.
1612 unsigned ExceptionSpecType : 4;
1613
1614 /// Whether this function has extended parameter information.
1615 unsigned HasExtParameterInfos : 1;
1616
1617 /// Whether the function is variadic.
1618 unsigned Variadic : 1;
1619
1620 /// Whether this function has a trailing return type.
1621 unsigned HasTrailingReturn : 1;
1622 };
1623
1624 class ObjCObjectTypeBitfields {
1625 friend class ObjCObjectType;
1626
1627 unsigned : NumTypeBits;
1628
1629 /// The number of type arguments stored directly on this object type.
1630 unsigned NumTypeArgs : 7;
1631
1632 /// The number of protocols stored directly on this object type.
1633 unsigned NumProtocols : 6;
1634
1635 /// Whether this is a "kindof" type.
1636 unsigned IsKindOf : 1;
1637 };
1638
1639 class ReferenceTypeBitfields {
1640 friend class ReferenceType;
1641
1642 unsigned : NumTypeBits;
1643
1644 /// True if the type was originally spelled with an lvalue sigil.
1645 /// This is never true of rvalue references but can also be false
1646 /// on lvalue references because of C++0x [dcl.typedef]p9,
1647 /// as follows:
1648 ///
1649 /// typedef int &ref; // lvalue, spelled lvalue
1650 /// typedef int &&rvref; // rvalue
1651 /// ref &a; // lvalue, inner ref, spelled lvalue
1652 /// ref &&a; // lvalue, inner ref
1653 /// rvref &a; // lvalue, inner ref, spelled lvalue
1654 /// rvref &&a; // rvalue, inner ref
1655 unsigned SpelledAsLValue : 1;
1656
1657 /// True if the inner type is a reference type. This only happens
1658 /// in non-canonical forms.
1659 unsigned InnerRef : 1;
1660 };
1661
1662 class TypeWithKeywordBitfields {
1663 friend class TypeWithKeyword;
1664
1665 unsigned : NumTypeBits;
1666
1667 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1668 unsigned Keyword : 8;
1669 };
1670
1671 enum { NumTypeWithKeywordBits = 8 };
1672
1673 class ElaboratedTypeBitfields {
1674 friend class ElaboratedType;
1675
1676 unsigned : NumTypeBits;
1677 unsigned : NumTypeWithKeywordBits;
1678
1679 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1680 unsigned HasOwnedTagDecl : 1;
1681 };
1682
1683 class VectorTypeBitfields {
1684 friend class VectorType;
1685 friend class DependentVectorType;
1686
1687 unsigned : NumTypeBits;
1688
1689 /// The kind of vector, either a generic vector type or some
1690 /// target-specific vector type such as for AltiVec or Neon.
1691 unsigned VecKind : 3;
1692 /// The number of elements in the vector.
1693 uint32_t NumElements;
1694 };
1695
1696 class AttributedTypeBitfields {
1697 friend class AttributedType;
1698
1699 unsigned : NumTypeBits;
1700
1701 /// An AttributedType::Kind
1702 unsigned AttrKind : 32 - NumTypeBits;
1703 };
1704
1705 class AutoTypeBitfields {
1706 friend class AutoType;
1707
1708 unsigned : NumTypeBits;
1709
1710 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1711 /// or '__auto_type'? AutoTypeKeyword value.
1712 unsigned Keyword : 2;
1713
1714 /// The number of template arguments in the type-constraints, which is
1715 /// expected to be able to hold at least 1024 according to [implimits].
1716 /// However as this limit is somewhat easy to hit with template
1717 /// metaprogramming we'd prefer to keep it as large as possible.
1718 /// At the moment it has been left as a non-bitfield since this type
1719 /// safely fits in 64 bits as an unsigned, so there is no reason to
1720 /// introduce the performance impact of a bitfield.
1721 unsigned NumArgs;
1722 };
1723
1724 class SubstTemplateTypeParmPackTypeBitfields {
1725 friend class SubstTemplateTypeParmPackType;
1726
1727 unsigned : NumTypeBits;
1728
1729 /// The number of template arguments in \c Arguments, which is
1730 /// expected to be able to hold at least 1024 according to [implimits].
1731 /// However as this limit is somewhat easy to hit with template
1732 /// metaprogramming we'd prefer to keep it as large as possible.
1733 /// At the moment it has been left as a non-bitfield since this type
1734 /// safely fits in 64 bits as an unsigned, so there is no reason to
1735 /// introduce the performance impact of a bitfield.
1736 unsigned NumArgs;
1737 };
1738
1739 class TemplateSpecializationTypeBitfields {
1740 friend class TemplateSpecializationType;
1741
1742 unsigned : NumTypeBits;
1743
1744 /// Whether this template specialization type is a substituted type alias.
1745 unsigned TypeAlias : 1;
1746
1747 /// The number of template arguments named in this class template
1748 /// specialization, which is expected to be able to hold at least 1024
1749 /// according to [implimits]. However, as this limit is somewhat easy to
1750 /// hit with template metaprogramming we'd prefer to keep it as large
1751 /// as possible. At the moment it has been left as a non-bitfield since
1752 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1753 /// to introduce the performance impact of a bitfield.
1754 unsigned NumArgs;
1755 };
1756
1757 class DependentTemplateSpecializationTypeBitfields {
1758 friend class DependentTemplateSpecializationType;
1759
1760 unsigned : NumTypeBits;
1761 unsigned : NumTypeWithKeywordBits;
1762
1763 /// The number of template arguments named in this class template
1764 /// specialization, which is expected to be able to hold at least 1024
1765 /// according to [implimits]. However, as this limit is somewhat easy to
1766 /// hit with template metaprogramming we'd prefer to keep it as large
1767 /// as possible. At the moment it has been left as a non-bitfield since
1768 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1769 /// to introduce the performance impact of a bitfield.
1770 unsigned NumArgs;
1771 };
1772
1773 class PackExpansionTypeBitfields {
1774 friend class PackExpansionType;
1775
1776 unsigned : NumTypeBits;
1777
1778 /// The number of expansions that this pack expansion will
1779 /// generate when substituted (+1), which is expected to be able to
1780 /// hold at least 1024 according to [implimits]. However, as this limit
1781 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1782 /// keep it as large as possible. At the moment it has been left as a
1783 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1784 /// there is no reason to introduce the performance impact of a bitfield.
1785 ///
1786 /// This field will only have a non-zero value when some of the parameter
1787 /// packs that occur within the pattern have been substituted but others
1788 /// have not.
1789 unsigned NumExpansions;
1790 };
1791
1792 union {
1793 TypeBitfields TypeBits;
1794 ArrayTypeBitfields ArrayTypeBits;
1795 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1796 AttributedTypeBitfields AttributedTypeBits;
1797 AutoTypeBitfields AutoTypeBits;
1798 BuiltinTypeBitfields BuiltinTypeBits;
1799 FunctionTypeBitfields FunctionTypeBits;
1800 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1801 ReferenceTypeBitfields ReferenceTypeBits;
1802 TypeWithKeywordBitfields TypeWithKeywordBits;
1803 ElaboratedTypeBitfields ElaboratedTypeBits;
1804 VectorTypeBitfields VectorTypeBits;
1805 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1806 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1807 DependentTemplateSpecializationTypeBitfields
1808 DependentTemplateSpecializationTypeBits;
1809 PackExpansionTypeBitfields PackExpansionTypeBits;
1810 };
1811
1812private:
1813 template <class T> friend class TypePropertyCache;
1814
1815 /// Set whether this type comes from an AST file.
1816 void setFromAST(bool V = true) const {
1817 TypeBits.FromAST = V;
1818 }
1819
1820protected:
1821 friend class ASTContext;
1822
1823 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1824 : ExtQualsTypeCommonBase(this,
1825 canon.isNull() ? QualType(this_(), 0) : canon) {
1826 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1827 "changing bitfields changed sizeof(Type)!");
1828 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1829 "Insufficient alignment!");
1830 TypeBits.TC = tc;
1831 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1832 TypeBits.CacheValid = false;
1833 TypeBits.CachedLocalOrUnnamed = false;
1834 TypeBits.CachedLinkage = NoLinkage;
1835 TypeBits.FromAST = false;
1836 }
1837
1838 // silence VC++ warning C4355: 'this' : used in base member initializer list
1839 Type *this_() { return this; }
1840
1841 void setDependence(TypeDependence D) {
1842 TypeBits.Dependence = static_cast<unsigned>(D);
1843 }
1844
1845 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1846
1847public:
1848 friend class ASTReader;
1849 friend class ASTWriter;
1850 template <class T> friend class serialization::AbstractTypeReader;
1851 template <class T> friend class serialization::AbstractTypeWriter;
1852
1853 Type(const Type &) = delete;
1854 Type(Type &&) = delete;
1855 Type &operator=(const Type &) = delete;
1856 Type &operator=(Type &&) = delete;
1857
1858 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1859
1860 /// Whether this type comes from an AST file.
1861 bool isFromAST() const { return TypeBits.FromAST; }
1862
1863 /// Whether this type is or contains an unexpanded parameter
1864 /// pack, used to support C++0x variadic templates.
1865 ///
1866 /// A type that contains a parameter pack shall be expanded by the
1867 /// ellipsis operator at some point. For example, the typedef in the
1868 /// following example contains an unexpanded parameter pack 'T':
1869 ///
1870 /// \code
1871 /// template<typename ...T>
1872 /// struct X {
1873 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1874 /// };
1875 /// \endcode
1876 ///
1877 /// Note that this routine does not specify which
1878 bool containsUnexpandedParameterPack() const {
1879 return getDependence() & TypeDependence::UnexpandedPack;
1880 }
1881
1882 /// Determines if this type would be canonical if it had no further
1883 /// qualification.
1884 bool isCanonicalUnqualified() const {
1885 return CanonicalType == QualType(this, 0);
1886 }
1887
1888 /// Pull a single level of sugar off of this locally-unqualified type.
1889 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1890 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1891 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1892
1893 /// As an extension, we classify types as one of "sized" or "sizeless";
1894 /// every type is one or the other. Standard types are all sized;
1895 /// sizeless types are purely an extension.
1896 ///
1897 /// Sizeless types contain data with no specified size, alignment,
1898 /// or layout.
1899 bool isSizelessType() const;
1900 bool isSizelessBuiltinType() const;
1901
1902 /// Determines if this is a sizeless type supported by the
1903 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1904 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1905 bool isVLSTBuiltinType() const;
1906
1907 /// Returns the representative type for the element of an SVE builtin type.
1908 /// This is used to represent fixed-length SVE vectors created with the
1909 /// 'arm_sve_vector_bits' type attribute as VectorType.
1910 QualType getSveEltType(const ASTContext &Ctx) const;
1911
1912 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1913 /// object types, function types, and incomplete types.
1914
1915 /// Return true if this is an incomplete type.
1916 /// A type that can describe objects, but which lacks information needed to
1917 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1918 /// routine will need to determine if the size is actually required.
1919 ///
1920 /// Def If non-null, and the type refers to some kind of declaration
1921 /// that can be completed (such as a C struct, C++ class, or Objective-C
1922 /// class), will be set to the declaration.
1923 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1924
1925 /// Return true if this is an incomplete or object
1926 /// type, in other words, not a function type.
1927 bool isIncompleteOrObjectType() const {
1928 return !isFunctionType();
1929 }
1930
1931 /// Determine whether this type is an object type.
1932 bool isObjectType() const {
1933 // C++ [basic.types]p8:
1934 // An object type is a (possibly cv-qualified) type that is not a
1935 // function type, not a reference type, and not a void type.
1936 return !isReferenceType() && !isFunctionType() && !isVoidType();
1937 }
1938
1939 /// Return true if this is a literal type
1940 /// (C++11 [basic.types]p10)
1941 bool isLiteralType(const ASTContext &Ctx) const;
1942
1943 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1944 bool isStructuralType() const;
1945
1946 /// Test if this type is a standard-layout type.
1947 /// (C++0x [basic.type]p9)
1948 bool isStandardLayoutType() const;
1949
1950 /// Helper methods to distinguish type categories. All type predicates
1951 /// operate on the canonical type, ignoring typedefs and qualifiers.
1952
1953 /// Returns true if the type is a builtin type.
1954 bool isBuiltinType() const;
1955
1956 /// Test for a particular builtin type.
1957 bool isSpecificBuiltinType(unsigned K) const;
1958
1959 /// Test for a type which does not represent an actual type-system type but
1960 /// is instead used as a placeholder for various convenient purposes within
1961 /// Clang. All such types are BuiltinTypes.
1962 bool isPlaceholderType() const;
1963 const BuiltinType *getAsPlaceholderType() const;
1964
1965 /// Test for a specific placeholder type.
1966 bool isSpecificPlaceholderType(unsigned K) const;
1967
1968 /// Test for a placeholder type other than Overload; see
1969 /// BuiltinType::isNonOverloadPlaceholderType.
1970 bool isNonOverloadPlaceholderType() const;
1971
1972 /// isIntegerType() does *not* include complex integers (a GCC extension).
1973 /// isComplexIntegerType() can be used to test for complex integers.
1974 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1975 bool isEnumeralType() const;
1976
1977 /// Determine whether this type is a scoped enumeration type.
1978 bool isScopedEnumeralType() const;
1979 bool isBooleanType() const;
1980 bool isCharType() const;
1981 bool isWideCharType() const;
1982 bool isChar8Type() const;
1983 bool isChar16Type() const;
1984 bool isChar32Type() const;
1985 bool isAnyCharacterType() const;
1986 bool isIntegralType(const ASTContext &Ctx) const;
1987
1988 /// Determine whether this type is an integral or enumeration type.
1989 bool isIntegralOrEnumerationType() const;
1990
1991 /// Determine whether this type is an integral or unscoped enumeration type.
1992 bool isIntegralOrUnscopedEnumerationType() const;
1993 bool isUnscopedEnumerationType() const;
1994
1995 /// Floating point categories.
1996 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1997 /// isComplexType() does *not* include complex integers (a GCC extension).
1998 /// isComplexIntegerType() can be used to test for complex integers.
1999 bool isComplexType() const; // C99 6.2.5p11 (complex)
2000 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2001 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2002 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2003 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2004 bool isBFloat16Type() const;
2005 bool isFloat128Type() const;
2006 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2007 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2008 bool isVoidType() const; // C99 6.2.5p19
2009 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2010 bool isAggregateType() const;
2011 bool isFundamentalType() const;
2012 bool isCompoundType() const;
2013
2014 // Type Predicates: Check to see if this type is structurally the specified
2015 // type, ignoring typedefs and qualifiers.
2016 bool isFunctionType() const;
2017 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2018 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2019 bool isPointerType() const;
2020 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2021 bool isBlockPointerType() const;
2022 bool isVoidPointerType() const;
2023 bool isReferenceType() const;
2024 bool isLValueReferenceType() const;
2025 bool isRValueReferenceType() const;
2026 bool isObjectPointerType() const;
2027 bool isFunctionPointerType() const;
2028 bool isFunctionReferenceType() const;
2029 bool isMemberPointerType() const;
2030 bool isMemberFunctionPointerType() const;
2031 bool isMemberDataPointerType() const;
2032 bool isArrayType() const;
2033 bool isConstantArrayType() const;
2034 bool isIncompleteArrayType() const;
2035 bool isVariableArrayType() const;
2036 bool isDependentSizedArrayType() const;
2037 bool isRecordType() const;
2038 bool isClassType() const;
2039 bool isStructureType() const;
2040 bool isObjCBoxableRecordType() const;
2041 bool isInterfaceType() const;
2042 bool isStructureOrClassType() const;
2043 bool isUnionType() const;
2044 bool isComplexIntegerType() const; // GCC _Complex integer type.
2045 bool isVectorType() const; // GCC vector type.
2046 bool isExtVectorType() const; // Extended vector type.
2047 bool isMatrixType() const; // Matrix type.
2048 bool isConstantMatrixType() const; // Constant matrix type.
2049 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2050 bool isObjCObjectPointerType() const; // pointer to ObjC object
2051 bool isObjCRetainableType() const; // ObjC object or block pointer
2052 bool isObjCLifetimeType() const; // (array of)* retainable type
2053 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2054 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2055 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2056 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2057 // for the common case.
2058 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2059 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2060 bool isObjCQualifiedIdType() const; // id<foo>
2061 bool isObjCQualifiedClassType() const; // Class<foo>
2062 bool isObjCObjectOrInterfaceType() const;
2063 bool isObjCIdType() const; // id
2064 bool isDecltypeType() const;
2065 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2066 /// qualifier?
2067 ///
2068 /// This approximates the answer to the following question: if this
2069 /// translation unit were compiled in ARC, would this type be qualified
2070 /// with __unsafe_unretained?
2071 bool isObjCInertUnsafeUnretainedType() const {
2072 return hasAttr(attr::ObjCInertUnsafeUnretained);
2073 }
2074
2075 /// Whether the type is Objective-C 'id' or a __kindof type of an
2076 /// object type, e.g., __kindof NSView * or __kindof id
2077 /// <NSCopying>.
2078 ///
2079 /// \param bound Will be set to the bound on non-id subtype types,
2080 /// which will be (possibly specialized) Objective-C class type, or
2081 /// null for 'id.
2082 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2083 const ObjCObjectType *&bound) const;
2084
2085 bool isObjCClassType() const; // Class
2086
2087 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2088 /// Class type, e.g., __kindof Class <NSCopying>.
2089 ///
2090 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2091 /// here because Objective-C's type system cannot express "a class
2092 /// object for a subclass of NSFoo".
2093 bool isObjCClassOrClassKindOfType() const;
2094
2095 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2096 bool isObjCSelType() const; // Class
2097 bool isObjCBuiltinType() const; // 'id' or 'Class'
2098 bool isObjCARCBridgableType() const;
2099 bool isCARCBridgableType() const;
2100 bool isTemplateTypeParmType() const; // C++ template type parameter
2101 bool isNullPtrType() const; // C++11 std::nullptr_t
2102 bool isNothrowT() const; // C++ std::nothrow_t
2103 bool isAlignValT() const; // C++17 std::align_val_t
2104 bool isStdByteType() const; // C++17 std::byte
2105 bool isAtomicType() const; // C11 _Atomic()
2106 bool isUndeducedAutoType() const; // C++11 auto or
2107 // C++14 decltype(auto)
2108 bool isTypedefNameType() const; // typedef or alias template
2109
2110#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2111 bool is##Id##Type() const;
2112#include "clang/Basic/OpenCLImageTypes.def"
2113
2114 bool isImageType() const; // Any OpenCL image type
2115
2116 bool isSamplerT() const; // OpenCL sampler_t
2117 bool isEventT() const; // OpenCL event_t
2118 bool isClkEventT() const; // OpenCL clk_event_t
2119 bool isQueueT() const; // OpenCL queue_t
2120 bool isReserveIDT() const; // OpenCL reserve_id_t
2121
2122#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2123 bool is##Id##Type() const;
2124#include "clang/Basic/OpenCLExtensionTypes.def"
2125 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2126 bool isOCLIntelSubgroupAVCType() const;
2127 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2128
2129 bool isPipeType() const; // OpenCL pipe type
2130 bool isExtIntType() const; // Extended Int Type
2131 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2132
2133 /// Determines if this type, which must satisfy
2134 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2135 /// than implicitly __strong.
2136 bool isObjCARCImplicitlyUnretainedType() const;
2137
2138 /// Check if the type is the CUDA device builtin surface type.
2139 bool isCUDADeviceBuiltinSurfaceType() const;
2140 /// Check if the type is the CUDA device builtin texture type.
2141 bool isCUDADeviceBuiltinTextureType() const;
2142
2143 /// Return the implicit lifetime for this type, which must not be dependent.
2144 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2145
2146 enum ScalarTypeKind {
2147 STK_CPointer,
2148 STK_BlockPointer,
2149 STK_ObjCObjectPointer,
2150 STK_MemberPointer,
2151 STK_Bool,
2152 STK_Integral,
2153 STK_Floating,
2154 STK_IntegralComplex,
2155 STK_FloatingComplex,
2156 STK_FixedPoint
2157 };
2158
2159 /// Given that this is a scalar type, classify it.
2160 ScalarTypeKind getScalarTypeKind() const;
2161
2162 TypeDependence getDependence() const {
2163 return static_cast<TypeDependence>(TypeBits.Dependence);
2164 }
2165
2166 /// Whether this type is an error type.
2167 bool containsErrors() const {
2168 return getDependence() & TypeDependence::Error;
2169 }
2170
2171 /// Whether this type is a dependent type, meaning that its definition
2172 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2173 bool isDependentType() const {
2174 return getDependence() & TypeDependence::Dependent;
2175 }
2176
2177 /// Determine whether this type is an instantiation-dependent type,
2178 /// meaning that the type involves a template parameter (even if the
2179 /// definition does not actually depend on the type substituted for that
2180 /// template parameter).
2181 bool isInstantiationDependentType() const {
2182 return getDependence() & TypeDependence::Instantiation;
2183 }
2184
2185 /// Determine whether this type is an undeduced type, meaning that
2186 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2187 /// deduced.
2188 bool isUndeducedType() const;
2189
2190 /// Whether this type is a variably-modified type (C99 6.7.5).
2191 bool isVariablyModifiedType() const {
2192 return getDependence() & TypeDependence::VariablyModified;
2193 }
2194
2195 /// Whether this type involves a variable-length array type
2196 /// with a definite size.
2197 bool hasSizedVLAType() const;
2198
2199 /// Whether this type is or contains a local or unnamed type.
2200 bool hasUnnamedOrLocalType() const;
2201
2202 bool isOverloadableType() const;
2203
2204 /// Determine wither this type is a C++ elaborated-type-specifier.
2205 bool isElaboratedTypeSpecifier() const;
2206
2207 bool canDecayToPointerType() const;
2208
2209 /// Whether this type is represented natively as a pointer. This includes
2210 /// pointers, references, block pointers, and Objective-C interface,
2211 /// qualified id, and qualified interface types, as well as nullptr_t.
2212 bool hasPointerRepresentation() const;
2213
2214 /// Whether this type can represent an objective pointer type for the
2215 /// purpose of GC'ability
2216 bool hasObjCPointerRepresentation() const;
2217
2218 /// Determine whether this type has an integer representation
2219 /// of some sort, e.g., it is an integer type or a vector.
2220 bool hasIntegerRepresentation() const;
2221
2222 /// Determine whether this type has an signed integer representation
2223 /// of some sort, e.g., it is an signed integer type or a vector.
2224 bool hasSignedIntegerRepresentation() const;
2225
2226 /// Determine whether this type has an unsigned integer representation
2227 /// of some sort, e.g., it is an unsigned integer type or a vector.
2228 bool hasUnsignedIntegerRepresentation() const;
2229
2230 /// Determine whether this type has a floating-point representation
2231 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2232 bool hasFloatingRepresentation() const;
2233
2234 // Type Checking Functions: Check to see if this type is structurally the
2235 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2236 // the best type we can.
2237 const RecordType *getAsStructureType() const;
2238 /// NOTE: getAs*ArrayType are methods on ASTContext.
2239 const RecordType *getAsUnionType() const;
2240 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2241 const ObjCObjectType *getAsObjCInterfaceType() const;
2242
2243 // The following is a convenience method that returns an ObjCObjectPointerType
2244 // for object declared using an interface.
2245 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2246 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2247 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2248 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2249
2250 /// Retrieves the CXXRecordDecl that this type refers to, either
2251 /// because the type is a RecordType or because it is the injected-class-name
2252 /// type of a class template or class template partial specialization.
2253 CXXRecordDecl *getAsCXXRecordDecl() const;
2254
2255 /// Retrieves the RecordDecl this type refers to.
2256 RecordDecl *getAsRecordDecl() const;
2257
2258 /// Retrieves the TagDecl that this type refers to, either
2259 /// because the type is a TagType or because it is the injected-class-name
2260 /// type of a class template or class template partial specialization.
2261 TagDecl *getAsTagDecl() const;
2262
2263 /// If this is a pointer or reference to a RecordType, return the
2264 /// CXXRecordDecl that the type refers to.
2265 ///
2266 /// If this is not a pointer or reference, or the type being pointed to does
2267 /// not refer to a CXXRecordDecl, returns NULL.
2268 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2269
2270 /// Get the DeducedType whose type will be deduced for a variable with
2271 /// an initializer of this type. This looks through declarators like pointer
2272 /// types, but not through decltype or typedefs.
2273 DeducedType *getContainedDeducedType() const;
2274
2275 /// Get the AutoType whose type will be deduced for a variable with
2276 /// an initializer of this type. This looks through declarators like pointer
2277 /// types, but not through decltype or typedefs.
2278 AutoType *getContainedAutoType() const {
2279 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2280 }
2281
2282 /// Determine whether this type was written with a leading 'auto'
2283 /// corresponding to a trailing return type (possibly for a nested
2284 /// function type within a pointer to function type or similar).
2285 bool hasAutoForTrailingReturnType() const;
2286
2287 /// Member-template getAs<specific type>'. Look through sugar for
2288 /// an instance of \<specific type>. This scheme will eventually
2289 /// replace the specific getAsXXXX methods above.
2290 ///
2291 /// There are some specializations of this member template listed
2292 /// immediately following this class.
2293 template <typename T> const T *getAs() const;
2294
2295 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2296 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2297 /// This is used when you need to walk over sugar nodes that represent some
2298 /// kind of type adjustment from a type that was written as a \<specific type>
2299 /// to another type that is still canonically a \<specific type>.
2300 template <typename T> const T *getAsAdjusted() const;
2301
2302 /// A variant of getAs<> for array types which silently discards
2303 /// qualifiers from the outermost type.
2304 const ArrayType *getAsArrayTypeUnsafe() const;
2305
2306 /// Member-template castAs<specific type>. Look through sugar for
2307 /// the underlying instance of \<specific type>.
2308 ///
2309 /// This method has the same relationship to getAs<T> as cast<T> has
2310 /// to dyn_cast<T>; which is to say, the underlying type *must*
2311 /// have the intended type, and this method will never return null.
2312 template <typename T> const T *castAs() const;
2313
2314 /// A variant of castAs<> for array type which silently discards
2315 /// qualifiers from the outermost type.
2316 const ArrayType *castAsArrayTypeUnsafe() const;
2317
2318 /// Determine whether this type had the specified attribute applied to it
2319 /// (looking through top-level type sugar).
2320 bool hasAttr(attr::Kind AK) const;
2321
2322 /// Get the base element type of this type, potentially discarding type
2323 /// qualifiers. This should never be used when type qualifiers
2324 /// are meaningful.
2325 const Type *getBaseElementTypeUnsafe() const;
2326
2327 /// If this is an array type, return the element type of the array,
2328 /// potentially with type qualifiers missing.
2329 /// This should never be used when type qualifiers are meaningful.
2330 const Type *getArrayElementTypeNoTypeQual() const;
2331
2332 /// If this is a pointer type, return the pointee type.
2333 /// If this is an array type, return the array element type.
2334 /// This should never be used when type qualifiers are meaningful.
2335 const Type *getPointeeOrArrayElementType() const;
2336
2337 /// If this is a pointer, ObjC object pointer, or block
2338 /// pointer, this returns the respective pointee.
2339 QualType getPointeeType() const;
2340
2341 /// Return the specified type with any "sugar" removed from the type,
2342 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2343 const Type *getUnqualifiedDesugaredType() const;
2344
2345 /// More type predicates useful for type checking/promotion
2346 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2347
2348 /// Return true if this is an integer type that is
2349 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2350 /// or an enum decl which has a signed representation.
2351 bool isSignedIntegerType() const;
2352
2353 /// Return true if this is an integer type that is
2354 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2355 /// or an enum decl which has an unsigned representation.
2356 bool isUnsignedIntegerType() const;
2357
2358 /// Determines whether this is an integer type that is signed or an
2359 /// enumeration types whose underlying type is a signed integer type.
2360 bool isSignedIntegerOrEnumerationType() const;
2361
2362 /// Determines whether this is an integer type that is unsigned or an
2363 /// enumeration types whose underlying type is a unsigned integer type.
2364 bool isUnsignedIntegerOrEnumerationType() const;
2365
2366 /// Return true if this is a fixed point type according to
2367 /// ISO/IEC JTC1 SC22 WG14 N1169.
2368 bool isFixedPointType() const;
2369
2370 /// Return true if this is a fixed point or integer type.
2371 bool isFixedPointOrIntegerType() const;
2372
2373 /// Return true if this is a saturated fixed point type according to
2374 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2375 bool isSaturatedFixedPointType() const;
2376
2377 /// Return true if this is a saturated fixed point type according to
2378 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2379 bool isUnsaturatedFixedPointType() const;
2380
2381 /// Return true if this is a fixed point type that is signed according
2382 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2383 bool isSignedFixedPointType() const;
2384
2385 /// Return true if this is a fixed point type that is unsigned according
2386 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2387 bool isUnsignedFixedPointType() const;
2388
2389 /// Return true if this is not a variable sized type,
2390 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2391 /// incomplete types.
2392 bool isConstantSizeType() const;
2393
2394 /// Returns true if this type can be represented by some
2395 /// set of type specifiers.
2396 bool isSpecifierType() const;
2397
2398 /// Determine the linkage of this type.
2399 Linkage getLinkage() const;
2400
2401 /// Determine the visibility of this type.
2402 Visibility getVisibility() const {
2403 return getLinkageAndVisibility().getVisibility();
2404 }
2405
2406 /// Return true if the visibility was explicitly set is the code.
2407 bool isVisibilityExplicit() const {
2408 return getLinkageAndVisibility().isVisibilityExplicit();
2409 }
2410
2411 /// Determine the linkage and visibility of this type.
2412 LinkageInfo getLinkageAndVisibility() const;
2413
2414 /// True if the computed linkage is valid. Used for consistency
2415 /// checking. Should always return true.
2416 bool isLinkageValid() const;
2417
2418 /// Determine the nullability of the given type.
2419 ///
2420 /// Note that nullability is only captured as sugar within the type
2421 /// system, not as part of the canonical type, so nullability will
2422 /// be lost by canonicalization and desugaring.
2423 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2424
2425 /// Determine whether the given type can have a nullability
2426 /// specifier applied to it, i.e., if it is any kind of pointer type.
2427 ///
2428 /// \param ResultIfUnknown The value to return if we don't yet know whether
2429 /// this type can have nullability because it is dependent.
2430 bool canHaveNullability(bool ResultIfUnknown = true) const;
2431
2432 /// Retrieve the set of substitutions required when accessing a member
2433 /// of the Objective-C receiver type that is declared in the given context.
2434 ///
2435 /// \c *this is the type of the object we're operating on, e.g., the
2436 /// receiver for a message send or the base of a property access, and is
2437 /// expected to be of some object or object pointer type.
2438 ///
2439 /// \param dc The declaration context for which we are building up a
2440 /// substitution mapping, which should be an Objective-C class, extension,
2441 /// category, or method within.
2442 ///
2443 /// \returns an array of type arguments that can be substituted for
2444 /// the type parameters of the given declaration context in any type described
2445 /// within that context, or an empty optional to indicate that no
2446 /// substitution is required.
2447 Optional<ArrayRef<QualType>>
2448 getObjCSubstitutions(const DeclContext *dc) const;
2449
2450 /// Determines if this is an ObjC interface type that may accept type
2451 /// parameters.
2452 bool acceptsObjCTypeParams() const;
2453
2454 const char *getTypeClassName() const;
2455
2456 QualType getCanonicalTypeInternal() const {
2457 return CanonicalType;
2458 }
2459
2460 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2461 void dump() const;
2462 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2463};
2464
2465/// This will check for a TypedefType by removing any existing sugar
2466/// until it reaches a TypedefType or a non-sugared type.
2467template <> const TypedefType *Type::getAs() const;
2468
2469/// This will check for a TemplateSpecializationType by removing any
2470/// existing sugar until it reaches a TemplateSpecializationType or a
2471/// non-sugared type.
2472template <> const TemplateSpecializationType *Type::getAs() const;
2473
2474/// This will check for an AttributedType by removing any existing sugar
2475/// until it reaches an AttributedType or a non-sugared type.
2476template <> const AttributedType *Type::getAs() const;
2477
2478// We can do canonical leaf types faster, because we don't have to
2479// worry about preserving child type decoration.
2480#define TYPE(Class, Base)
2481#define LEAF_TYPE(Class) \
2482template <> inline const Class##Type *Type::getAs() const { \
2483 return dyn_cast<Class##Type>(CanonicalType); \
2484} \
2485template <> inline const Class##Type *Type::castAs() const { \
2486 return cast<Class##Type>(CanonicalType); \
2487}
2488#include "clang/AST/TypeNodes.inc"
2489
2490/// This class is used for builtin types like 'int'. Builtin
2491/// types are always canonical and have a literal name field.
2492class BuiltinType : public Type {
2493public:
2494 enum Kind {
2495// OpenCL image types
2496#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2497#include "clang/Basic/OpenCLImageTypes.def"
2498// OpenCL extension types
2499#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2500#include "clang/Basic/OpenCLExtensionTypes.def"
2501// SVE Types
2502#define SVE_TYPE(Name, Id, SingletonId) Id,
2503#include "clang/Basic/AArch64SVEACLETypes.def"
2504// PPC MMA Types
2505#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2506#include "clang/Basic/PPCTypes.def"
2507// RVV Types
2508#define RVV_TYPE(Name, Id, SingletonId) Id,
2509#include "clang/Basic/RISCVVTypes.def"
2510// All other builtin types
2511#define BUILTIN_TYPE(Id, SingletonId) Id,
2512#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2513#include "clang/AST/BuiltinTypes.def"
2514 };
2515
2516private:
2517 friend class ASTContext; // ASTContext creates these.
2518
2519 BuiltinType(Kind K)
2520 : Type(Builtin, QualType(),
2521 K == Dependent ? TypeDependence::DependentInstantiation
2522 : TypeDependence::None) {
2523 BuiltinTypeBits.Kind = K;
2524 }
2525
2526public:
2527 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2528 StringRef getName(const PrintingPolicy &Policy) const;
2529
2530 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2531 // The StringRef is null-terminated.
2532 StringRef str = getName(Policy);
2533 assert(!str.empty() && str.data()[str.size()] == '\0')(static_cast<void> (0));
2534 return str.data();
2535 }
2536
2537 bool isSugared() const { return false; }
2538 QualType desugar() const { return QualType(this, 0); }
2539
2540 bool isInteger() const {
2541 return getKind() >= Bool && getKind() <= Int128;
2542 }
2543
2544 bool isSignedInteger() const {
2545 return getKind() >= Char_S && getKind() <= Int128;
2546 }
2547
2548 bool isUnsignedInteger() const {
2549 return getKind() >= Bool && getKind() <= UInt128;
2550 }
2551
2552 bool isFloatingPoint() const {
2553 return getKind() >= Half && getKind() <= Float128;
2554 }
2555
2556 /// Determines whether the given kind corresponds to a placeholder type.
2557 static bool isPlaceholderTypeKind(Kind K) {
2558 return K >= Overload;
2559 }
2560
2561 /// Determines whether this type is a placeholder type, i.e. a type
2562 /// which cannot appear in arbitrary positions in a fully-formed
2563 /// expression.
2564 bool isPlaceholderType() const {
2565 return isPlaceholderTypeKind(getKind());
2566 }
2567
2568 /// Determines whether this type is a placeholder type other than
2569 /// Overload. Most placeholder types require only syntactic
2570 /// information about their context in order to be resolved (e.g.
2571 /// whether it is a call expression), which means they can (and
2572 /// should) be resolved in an earlier "phase" of analysis.
2573 /// Overload expressions sometimes pick up further information
2574 /// from their context, like whether the context expects a
2575 /// specific function-pointer type, and so frequently need
2576 /// special treatment.
2577 bool isNonOverloadPlaceholderType() const {
2578 return getKind() > Overload;
2579 }
2580
2581 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2582};
2583
2584/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2585/// types (_Complex float etc) as well as the GCC integer complex extensions.
2586class ComplexType : public Type, public llvm::FoldingSetNode {
2587 friend class ASTContext; // ASTContext creates these.
2588
2589 QualType ElementType;
2590
2591 ComplexType(QualType Element, QualType CanonicalPtr)
2592 : Type(Complex, CanonicalPtr, Element->getDependence()),
2593 ElementType(Element) {}
2594
2595public:
2596 QualType getElementType() const { return ElementType; }
2597
2598 bool isSugared() const { return false; }
2599 QualType desugar() const { return QualType(this, 0); }
2600
2601 void Profile(llvm::FoldingSetNodeID &ID) {
2602 Profile(ID, getElementType());
2603 }
2604
2605 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2606 ID.AddPointer(Element.getAsOpaquePtr());
2607 }
2608
2609 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2610};
2611
2612/// Sugar for parentheses used when specifying types.
2613class ParenType : public Type, public llvm::FoldingSetNode {
2614 friend class ASTContext; // ASTContext creates these.
2615
2616 QualType Inner;
2617
2618 ParenType(QualType InnerType, QualType CanonType)
2619 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2620
2621public:
2622 QualType getInnerType() const { return Inner; }
2623
2624 bool isSugared() const { return true; }
2625 QualType desugar() const { return getInnerType(); }
2626
2627 void Profile(llvm::FoldingSetNodeID &ID) {
2628 Profile(ID, getInnerType());
2629 }
2630
2631 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2632 Inner.Profile(ID);
2633 }
2634
2635 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2636};
2637
2638/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2639class PointerType : public Type, public llvm::FoldingSetNode {
2640 friend class ASTContext; // ASTContext creates these.
2641
2642 QualType PointeeType;
2643
2644 PointerType(QualType Pointee, QualType CanonicalPtr)
2645 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2646 PointeeType(Pointee) {}
2647
2648public:
2649 QualType getPointeeType() const { return PointeeType; }
2650
2651 bool isSugared() const { return false; }
2652 QualType desugar() const { return QualType(this, 0); }
2653
2654 void Profile(llvm::FoldingSetNodeID &ID) {
2655 Profile(ID, getPointeeType());
2656 }
2657
2658 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2659 ID.AddPointer(Pointee.getAsOpaquePtr());
2660 }
2661
2662 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2663};
2664
2665/// Represents a type which was implicitly adjusted by the semantic
2666/// engine for arbitrary reasons. For example, array and function types can
2667/// decay, and function types can have their calling conventions adjusted.
2668class AdjustedType : public Type, public llvm::FoldingSetNode {
2669 QualType OriginalTy;
2670 QualType AdjustedTy;
2671
2672protected:
2673 friend class ASTContext; // ASTContext creates these.
2674
2675 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2676 QualType CanonicalPtr)
2677 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2678 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2679
2680public:
2681 QualType getOriginalType() const { return OriginalTy; }
2682 QualType getAdjustedType() const { return AdjustedTy; }
2683
2684 bool isSugared() const { return true; }
2685 QualType desugar() const { return AdjustedTy; }
2686
2687 void Profile(llvm::FoldingSetNodeID &ID) {
2688 Profile(ID, OriginalTy, AdjustedTy);
2689 }
2690
2691 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2692 ID.AddPointer(Orig.getAsOpaquePtr());
2693 ID.AddPointer(New.getAsOpaquePtr());
2694 }
2695
2696 static bool classof(const Type *T) {
2697 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2698 }
2699};
2700
2701/// Represents a pointer type decayed from an array or function type.
2702class DecayedType : public AdjustedType {
2703 friend class ASTContext; // ASTContext creates these.
2704
2705 inline
2706 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2707
2708public:
2709 QualType getDecayedType() const { return getAdjustedType(); }
2710
2711 inline QualType getPointeeType() const;
2712
2713 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2714};
2715
2716/// Pointer to a block type.
2717/// This type is to represent types syntactically represented as
2718/// "void (^)(int)", etc. Pointee is required to always be a function type.
2719class BlockPointerType : public Type, public llvm::FoldingSetNode {
2720 friend class ASTContext; // ASTContext creates these.
2721
2722 // Block is some kind of pointer type
2723 QualType PointeeType;
2724
2725 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2726 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2727 PointeeType(Pointee) {}
2728
2729public:
2730 // Get the pointee type. Pointee is required to always be a function type.
2731 QualType getPointeeType() const { return PointeeType; }
2732
2733 bool isSugared() const { return false; }
2734 QualType desugar() const { return QualType(this, 0); }
2735
2736 void Profile(llvm::FoldingSetNodeID &ID) {
2737 Profile(ID, getPointeeType());
2738 }
2739
2740 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2741 ID.AddPointer(Pointee.getAsOpaquePtr());
2742 }
2743
2744 static bool classof(const Type *T) {
2745 return T->getTypeClass() == BlockPointer;
2746 }
2747};
2748
2749/// Base for LValueReferenceType and RValueReferenceType
2750class ReferenceType : public Type, public llvm::FoldingSetNode {
2751 QualType PointeeType;
2752
2753protected:
2754 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2755 bool SpelledAsLValue)
2756 : Type(tc, CanonicalRef, Referencee->getDependence()),
2757 PointeeType(Referencee) {
2758 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2759 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2760 }
2761
2762public:
2763 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2764 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2765
2766 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2767
2768 QualType getPointeeType() const {
2769 // FIXME: this might strip inner qualifiers; okay?
2770 const ReferenceType *T = this;
2771 while (T->isInnerRef())
2772 T = T->PointeeType->castAs<ReferenceType>();
2773 return T->PointeeType;
2774 }
2775
2776 void Profile(llvm::FoldingSetNodeID &ID) {
2777 Profile(ID, PointeeType, isSpelledAsLValue());
2778 }
2779
2780 static void Profile(llvm::FoldingSetNodeID &ID,
2781 QualType Referencee,
2782 bool SpelledAsLValue) {
2783 ID.AddPointer(Referencee.getAsOpaquePtr());
2784 ID.AddBoolean(SpelledAsLValue);
2785 }
2786
2787 static bool classof(const Type *T) {
2788 return T->getTypeClass() == LValueReference ||
2789 T->getTypeClass() == RValueReference;
2790 }
2791};
2792
2793/// An lvalue reference type, per C++11 [dcl.ref].
2794class LValueReferenceType : public ReferenceType {
2795 friend class ASTContext; // ASTContext creates these
2796
2797 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2798 bool SpelledAsLValue)
2799 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2800 SpelledAsLValue) {}
2801
2802public:
2803 bool isSugared() const { return false; }
2804 QualType desugar() const { return QualType(this, 0); }
2805
2806 static bool classof(const Type *T) {
2807 return T->getTypeClass() == LValueReference;
2808 }
2809};
2810
2811/// An rvalue reference type, per C++11 [dcl.ref].
2812class RValueReferenceType : public ReferenceType {
2813 friend class ASTContext; // ASTContext creates these
2814
2815 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2816 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2817
2818public:
2819 bool isSugared() const { return false; }
2820 QualType desugar() const { return QualType(this, 0); }
2821
2822 static bool classof(const Type *T) {
2823 return T->getTypeClass() == RValueReference;
2824 }
2825};
2826
2827/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2828///
2829/// This includes both pointers to data members and pointer to member functions.
2830class MemberPointerType : public Type, public llvm::FoldingSetNode {
2831 friend class ASTContext; // ASTContext creates these.
2832
2833 QualType PointeeType;
2834
2835 /// The class of which the pointee is a member. Must ultimately be a
2836 /// RecordType, but could be a typedef or a template parameter too.
2837 const Type *Class;
2838
2839 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2840 : Type(MemberPointer, CanonicalPtr,
2841 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2842 Pointee->getDependence()),
2843 PointeeType(Pointee), Class(Cls) {}
2844
2845public:
2846 QualType getPointeeType() const { return PointeeType; }
2847
2848 /// Returns true if the member type (i.e. the pointee type) is a
2849 /// function type rather than a data-member type.
2850 bool isMemberFunctionPointer() const {
2851 return PointeeType->isFunctionProtoType();
2852 }
2853
2854 /// Returns true if the member type (i.e. the pointee type) is a
2855 /// data type rather than a function type.
2856 bool isMemberDataPointer() const {
2857 return !PointeeType->isFunctionProtoType();
2858 }
2859
2860 const Type *getClass() const { return Class; }
2861 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2862
2863 bool isSugared() const { return false; }
2864 QualType desugar() const { return QualType(this, 0); }
2865
2866 void Profile(llvm::FoldingSetNodeID &ID) {
2867 Profile(ID, getPointeeType(), getClass());
2868 }
2869
2870 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2871 const Type *Class) {
2872 ID.AddPointer(Pointee.getAsOpaquePtr());
2873 ID.AddPointer(Class);
2874 }
2875
2876 static bool classof(const Type *T) {
2877 return T->getTypeClass() == MemberPointer;
2878 }
2879};
2880
2881/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2882class ArrayType : public Type, public llvm::FoldingSetNode {
2883public:
2884 /// Capture whether this is a normal array (e.g. int X[4])
2885 /// an array with a static size (e.g. int X[static 4]), or an array
2886 /// with a star size (e.g. int X[*]).
2887 /// 'static' is only allowed on function parameters.
2888 enum ArraySizeModifier {
2889 Normal, Static, Star
2890 };
2891
2892private:
2893 /// The element type of the array.
2894 QualType ElementType;
2895
2896protected:
2897 friend class ASTContext; // ASTContext creates these.
2898
2899 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2900 unsigned tq, const Expr *sz = nullptr);
2901
2902public:
2903 QualType getElementType() const { return ElementType; }
2904
2905 ArraySizeModifier getSizeModifier() const {
2906 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2907 }
2908
2909 Qualifiers getIndexTypeQualifiers() const {
2910 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2911 }
2912
2913 unsigned getIndexTypeCVRQualifiers() const {
2914 return ArrayTypeBits.IndexTypeQuals;
2915 }
2916
2917 static bool classof(const Type *T) {
2918 return T->getTypeClass() == ConstantArray ||
2919 T->getTypeClass() == VariableArray ||
2920 T->getTypeClass() == IncompleteArray ||
2921 T->getTypeClass() == DependentSizedArray;
2922 }
2923};
2924
2925/// Represents the canonical version of C arrays with a specified constant size.
2926/// For example, the canonical type for 'int A[4 + 4*100]' is a
2927/// ConstantArrayType where the element type is 'int' and the size is 404.
2928class ConstantArrayType final
2929 : public ArrayType,
2930 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2931 friend class ASTContext; // ASTContext creates these.
2932 friend TrailingObjects;
2933
2934 llvm::APInt Size; // Allows us to unique the type.
2935
2936 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2937 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2938 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2939 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2940 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2941 assert(!can.isNull() && "canonical constant array should not have size")(static_cast<void> (0));
2942 *getTrailingObjects<const Expr*>() = sz;
2943 }
2944 }
2945
2946 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2947 return ConstantArrayTypeBits.HasStoredSizeExpr;
2948 }
2949
2950public:
2951 const llvm::APInt &getSize() const { return Size; }
2952 const Expr *getSizeExpr() const {
2953 return ConstantArrayTypeBits.HasStoredSizeExpr
2954 ? *getTrailingObjects<const Expr *>()
2955 : nullptr;
2956 }
2957 bool isSugared() const { return false; }
2958 QualType desugar() const { return QualType(this, 0); }
2959
2960 /// Determine the number of bits required to address a member of
2961 // an array with the given element type and number of elements.
2962 static unsigned getNumAddressingBits(const ASTContext &Context,
2963 QualType ElementType,
2964 const llvm::APInt &NumElements);
2965
2966 /// Determine the maximum number of active bits that an array's size
2967 /// can require, which limits the maximum size of the array.
2968 static unsigned getMaxSizeBits(const ASTContext &Context);
2969
2970 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2971 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2972 getSizeModifier(), getIndexTypeCVRQualifiers());
2973 }
2974
2975 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2976 QualType ET, const llvm::APInt &ArraySize,
2977 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2978 unsigned TypeQuals);
2979
2980 static bool classof(const Type *T) {
2981 return T->getTypeClass() == ConstantArray;
2982 }
2983};
2984
2985/// Represents a C array with an unspecified size. For example 'int A[]' has
2986/// an IncompleteArrayType where the element type is 'int' and the size is
2987/// unspecified.
2988class IncompleteArrayType : public ArrayType {
2989 friend class ASTContext; // ASTContext creates these.
2990
2991 IncompleteArrayType(QualType et, QualType can,
2992 ArraySizeModifier sm, unsigned tq)
2993 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2994
2995public:
2996 friend class StmtIteratorBase;
2997
2998 bool isSugared() const { return false; }
2999 QualType desugar() const { return QualType(this, 0); }
3000
3001 static bool classof(const Type *T) {
3002 return T->getTypeClass() == IncompleteArray;
3003 }
3004
3005 void Profile(llvm::FoldingSetNodeID &ID) {
3006 Profile(ID, getElementType(), getSizeModifier(),
3007 getIndexTypeCVRQualifiers());
3008 }
3009
3010 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3011 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3012 ID.AddPointer(ET.getAsOpaquePtr());
3013 ID.AddInteger(SizeMod);
3014 ID.AddInteger(TypeQuals);
3015 }
3016};
3017
3018/// Represents a C array with a specified size that is not an
3019/// integer-constant-expression. For example, 'int s[x+foo()]'.
3020/// Since the size expression is an arbitrary expression, we store it as such.
3021///
3022/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3023/// should not be: two lexically equivalent variable array types could mean
3024/// different things, for example, these variables do not have the same type
3025/// dynamically:
3026///
3027/// void foo(int x) {
3028/// int Y[x];
3029/// ++x;
3030/// int Z[x];
3031/// }
3032class VariableArrayType : public ArrayType {
3033 friend class ASTContext; // ASTContext creates these.
3034
3035 /// An assignment-expression. VLA's are only permitted within
3036 /// a function block.
3037 Stmt *SizeExpr;
3038
3039 /// The range spanned by the left and right array brackets.
3040 SourceRange Brackets;
3041
3042 VariableArrayType(QualType et, QualType can, Expr *e,
3043 ArraySizeModifier sm, unsigned tq,
3044 SourceRange brackets)
3045 : ArrayType(VariableArray, et, can, sm, tq, e),
3046 SizeExpr((Stmt*) e), Brackets(brackets) {}
3047
3048public:
3049 friend class StmtIteratorBase;
3050
3051 Expr *getSizeExpr() const {
3052 // We use C-style casts instead of cast<> here because we do not wish
3053 // to have a dependency of Type.h on Stmt.h/Expr.h.
3054 return (Expr*) SizeExpr;
3055 }
3056
3057 SourceRange getBracketsRange() const { return Brackets; }
3058 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3059 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3060
3061 bool isSugared() const { return false; }
3062 QualType desugar() const { return QualType(this, 0); }
3063
3064 static bool classof(const Type *T) {
3065 return T->getTypeClass() == VariableArray;
3066 }
3067
3068 void Profile(llvm::FoldingSetNodeID &ID) {
3069 llvm_unreachable("Cannot unique VariableArrayTypes.")__builtin_unreachable();
3070 }
3071};
3072
3073/// Represents an array type in C++ whose size is a value-dependent expression.
3074///
3075/// For example:
3076/// \code
3077/// template<typename T, int Size>
3078/// class array {
3079/// T data[Size];
3080/// };
3081/// \endcode
3082///
3083/// For these types, we won't actually know what the array bound is
3084/// until template instantiation occurs, at which point this will
3085/// become either a ConstantArrayType or a VariableArrayType.
3086class DependentSizedArrayType : public ArrayType {
3087 friend class ASTContext; // ASTContext creates these.
3088
3089 const ASTContext &Context;
3090
3091 /// An assignment expression that will instantiate to the
3092 /// size of the array.
3093 ///
3094 /// The expression itself might be null, in which case the array
3095 /// type will have its size deduced from an initializer.
3096 Stmt *SizeExpr;
3097
3098 /// The range spanned by the left and right array brackets.
3099 SourceRange Brackets;
3100
3101 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3102 Expr *e, ArraySizeModifier sm, unsigned tq,
3103 SourceRange brackets);
3104
3105public:
3106 friend class StmtIteratorBase;
3107
3108 Expr *getSizeExpr() const {
3109 // We use C-style casts instead of cast<> here because we do not wish
3110 // to have a dependency of Type.h on Stmt.h/Expr.h.
3111 return (Expr*) SizeExpr;
3112 }
3113
3114 SourceRange getBracketsRange() const { return Brackets; }
3115 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3116 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3117
3118 bool isSugared() const { return false; }
3119 QualType desugar() const { return QualType(this, 0); }
3120
3121 static bool classof(const Type *T) {
3122 return T->getTypeClass() == DependentSizedArray;
3123 }
3124
3125 void Profile(llvm::FoldingSetNodeID &ID) {
3126 Profile(ID, Context, getElementType(),
3127 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3128 }
3129
3130 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3131 QualType ET, ArraySizeModifier SizeMod,
3132 unsigned TypeQuals, Expr *E);
3133};
3134
3135/// Represents an extended address space qualifier where the input address space
3136/// value is dependent. Non-dependent address spaces are not represented with a
3137/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3138///
3139/// For example:
3140/// \code
3141/// template<typename T, int AddrSpace>
3142/// class AddressSpace {
3143/// typedef T __attribute__((address_space(AddrSpace))) type;
3144/// }
3145/// \endcode
3146class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3147 friend class ASTContext;
3148
3149 const ASTContext &Context;
3150 Expr *AddrSpaceExpr;
3151 QualType PointeeType;
3152 SourceLocation loc;
3153
3154 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3155 QualType can, Expr *AddrSpaceExpr,
3156 SourceLocation loc);
3157
3158public:
3159 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3160 QualType getPointeeType() const { return PointeeType; }
3161 SourceLocation getAttributeLoc() const { return loc; }
3162
3163 bool isSugared() const { return false; }
3164 QualType desugar() const { return QualType(this, 0); }
3165
3166 static bool classof(const Type *T) {
3167 return T->getTypeClass() == DependentAddressSpace;
3168 }
3169
3170 void Profile(llvm::FoldingSetNodeID &ID) {
3171 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3172 }
3173
3174 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3175 QualType PointeeType, Expr *AddrSpaceExpr);
3176};
3177
3178/// Represents an extended vector type where either the type or size is
3179/// dependent.
3180///
3181/// For example:
3182/// \code
3183/// template<typename T, int Size>
3184/// class vector {
3185/// typedef T __attribute__((ext_vector_type(Size))) type;
3186/// }
3187/// \endcode
3188class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3189 friend class ASTContext;
3190
3191 const ASTContext &Context;
3192 Expr *SizeExpr;
3193
3194 /// The element type of the array.
3195 QualType ElementType;
3196
3197 SourceLocation loc;
3198
3199 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3200 QualType can, Expr *SizeExpr, SourceLocation loc);
3201
3202public:
3203 Expr *getSizeExpr() const { return SizeExpr; }
3204 QualType getElementType() const { return ElementType; }
3205 SourceLocation getAttributeLoc() const { return loc; }
3206
3207 bool isSugared() const { return false; }
3208 QualType desugar() const { return QualType(this, 0); }
3209
3210 static bool classof(const Type *T) {
3211 return T->getTypeClass() == DependentSizedExtVector;
3212 }
3213
3214 void Profile(llvm::FoldingSetNodeID &ID) {
3215 Profile(ID, Context, getElementType(), getSizeExpr());
3216 }
3217
3218 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3219 QualType ElementType, Expr *SizeExpr);
3220};
3221
3222
3223/// Represents a GCC generic vector type. This type is created using
3224/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3225/// bytes; or from an Altivec __vector or vector declaration.
3226/// Since the constructor takes the number of vector elements, the
3227/// client is responsible for converting the size into the number of elements.
3228class VectorType : public Type, public llvm::FoldingSetNode {
3229public:
3230 enum VectorKind {
3231 /// not a target-specific vector type
3232 GenericVector,
3233
3234 /// is AltiVec vector
3235 AltiVecVector,
3236
3237 /// is AltiVec 'vector Pixel'
3238 AltiVecPixel,
3239
3240 /// is AltiVec 'vector bool ...'
3241 AltiVecBool,
3242
3243 /// is ARM Neon vector
3244 NeonVector,
3245
3246 /// is ARM Neon polynomial vector
3247 NeonPolyVector,
3248
3249 /// is AArch64 SVE fixed-length data vector
3250 SveFixedLengthDataVector,
3251
3252 /// is AArch64 SVE fixed-length predicate vector
3253 SveFixedLengthPredicateVector
3254 };
3255
3256protected:
3257 friend class ASTContext; // ASTContext creates these.
3258
3259 /// The element type of the vector.
3260 QualType ElementType;
3261
3262 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3263 VectorKind vecKind);
3264
3265 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3266 QualType canonType, VectorKind vecKind);
3267
3268public:
3269 QualType getElementType() const { return ElementType; }
3270 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3271
3272 bool isSugared() const { return false; }
3273 QualType desugar() const { return QualType(this, 0); }
3274
3275 VectorKind getVectorKind() const {
3276 return VectorKind(VectorTypeBits.VecKind);
3277 }
3278
3279 void Profile(llvm::FoldingSetNodeID &ID) {
3280 Profile(ID, getElementType(), getNumElements(),
3281 getTypeClass(), getVectorKind());
3282 }
3283
3284 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3285 unsigned NumElements, TypeClass TypeClass,
3286 VectorKind VecKind) {
3287 ID.AddPointer(ElementType.getAsOpaquePtr());
3288 ID.AddInteger(NumElements);
3289 ID.AddInteger(TypeClass);
3290 ID.AddInteger(VecKind);
3291 }
3292
3293 static bool classof(const Type *T) {
3294 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3295 }
3296};
3297
3298/// Represents a vector type where either the type or size is dependent.
3299////
3300/// For example:
3301/// \code
3302/// template<typename T, int Size>
3303/// class vector {
3304/// typedef T __attribute__((vector_size(Size))) type;
3305/// }
3306/// \endcode
3307class DependentVectorType : public Type, public llvm::FoldingSetNode {
3308 friend class ASTContext;
3309
3310 const ASTContext &Context;
3311 QualType ElementType;
3312 Expr *SizeExpr;
3313 SourceLocation Loc;
3314
3315 DependentVectorType(const ASTContext &Context, QualType ElementType,
3316 QualType CanonType, Expr *SizeExpr,
3317 SourceLocation Loc, VectorType::VectorKind vecKind);
3318
3319public:
3320 Expr *getSizeExpr() const { return SizeExpr; }
3321 QualType getElementType() const { return ElementType; }
3322 SourceLocation getAttributeLoc() const { return Loc; }
3323 VectorType::VectorKind getVectorKind() const {
3324 return VectorType::VectorKind(VectorTypeBits.VecKind);
3325 }
3326
3327 bool isSugared() const { return false; }
3328 QualType desugar() const { return QualType(this, 0); }
3329
3330 static bool classof(const Type *T) {
3331 return T->getTypeClass() == DependentVector;
3332 }
3333
3334 void Profile(llvm::FoldingSetNodeID &ID) {
3335 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3336 }
3337
3338 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3339 QualType ElementType, const Expr *SizeExpr,
3340 VectorType::VectorKind VecKind);
3341};
3342
3343/// ExtVectorType - Extended vector type. This type is created using
3344/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3345/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3346/// class enables syntactic extensions, like Vector Components for accessing
3347/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3348/// Shading Language).
3349class ExtVectorType : public VectorType {
3350 friend class ASTContext; // ASTContext creates these.
3351
3352 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3353 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3354
3355public:
3356 static int getPointAccessorIdx(char c) {
3357 switch (c) {
3358 default: return -1;
3359 case 'x': case 'r': return 0;
3360 case 'y': case 'g': return 1;
3361 case 'z': case 'b': return 2;
3362 case 'w': case 'a': return 3;
3363 }
3364 }
3365
3366 static int getNumericAccessorIdx(char c) {
3367 switch (c) {
3368 default: return -1;
3369 case '0': return 0;
3370 case '1': return 1;
3371 case '2': return 2;
3372 case '3': return 3;
3373 case '4': return 4;
3374 case '5': return 5;
3375 case '6': return 6;
3376 case '7': return 7;
3377 case '8': return 8;
3378 case '9': return 9;
3379 case 'A':
3380 case 'a': return 10;
3381 case 'B':
3382 case 'b': return 11;
3383 case 'C':
3384 case 'c': return 12;
3385 case 'D':
3386 case 'd': return 13;
3387 case 'E':
3388 case 'e': return 14;
3389 case 'F':
3390 case 'f': return 15;
3391 }
3392 }
3393
3394 static int getAccessorIdx(char c, bool isNumericAccessor) {
3395 if (isNumericAccessor)
3396 return getNumericAccessorIdx(c);
3397 else
3398 return getPointAccessorIdx(c);
3399 }
3400
3401 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3402 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3403 return unsigned(idx-1) < getNumElements();
3404 return false;
3405 }
3406
3407 bool isSugared() const { return false; }
3408 QualType desugar() const { return QualType(this, 0); }
3409
3410 static bool classof(const Type *T) {
3411 return T->getTypeClass() == ExtVector;
3412 }
3413};
3414
3415/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3416/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3417/// number of rows and "columns" specifies the number of columns.
3418class MatrixType : public Type, public llvm::FoldingSetNode {
3419protected:
3420 friend class ASTContext;
3421
3422 /// The element type of the matrix.
3423 QualType ElementType;
3424
3425 MatrixType(QualType ElementTy, QualType CanonElementTy);
3426
3427 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3428 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3429
3430public:
3431 /// Returns type of the elements being stored in the matrix
3432 QualType getElementType() const { return ElementType; }
3433
3434 /// Valid elements types are the following:
3435 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3436 /// and _Bool
3437 /// * the standard floating types float or double
3438 /// * a half-precision floating point type, if one is supported on the target
3439 static bool isValidElementType(QualType T) {
3440 return T->isDependentType() ||
3441 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3442 }
3443
3444 bool isSugared() const { return false; }
3445 QualType desugar() const { return QualType(this, 0); }
3446
3447 static bool classof(const Type *T) {
3448 return T->getTypeClass() == ConstantMatrix ||
3449 T->getTypeClass() == DependentSizedMatrix;
3450 }
3451};
3452
3453/// Represents a concrete matrix type with constant number of rows and columns
3454class ConstantMatrixType final : public MatrixType {
3455protected:
3456 friend class ASTContext;
3457
3458 /// Number of rows and columns.
3459 unsigned NumRows;
3460 unsigned NumColumns;
3461
3462 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3463
3464 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3465 unsigned NColumns, QualType CanonElementType);
3466
3467 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3468 unsigned NColumns, QualType CanonElementType);
3469
3470public:
3471 /// Returns the number of rows in the matrix.
3472 unsigned getNumRows() const { return NumRows; }
3473
3474 /// Returns the number of columns in the matrix.
3475 unsigned getNumColumns() const { return NumColumns; }
3476
3477 /// Returns the number of elements required to embed the matrix into a vector.
3478 unsigned getNumElementsFlattened() const {
3479 return getNumRows() * getNumColumns();
3480 }
3481
3482 /// Returns true if \p NumElements is a valid matrix dimension.
3483 static constexpr bool isDimensionValid(size_t NumElements) {
3484 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3485 }
3486
3487 /// Returns the maximum number of elements per dimension.
3488 static constexpr unsigned getMaxElementsPerDimension() {
3489 return MaxElementsPerDimension;
3490 }
3491
3492 void Profile(llvm::FoldingSetNodeID &ID) {
3493 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3494 getTypeClass());
3495 }
3496
3497 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3498 unsigned NumRows, unsigned NumColumns,
3499 TypeClass TypeClass) {
3500 ID.AddPointer(ElementType.getAsOpaquePtr());
3501 ID.AddInteger(NumRows);
3502 ID.AddInteger(NumColumns);
3503 ID.AddInteger(TypeClass);
3504 }
3505
3506 static bool classof(const Type *T) {
3507 return T->getTypeClass() == ConstantMatrix;
3508 }
3509};
3510
3511/// Represents a matrix type where the type and the number of rows and columns
3512/// is dependent on a template.
3513class DependentSizedMatrixType final : public MatrixType {
3514 friend class ASTContext;
3515
3516 const ASTContext &Context;
3517 Expr *RowExpr;
3518 Expr *ColumnExpr;
3519
3520 SourceLocation loc;
3521
3522 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3523 QualType CanonicalType, Expr *RowExpr,
3524 Expr *ColumnExpr, SourceLocation loc);
3525
3526public:
3527 Expr *getRowExpr() const { return RowExpr; }
3528 Expr *getColumnExpr() const { return ColumnExpr; }
3529 SourceLocation getAttributeLoc() const { return loc; }
3530
3531 static bool classof(const Type *T) {
3532 return T->getTypeClass() == DependentSizedMatrix;
3533 }
3534
3535 void Profile(llvm::FoldingSetNodeID &ID) {
3536 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3537 }
3538
3539 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3540 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3541};
3542
3543/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3544/// class of FunctionNoProtoType and FunctionProtoType.
3545class FunctionType : public Type {
3546 // The type returned by the function.
3547 QualType ResultType;
3548
3549public:
3550 /// Interesting information about a specific parameter that can't simply
3551 /// be reflected in parameter's type. This is only used by FunctionProtoType
3552 /// but is in FunctionType to make this class available during the
3553 /// specification of the bases of FunctionProtoType.
3554 ///
3555 /// It makes sense to model language features this way when there's some
3556 /// sort of parameter-specific override (such as an attribute) that
3557 /// affects how the function is called. For example, the ARC ns_consumed
3558 /// attribute changes whether a parameter is passed at +0 (the default)
3559 /// or +1 (ns_consumed). This must be reflected in the function type,
3560 /// but isn't really a change to the parameter type.
3561 ///
3562 /// One serious disadvantage of modelling language features this way is
3563 /// that they generally do not work with language features that attempt
3564 /// to destructure types. For example, template argument deduction will
3565 /// not be able to match a parameter declared as
3566 /// T (*)(U)
3567 /// against an argument of type
3568 /// void (*)(__attribute__((ns_consumed)) id)
3569 /// because the substitution of T=void, U=id into the former will
3570 /// not produce the latter.
3571 class ExtParameterInfo {
3572 enum {
3573 ABIMask = 0x0F,
3574 IsConsumed = 0x10,
3575 HasPassObjSize = 0x20,
3576 IsNoEscape = 0x40,
3577 };
3578 unsigned char Data = 0;
3579
3580 public:
3581 ExtParameterInfo() = default;
3582
3583 /// Return the ABI treatment of this parameter.
3584 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3585 ExtParameterInfo withABI(ParameterABI kind) const {
3586 ExtParameterInfo copy = *this;
3587 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3588 return copy;
3589 }
3590
3591 /// Is this parameter considered "consumed" by Objective-C ARC?
3592 /// Consumed parameters must have retainable object type.
3593 bool isConsumed() const { return (Data & IsConsumed); }
3594 ExtParameterInfo withIsConsumed(bool consumed) const {
3595 ExtParameterInfo copy = *this;
3596 if (consumed)
3597 copy.Data |= IsConsumed;
3598 else
3599 copy.Data &= ~IsConsumed;
3600 return copy;
3601 }
3602
3603 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3604 ExtParameterInfo withHasPassObjectSize() const {
3605 ExtParameterInfo Copy = *this;
3606 Copy.Data |= HasPassObjSize;
3607 return Copy;
3608 }
3609
3610 bool isNoEscape() const { return Data & IsNoEscape; }
3611 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3612 ExtParameterInfo Copy = *this;
3613 if (NoEscape)
3614 Copy.Data |= IsNoEscape;
3615 else
3616 Copy.Data &= ~IsNoEscape;
3617 return Copy;
3618 }
3619
3620 unsigned char getOpaqueValue() const { return Data; }
3621 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3622 ExtParameterInfo result;
3623 result.Data = data;
3624 return result;
3625 }
3626
3627 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3628 return lhs.Data == rhs.Data;
3629 }
3630
3631 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3632 return lhs.Data != rhs.Data;
3633 }
3634 };
3635
3636 /// A class which abstracts out some details necessary for
3637 /// making a call.
3638 ///
3639 /// It is not actually used directly for storing this information in
3640 /// a FunctionType, although FunctionType does currently use the
3641 /// same bit-pattern.
3642 ///
3643 // If you add a field (say Foo), other than the obvious places (both,
3644 // constructors, compile failures), what you need to update is
3645 // * Operator==
3646 // * getFoo
3647 // * withFoo
3648 // * functionType. Add Foo, getFoo.
3649 // * ASTContext::getFooType
3650 // * ASTContext::mergeFunctionTypes
3651 // * FunctionNoProtoType::Profile
3652 // * FunctionProtoType::Profile
3653 // * TypePrinter::PrintFunctionProto
3654 // * AST read and write
3655 // * Codegen
3656 class ExtInfo {
3657 friend class FunctionType;
3658
3659 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3660 // adjust the Bits field below, and if you add bits, you'll need to adjust
3661 // Type::FunctionTypeBitfields::ExtInfo as well.
3662
3663 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3664 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3665 //
3666 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3667 enum { CallConvMask = 0x1F };
3668 enum { NoReturnMask = 0x20 };
3669 enum { ProducesResultMask = 0x40 };
3670 enum { NoCallerSavedRegsMask = 0x80 };
3671 enum {
3672 RegParmMask = 0x700,
3673 RegParmOffset = 8
3674 };
3675 enum { NoCfCheckMask = 0x800 };
3676 enum { CmseNSCallMask = 0x1000 };
3677 uint16_t Bits = CC_C;
3678
3679 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3680
3681 public:
3682 // Constructor with no defaults. Use this when you know that you
3683 // have all the elements (when reading an AST file for example).
3684 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3685 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3686 bool cmseNSCall) {
3687 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(static_cast<void> (0));
3688 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3689 (producesResult ? ProducesResultMask : 0) |
3690 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3691 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3692 (NoCfCheck ? NoCfCheckMask : 0) |
3693 (cmseNSCall ? CmseNSCallMask : 0);
3694 }
3695
3696 // Constructor with all defaults. Use when for example creating a
3697 // function known to use defaults.
3698 ExtInfo() = default;
3699
3700 // Constructor with just the calling convention, which is an important part
3701 // of the canonical type.
3702 ExtInfo(CallingConv CC) : Bits(CC) {}
3703
3704 bool getNoReturn() const { return Bits & NoReturnMask; }
3705 bool getProducesResult() const { return Bits & ProducesResultMask; }
3706 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3707 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3708 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3709 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3710
3711 unsigned getRegParm() const {
3712 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3713 if (RegParm > 0)
3714 --RegParm;
3715 return RegParm;
3716 }
3717
3718 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3719
3720 bool operator==(ExtInfo Other) const {
3721 return Bits == Other.Bits;
3722 }
3723 bool operator!=(ExtInfo Other) const {
3724 return Bits != Other.Bits;
3725 }
3726
3727 // Note that we don't have setters. That is by design, use
3728 // the following with methods instead of mutating these objects.
3729
3730 ExtInfo withNoReturn(bool noReturn) const {
3731 if (noReturn)
3732 return ExtInfo(Bits | NoReturnMask);
3733 else
3734 return ExtInfo(Bits & ~NoReturnMask);
3735 }
3736
3737 ExtInfo withProducesResult(bool producesResult) const {
3738 if (producesResult)
3739 return ExtInfo(Bits | ProducesResultMask);
3740 else
3741 return ExtInfo(Bits & ~ProducesResultMask);
3742 }
3743
3744 ExtInfo withCmseNSCall(bool cmseNSCall) const {
3745 if (cmseNSCall)
3746 return ExtInfo(Bits | CmseNSCallMask);
3747 else
3748 return ExtInfo(Bits & ~CmseNSCallMask);
3749 }
3750
3751 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3752 if (noCallerSavedRegs)
3753 return ExtInfo(Bits | NoCallerSavedRegsMask);
3754 else
3755 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3756 }
3757
3758 ExtInfo withNoCfCheck(bool noCfCheck) const {
3759 if (noCfCheck)
3760 return ExtInfo(Bits | NoCfCheckMask);
3761 else
3762 return ExtInfo(Bits & ~NoCfCheckMask);
3763 }
3764
3765 ExtInfo withRegParm(unsigned RegParm) const {
3766 assert(RegParm < 7 && "Invalid regparm value")(static_cast<void> (0));
3767 return ExtInfo((Bits & ~RegParmMask) |
3768 ((RegParm + 1) << RegParmOffset));
3769 }
3770
3771 ExtInfo withCallingConv(CallingConv cc) const {
3772 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3773 }
3774
3775 void Profile(llvm::FoldingSetNodeID &ID) const {
3776 ID.AddInteger(Bits);
3777 }
3778 };
3779
3780 /// A simple holder for a QualType representing a type in an
3781 /// exception specification. Unfortunately needed by FunctionProtoType
3782 /// because TrailingObjects cannot handle repeated types.
3783 struct ExceptionType { QualType Type; };
3784
3785 /// A simple holder for various uncommon bits which do not fit in
3786 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3787 /// alignment of subsequent objects in TrailingObjects. You must update
3788 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3789 struct alignas(void *) FunctionTypeExtraBitfields {
3790 /// The number of types in the exception specification.
3791 /// A whole unsigned is not needed here and according to
3792 /// [implimits] 8 bits would be enough here.
3793 unsigned NumExceptionType;
3794 };
3795
3796protected:
3797 FunctionType(TypeClass tc, QualType res, QualType Canonical,
3798 TypeDependence Dependence, ExtInfo Info)
3799 : Type(tc, Canonical, Dependence), ResultType(res) {
3800 FunctionTypeBits.ExtInfo = Info.Bits;
3801 }
3802
3803 Qualifiers getFastTypeQuals() const {
3804 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3805 }
3806
3807public:
3808 QualType getReturnType() const { return ResultType; }
3809
3810 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3811 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3812
3813 /// Determine whether this function type includes the GNU noreturn
3814 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3815 /// type.
3816 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3817
3818 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3819 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3820 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3821
3822 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3823 "Const, volatile and restrict are assumed to be a subset of "
3824 "the fast qualifiers.");
3825
3826 bool isConst() const { return getFastTypeQuals().hasConst(); }
3827 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3828 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3829
3830 /// Determine the type of an expression that calls a function of
3831 /// this type.
3832 QualType getCallResultType(const ASTContext &Context) const {
3833 return getReturnType().getNonLValueExprType(Context);
3834 }
3835
3836 static StringRef getNameForCallConv(CallingConv CC);
3837
3838 static bool classof(const Type *T) {
3839 return T->getTypeClass() == FunctionNoProto ||
3840 T->getTypeClass() == FunctionProto;
3841 }
3842};
3843
3844/// Represents a K&R-style 'int foo()' function, which has
3845/// no information available about its arguments.
3846class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3847 friend class ASTContext; // ASTContext creates these.
3848
3849 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3850 : FunctionType(FunctionNoProto, Result, Canonical,
3851 Result->getDependence() &
3852 ~(TypeDependence::DependentInstantiation |
3853 TypeDependence::UnexpandedPack),
3854 Info) {}
3855
3856public:
3857 // No additional state past what FunctionType provides.
3858
3859 bool isSugared() const { return false; }
3860 QualType desugar() const { return QualType(this, 0); }
3861
3862 void Profile(llvm::FoldingSetNodeID &ID) {
3863 Profile(ID, getReturnType(), getExtInfo());
3864 }
3865
3866 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3867 ExtInfo Info) {
3868 Info.Profile(ID);
3869 ID.AddPointer(ResultType.getAsOpaquePtr());
3870 }
3871
3872 static bool classof(const Type *T) {
3873 return T->getTypeClass() == FunctionNoProto;
3874 }
3875};
3876
3877/// Represents a prototype with parameter type info, e.g.
3878/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3879/// parameters, not as having a single void parameter. Such a type can have
3880/// an exception specification, but this specification is not part of the
3881/// canonical type. FunctionProtoType has several trailing objects, some of
3882/// which optional. For more information about the trailing objects see
3883/// the first comment inside FunctionProtoType.
3884class FunctionProtoType final
3885 : public FunctionType,
3886 public llvm::FoldingSetNode,
3887 private llvm::TrailingObjects<
3888 FunctionProtoType, QualType, SourceLocation,
3889 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3890 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3891 friend class ASTContext; // ASTContext creates these.
3892 friend TrailingObjects;
3893
3894 // FunctionProtoType is followed by several trailing objects, some of
3895 // which optional. They are in order:
3896 //
3897 // * An array of getNumParams() QualType holding the parameter types.
3898 // Always present. Note that for the vast majority of FunctionProtoType,
3899 // these will be the only trailing objects.
3900 //
3901 // * Optionally if the function is variadic, the SourceLocation of the
3902 // ellipsis.
3903 //
3904 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3905 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3906 // a single FunctionTypeExtraBitfields. Present if and only if
3907 // hasExtraBitfields() is true.
3908 //
3909 // * Optionally exactly one of:
3910 // * an array of getNumExceptions() ExceptionType,
3911 // * a single Expr *,
3912 // * a pair of FunctionDecl *,
3913 // * a single FunctionDecl *
3914 // used to store information about the various types of exception
3915 // specification. See getExceptionSpecSize for the details.
3916 //
3917 // * Optionally an array of getNumParams() ExtParameterInfo holding
3918 // an ExtParameterInfo for each of the parameters. Present if and
3919 // only if hasExtParameterInfos() is true.
3920 //
3921 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3922 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3923 // if hasExtQualifiers() is true.
3924 //
3925 // The optional FunctionTypeExtraBitfields has to be before the data
3926 // related to the exception specification since it contains the number
3927 // of exception types.
3928 //
3929 // We put the ExtParameterInfos last. If all were equal, it would make
3930 // more sense to put these before the exception specification, because
3931 // it's much easier to skip past them compared to the elaborate switch
3932 // required to skip the exception specification. However, all is not
3933 // equal; ExtParameterInfos are used to model very uncommon features,
3934 // and it's better not to burden the more common paths.
3935
3936public:
3937 /// Holds information about the various types of exception specification.
3938 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3939 /// used to group together the various bits of information about the
3940 /// exception specification.
3941 struct ExceptionSpecInfo {
3942 /// The kind of exception specification this is.
3943 ExceptionSpecificationType Type = EST_None;
3944
3945 /// Explicitly-specified list of exception types.
3946 ArrayRef<QualType> Exceptions;
3947
3948 /// Noexcept expression, if this is a computed noexcept specification.
3949 Expr *NoexceptExpr = nullptr;
3950
3951 /// The function whose exception specification this is, for
3952 /// EST_Unevaluated and EST_Uninstantiated.
3953 FunctionDecl *SourceDecl = nullptr;
3954
3955 /// The function template whose exception specification this is instantiated
3956 /// from, for EST_Uninstantiated.
3957 FunctionDecl *SourceTemplate = nullptr;
3958
3959 ExceptionSpecInfo() = default;
3960
3961 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3962 };
3963
3964 /// Extra information about a function prototype. ExtProtoInfo is not
3965 /// stored as such in FunctionProtoType but is used to group together
3966 /// the various bits of extra information about a function prototype.
3967 struct ExtProtoInfo {
3968 FunctionType::ExtInfo ExtInfo;
3969 bool Variadic : 1;
3970 bool HasTrailingReturn : 1;
3971 Qualifiers TypeQuals;
3972 RefQualifierKind RefQualifier = RQ_None;
3973 ExceptionSpecInfo ExceptionSpec;
3974 const ExtParameterInfo *ExtParameterInfos = nullptr;
3975 SourceLocation EllipsisLoc;
3976
3977 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3978
3979 ExtProtoInfo(CallingConv CC)
3980 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3981
3982 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3983 ExtProtoInfo Result(*this);
3984 Result.ExceptionSpec = ESI;
3985 return Result;
3986 }
3987 };
3988
3989private:
3990 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3991 return getNumParams();
3992 }
3993
3994 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3995 return isVariadic();
3996 }
3997
3998 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3999 return hasExtraBitfields();
4000 }
4001
4002 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
4003 return getExceptionSpecSize().NumExceptionType;
4004 }
4005
4006 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4007 return getExceptionSpecSize().NumExprPtr;
4008 }
4009
4010 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4011 return getExceptionSpecSize().NumFunctionDeclPtr;
4012 }
4013
4014 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4015 return hasExtParameterInfos() ? getNumParams() : 0;
4016 }
4017
4018 /// Determine whether there are any argument types that
4019 /// contain an unexpanded parameter pack.
4020 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4021 unsigned numArgs) {
4022 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4023 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4024 return true;
4025
4026 return false;
4027 }
4028
4029 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4030 QualType canonical, const ExtProtoInfo &epi);
4031
4032 /// This struct is returned by getExceptionSpecSize and is used to
4033 /// translate an ExceptionSpecificationType to the number and kind
4034 /// of trailing objects related to the exception specification.
4035 struct ExceptionSpecSizeHolder {
4036 unsigned NumExceptionType;
4037 unsigned NumExprPtr;
4038 unsigned NumFunctionDeclPtr;
4039 };
4040
4041 /// Return the number and kind of trailing objects
4042 /// related to the exception specification.
4043 static ExceptionSpecSizeHolder
4044 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4045 switch (EST) {
4046 case EST_None:
4047 case EST_DynamicNone:
4048 case EST_MSAny:
4049 case EST_BasicNoexcept:
4050 case EST_Unparsed:
4051 case EST_NoThrow:
4052 return {0, 0, 0};
4053
4054 case EST_Dynamic:
4055 return {NumExceptions, 0, 0};
4056
4057 case EST_DependentNoexcept:
4058 case EST_NoexceptFalse:
4059 case EST_NoexceptTrue:
4060 return {0, 1, 0};
4061
4062 case EST_Uninstantiated:
4063 return {0, 0, 2};
4064
4065 case EST_Unevaluated:
4066 return {0, 0, 1};
4067 }
4068 llvm_unreachable("bad exception specification kind")__builtin_unreachable();
4069 }
4070
4071 /// Return the number and kind of trailing objects
4072 /// related to the exception specification.
4073 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4074 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4075 }
4076
4077 /// Whether the trailing FunctionTypeExtraBitfields is present.
4078 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4079 // If the exception spec type is EST_Dynamic then we have > 0 exception
4080 // types and the exact number is stored in FunctionTypeExtraBitfields.
4081 return EST == EST_Dynamic;
4082 }
4083
4084 /// Whether the trailing FunctionTypeExtraBitfields is present.
4085 bool hasExtraBitfields() const {
4086 return hasExtraBitfields(getExceptionSpecType());
4087 }
4088
4089 bool hasExtQualifiers() const {
4090 return FunctionTypeBits.HasExtQuals;
4091 }
4092
4093public:
4094 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4095
4096 QualType getParamType(unsigned i) const {
4097 assert(i < getNumParams() && "invalid parameter index")(static_cast<void> (0));
4098 return param_type_begin()[i];
4099 }
4100
4101 ArrayRef<QualType> getParamTypes() const {
4102 return llvm::makeArrayRef(param_type_begin(), param_type_end());
4103 }
4104
4105 ExtProtoInfo getExtProtoInfo() const {
4106 ExtProtoInfo EPI;
4107 EPI.ExtInfo = getExtInfo();
4108 EPI.Variadic = isVariadic();
4109 EPI.EllipsisLoc = getEllipsisLoc();
4110 EPI.HasTrailingReturn = hasTrailingReturn();
4111 EPI.ExceptionSpec = getExceptionSpecInfo();
4112 EPI.TypeQuals = getMethodQuals();
4113 EPI.RefQualifier = getRefQualifier();
4114 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4115 return EPI;
4116 }
4117
4118 /// Get the kind of exception specification on this function.
4119 ExceptionSpecificationType getExceptionSpecType() const {
4120 return static_cast<ExceptionSpecificationType>(
4121 FunctionTypeBits.ExceptionSpecType);
4122 }
4123
4124 /// Return whether this function has any kind of exception spec.
4125 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4126
4127 /// Return whether this function has a dynamic (throw) exception spec.
4128 bool hasDynamicExceptionSpec() const {
4129 return isDynamicExceptionSpec(getExceptionSpecType());
4130 }
4131
4132 /// Return whether this function has a noexcept exception spec.
4133 bool hasNoexceptExceptionSpec() const {
4134 return isNoexceptExceptionSpec(getExceptionSpecType());
4135 }
4136
4137 /// Return whether this function has a dependent exception spec.
4138 bool hasDependentExceptionSpec() const;
4139
4140 /// Return whether this function has an instantiation-dependent exception
4141 /// spec.
4142 bool hasInstantiationDependentExceptionSpec() const;
4143
4144 /// Return all the available information about this type's exception spec.
4145 ExceptionSpecInfo getExceptionSpecInfo() const {
4146 ExceptionSpecInfo Result;
4147 Result.Type = getExceptionSpecType();
4148 if (Result.Type == EST_Dynamic) {
4149 Result.Exceptions = exceptions();
4150 } else if (isComputedNoexcept(Result.Type)) {
4151 Result.NoexceptExpr = getNoexceptExpr();
4152 } else if (Result.Type == EST_Uninstantiated) {
4153 Result.SourceDecl = getExceptionSpecDecl();
4154 Result.SourceTemplate = getExceptionSpecTemplate();
4155 } else if (Result.Type == EST_Unevaluated) {
4156 Result.SourceDecl = getExceptionSpecDecl();
4157 }
4158 return Result;
4159 }
4160
4161 /// Return the number of types in the exception specification.
4162 unsigned getNumExceptions() const {
4163 return getExceptionSpecType() == EST_Dynamic
4164 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4165 ->NumExceptionType
4166 : 0;
4167 }
4168
4169 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4170 QualType getExceptionType(unsigned i) const {
4171 assert(i < getNumExceptions() && "Invalid exception number!")(static_cast<void> (0));
4172 return exception_begin()[i];
4173 }
4174
4175 /// Return the expression inside noexcept(expression), or a null pointer
4176 /// if there is none (because the exception spec is not of this form).
4177 Expr *getNoexceptExpr() const {
4178 if (!isComputedNoexcept(getExceptionSpecType()))
4179 return nullptr;
4180 return *getTrailingObjects<Expr *>();
4181 }
4182
4183 /// If this function type has an exception specification which hasn't
4184 /// been determined yet (either because it has not been evaluated or because
4185 /// it has not been instantiated), this is the function whose exception
4186 /// specification is represented by this type.
4187 FunctionDecl *getExceptionSpecDecl() const {
4188 if (getExceptionSpecType() != EST_Uninstantiated &&
4189 getExceptionSpecType() != EST_Unevaluated)
4190 return nullptr;
4191 return getTrailingObjects<FunctionDecl *>()[0];
4192 }
4193
4194 /// If this function type has an uninstantiated exception
4195 /// specification, this is the function whose exception specification
4196 /// should be instantiated to find the exception specification for
4197 /// this type.
4198 FunctionDecl *getExceptionSpecTemplate() const {
4199 if (getExceptionSpecType() != EST_Uninstantiated)
4200 return nullptr;
4201 return getTrailingObjects<FunctionDecl *>()[1];
4202 }
4203
4204 /// Determine whether this function type has a non-throwing exception
4205 /// specification.
4206 CanThrowResult canThrow() const;
4207
4208 /// Determine whether this function type has a non-throwing exception
4209 /// specification. If this depends on template arguments, returns
4210 /// \c ResultIfDependent.
4211 bool isNothrow(bool ResultIfDependent = false) const {
4212 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4213 }
4214
4215 /// Whether this function prototype is variadic.
4216 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4217
4218 SourceLocation getEllipsisLoc() const {
4219 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4220 : SourceLocation();
4221 }
4222
4223 /// Determines whether this function prototype contains a
4224 /// parameter pack at the end.
4225 ///
4226 /// A function template whose last parameter is a parameter pack can be
4227 /// called with an arbitrary number of arguments, much like a variadic
4228 /// function.
4229 bool isTemplateVariadic() const;
4230
4231 /// Whether this function prototype has a trailing return type.
4232 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4233
4234 Qualifiers getMethodQuals() const {
4235 if (hasExtQualifiers())
4236 return *getTrailingObjects<Qualifiers>();
4237 else
4238 return getFastTypeQuals();
4239 }
4240
4241 /// Retrieve the ref-qualifier associated with this function type.
4242 RefQualifierKind getRefQualifier() const {
4243 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4244 }
4245
4246 using param_type_iterator = const QualType *;
4247 using param_type_range = llvm::iterator_range<param_type_iterator>;
4248
4249 param_type_range param_types() const {
4250 return param_type_range(param_type_begin(), param_type_end());
4251 }
4252
4253 param_type_iterator param_type_begin() const {
4254 return getTrailingObjects<QualType>();
4255 }
4256
4257 param_type_iterator param_type_end() const {
4258 return param_type_begin() + getNumParams();
4259 }
4260
4261 using exception_iterator = const QualType *;
4262
4263 ArrayRef<QualType> exceptions() const {
4264 return llvm::makeArrayRef(exception_begin(), exception_end());
4265 }
4266
4267 exception_iterator exception_begin() const {
4268 return reinterpret_cast<exception_iterator>(
4269 getTrailingObjects<ExceptionType>());
4270 }
4271
4272 exception_iterator exception_end() const {
4273 return exception_begin() + getNumExceptions();
4274 }
4275
4276 /// Is there any interesting extra information for any of the parameters
4277 /// of this function type?
4278 bool hasExtParameterInfos() const {
4279 return FunctionTypeBits.HasExtParameterInfos;
4280 }
4281
4282 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4283 assert(hasExtParameterInfos())(static_cast<void> (0));
4284 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4285 getNumParams());
4286 }
4287
4288 /// Return a pointer to the beginning of the array of extra parameter
4289 /// information, if present, or else null if none of the parameters
4290 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4291 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4292 if (!hasExtParameterInfos())
4293 return nullptr;
4294 return getTrailingObjects<ExtParameterInfo>();
4295 }
4296
4297 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4298 assert(I < getNumParams() && "parameter index out of range")(static_cast<void> (0));
4299 if (hasExtParameterInfos())
4300 return getTrailingObjects<ExtParameterInfo>()[I];
4301 return ExtParameterInfo();
4302 }
4303
4304 ParameterABI getParameterABI(unsigned I) const {
4305 assert(I < getNumParams() && "parameter index out of range")(static_cast<void> (0));
4306 if (hasExtParameterInfos())
4307 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4308 return ParameterABI::Ordinary;
4309 }
4310
4311 bool isParamConsumed(unsigned I) const {
4312 assert(I < getNumParams() && "parameter index out of range")(static_cast<void> (0));
4313 if (hasExtParameterInfos())
4314 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4315 return false;
4316 }
4317
4318 bool isSugared() const { return false; }
4319 QualType desugar() const { return QualType(this, 0); }
4320
4321 void printExceptionSpecification(raw_ostream &OS,
4322 const PrintingPolicy &Policy) const;
4323
4324 static bool classof(const Type *T) {
4325 return T->getTypeClass() == FunctionProto;
4326 }
4327
4328 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4329 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4330 param_type_iterator ArgTys, unsigned NumArgs,
4331 const ExtProtoInfo &EPI, const ASTContext &Context,
4332 bool Canonical);
4333};
4334
4335/// Represents the dependent type named by a dependently-scoped
4336/// typename using declaration, e.g.
4337/// using typename Base<T>::foo;
4338///
4339/// Template instantiation turns these into the underlying type.
4340class UnresolvedUsingType : public Type {
4341 friend class ASTContext; // ASTContext creates these.
4342
4343 UnresolvedUsingTypenameDecl *Decl;
4344
4345 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4346 : Type(UnresolvedUsing, QualType(),
4347 TypeDependence::DependentInstantiation),
4348 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4349
4350public:
4351 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4352
4353 bool isSugared() const { return false; }
4354 QualType desugar() const { return QualType(this, 0); }
4355
4356 static bool classof(const Type *T) {
4357 return T->getTypeClass() == UnresolvedUsing;
4358 }
4359
4360 void Profile(llvm::FoldingSetNodeID &ID) {
4361 return Profile(ID, Decl);
4362 }
4363
4364 static void Profile(llvm::FoldingSetNodeID &ID,
4365 UnresolvedUsingTypenameDecl *D) {
4366 ID.AddPointer(D);
4367 }
4368};
4369
4370class TypedefType : public Type {
4371 TypedefNameDecl *Decl;
4372
4373private:
4374 friend class ASTContext; // ASTContext creates these.
4375
4376 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
4377 QualType can);
4378
4379public:
4380 TypedefNameDecl *getDecl() const { return Decl; }
4381
4382 bool isSugared() const { return true; }
4383 QualType desugar() const;
4384
4385 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4386};
4387
4388/// Sugar type that represents a type that was qualified by a qualifier written
4389/// as a macro invocation.
4390class MacroQualifiedType : public Type {
4391 friend class ASTContext; // ASTContext creates these.
4392
4393 QualType UnderlyingTy;
4394 const IdentifierInfo *MacroII;
4395
4396 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4397 const IdentifierInfo *MacroII)
4398 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4399 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4400 assert(isa<AttributedType>(UnderlyingTy) &&(static_cast<void> (0))
4401 "Expected a macro qualified type to only wrap attributed types.")(static_cast<void> (0));
4402 }
4403
4404public:
4405 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4406 QualType getUnderlyingType() const { return UnderlyingTy; }
4407
4408 /// Return this attributed type's modified type with no qualifiers attached to
4409 /// it.
4410 QualType getModifiedType() const;
4411
4412 bool isSugared() const { return true; }
4413 QualType desugar() const;
4414
4415 static bool classof(const Type *T) {
4416 return T->getTypeClass() == MacroQualified;
4417 }
4418};
4419
4420/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4421class TypeOfExprType : public Type {
4422 Expr *TOExpr;
4423
4424protected:
4425 friend class ASTContext; // ASTContext creates these.
4426
4427 TypeOfExprType(Expr *E, QualType can = QualType());
4428
4429public:
4430 Expr *getUnderlyingExpr() const { return TOExpr; }
4431
4432 /// Remove a single level of sugar.
4433 QualType desugar() const;
4434
4435 /// Returns whether this type directly provides sugar.
4436 bool isSugared() const;
4437
4438 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4439};
4440
4441/// Internal representation of canonical, dependent
4442/// `typeof(expr)` types.
4443///
4444/// This class is used internally by the ASTContext to manage
4445/// canonical, dependent types, only. Clients will only see instances
4446/// of this class via TypeOfExprType nodes.
4447class DependentTypeOfExprType
4448 : public TypeOfExprType, public llvm::FoldingSetNode {
4449 const ASTContext &Context;
4450
4451public:
4452 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4453 : TypeOfExprType(E), Context(Context) {}
4454
4455 void Profile(llvm::FoldingSetNodeID &ID) {
4456 Profile(ID, Context, getUnderlyingExpr());
4457 }
4458
4459 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4460 Expr *E);
4461};
4462
4463/// Represents `typeof(type)`, a GCC extension.
4464class TypeOfType : public Type {
4465 friend class ASTContext; // ASTContext creates these.
4466
4467 QualType TOType;
4468
4469 TypeOfType(QualType T, QualType can)
4470 : Type(TypeOf, can, T->getDependence()), TOType(T) {
4471 assert(!isa<TypedefType>(can) && "Invalid canonical type")(static_cast<void> (0));
4472 }
4473
4474public:
4475 QualType getUnderlyingType() const { return TOType; }
4476
4477 /// Remove a single level of sugar.
4478 QualType desugar() const { return getUnderlyingType(); }
4479
4480 /// Returns whether this type directly provides sugar.
4481 bool isSugared() const { return true; }
4482
4483 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4484};
4485
4486/// Represents the type `decltype(expr)` (C++11).
4487class DecltypeType : public Type {
4488 Expr *E;
4489 QualType UnderlyingType;
4490
4491protected:
4492 friend class ASTContext; // ASTContext creates these.
4493
4494 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4495
4496public:
4497 Expr *getUnderlyingExpr() const { return E; }
4498 QualType getUnderlyingType() const { return UnderlyingType; }
4499
4500 /// Remove a single level of sugar.
4501 QualType desugar() const;
4502
4503 /// Returns whether this type directly provides sugar.
4504 bool isSugared() const;
4505
4506 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4507};
4508
4509/// Internal representation of canonical, dependent
4510/// decltype(expr) types.
4511///
4512/// This class is used internally by the ASTContext to manage
4513/// canonical, dependent types, only. Clients will only see instances
4514/// of this class via DecltypeType nodes.
4515class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4516 const ASTContext &Context;
4517
4518public:
4519 DependentDecltypeType(const ASTContext &Context, Expr *E);
4520
4521 void Profile(llvm::FoldingSetNodeID &ID) {
4522 Profile(ID, Context, getUnderlyingExpr());
4523 }
4524
4525 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4526 Expr *E);
4527};
4528
4529/// A unary type transform, which is a type constructed from another.
4530class UnaryTransformType : public Type {
4531public:
4532 enum UTTKind {
4533 EnumUnderlyingType
4534 };
4535
4536private:
4537 /// The untransformed type.
4538 QualType BaseType;
4539
4540 /// The transformed type if not dependent, otherwise the same as BaseType.
4541 QualType UnderlyingType;
4542
4543 UTTKind UKind;
4544
4545protected:
4546 friend class ASTContext;
4547
4548 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4549 QualType CanonicalTy);
4550
4551public:
4552 bool isSugared() const { return !isDependentType(); }
4553 QualType desugar() const { return UnderlyingType; }
4554
4555 QualType getUnderlyingType() const { return UnderlyingType; }
4556 QualType getBaseType() const { return BaseType; }
4557
4558 UTTKind getUTTKind() const { return UKind; }
4559
4560 static bool classof(const Type *T) {
4561 return T->getTypeClass() == UnaryTransform;
4562 }
4563};
4564
4565/// Internal representation of canonical, dependent
4566/// __underlying_type(type) types.
4567///
4568/// This class is used internally by the ASTContext to manage
4569/// canonical, dependent types, only. Clients will only see instances
4570/// of this class via UnaryTransformType nodes.
4571class DependentUnaryTransformType : public UnaryTransformType,
4572 public llvm::FoldingSetNode {
4573public:
4574 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4575 UTTKind UKind);
4576
4577 void Profile(llvm::FoldingSetNodeID &ID) {
4578 Profile(ID, getBaseType(), getUTTKind());
4579 }
4580
4581 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4582 UTTKind UKind) {
4583 ID.AddPointer(BaseType.getAsOpaquePtr());
4584 ID.AddInteger((unsigned)UKind);
4585 }
4586};
4587
4588class TagType : public Type {
4589 friend class ASTReader;
4590 template <class T> friend class serialization::AbstractTypeReader;
4591
4592 /// Stores the TagDecl associated with this type. The decl may point to any
4593 /// TagDecl that declares the entity.
4594 TagDecl *decl;
4595
4596protected:
4597 TagType(TypeClass TC, const TagDecl *D, QualType can);
4598
4599public:
4600 TagDecl *getDecl() const;
4601
4602 /// Determines whether this type is in the process of being defined.
4603 bool isBeingDefined() const;
4604
4605 static bool classof(const Type *T) {
4606 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4607 }
4608};
4609
4610/// A helper class that allows the use of isa/cast/dyncast
4611/// to detect TagType objects of structs/unions/classes.
4612class RecordType : public TagType {
4613protected:
4614 friend class ASTContext; // ASTContext creates these.
4615
4616 explicit RecordType(const RecordDecl *D)
4617 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4618 explicit RecordType(TypeClass TC, RecordDecl *D)
4619 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4620
4621public:
4622 RecordDecl *getDecl() const {
4623 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4624 }
4625
4626 /// Recursively check all fields in the record for const-ness. If any field
4627 /// is declared const, return true. Otherwise, return false.
4628 bool hasConstFields() const;
4629
4630 bool isSugared() const { return false; }
4631 QualType desugar() const { return QualType(this, 0); }
4632
4633 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4634};
4635
4636/// A helper class that allows the use of isa/cast/dyncast
4637/// to detect TagType objects of enums.
4638class EnumType : public TagType {
4639 friend class ASTContext; // ASTContext creates these.
4640
4641 explicit EnumType(const EnumDecl *D)
4642 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4643
4644public:
4645 EnumDecl *getDecl() const {
4646 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4647 }
4648
4649 bool isSugared() const { return false; }
4650 QualType desugar() const { return QualType(this, 0); }
4651
4652 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4653};
4654
4655/// An attributed type is a type to which a type attribute has been applied.
4656///
4657/// The "modified type" is the fully-sugared type to which the attributed
4658/// type was applied; generally it is not canonically equivalent to the
4659/// attributed type. The "equivalent type" is the minimally-desugared type
4660/// which the type is canonically equivalent to.
4661///
4662/// For example, in the following attributed type:
4663/// int32_t __attribute__((vector_size(16)))
4664/// - the modified type is the TypedefType for int32_t
4665/// - the equivalent type is VectorType(16, int32_t)
4666/// - the canonical type is VectorType(16, int)
4667class AttributedType : public Type, public llvm::FoldingSetNode {
4668public:
4669 using Kind = attr::Kind;
4670
4671private:
4672 friend class ASTContext; // ASTContext creates these
4673
4674 QualType ModifiedType;
4675 QualType EquivalentType;
4676
4677 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4678 QualType equivalent)
4679 : Type(Attributed, canon, equivalent->getDependence()),
4680 ModifiedType(modified), EquivalentType(equivalent) {
4681 AttributedTypeBits.AttrKind = attrKind;
4682 }
4683
4684public:
4685 Kind getAttrKind() const {
4686 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4687 }
4688
4689 QualType getModifiedType() const { return ModifiedType; }
4690 QualType getEquivalentType() const { return EquivalentType; }
4691
4692 bool isSugared() const { return true; }
4693 QualType desugar() const { return getEquivalentType(); }
4694
4695 /// Does this attribute behave like a type qualifier?
4696 ///
4697 /// A type qualifier adjusts a type to provide specialized rules for
4698 /// a specific object, like the standard const and volatile qualifiers.
4699 /// This includes attributes controlling things like nullability,
4700 /// address spaces, and ARC ownership. The value of the object is still
4701 /// largely described by the modified type.
4702 ///
4703 /// In contrast, many type attributes "rewrite" their modified type to
4704 /// produce a fundamentally different type, not necessarily related in any
4705 /// formalizable way to the original type. For example, calling convention
4706 /// and vector attributes are not simple type qualifiers.
4707 ///
4708 /// Type qualifiers are often, but not always, reflected in the canonical
4709 /// type.
4710 bool isQualifier() const;
4711
4712 bool isMSTypeSpec() const;
4713
4714 bool isCallingConv() const;
4715
4716 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4717
4718 /// Retrieve the attribute kind corresponding to the given
4719 /// nullability kind.
4720 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4721 switch (kind) {
4722 case NullabilityKind::NonNull:
4723 return attr::TypeNonNull;
4724
4725 case NullabilityKind::Nullable:
4726 return attr::TypeNullable;
4727
4728 case NullabilityKind::NullableResult:
4729 return attr::TypeNullableResult;
4730
4731 case NullabilityKind::Unspecified:
4732 return attr::TypeNullUnspecified;
4733 }
4734 llvm_unreachable("Unknown nullability kind.")__builtin_unreachable();
4735 }
4736
4737 /// Strip off the top-level nullability annotation on the given
4738 /// type, if it's there.
4739 ///
4740 /// \param T The type to strip. If the type is exactly an
4741 /// AttributedType specifying nullability (without looking through
4742 /// type sugar), the nullability is returned and this type changed
4743 /// to the underlying modified type.
4744 ///
4745 /// \returns the top-level nullability, if present.
4746 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4747
4748 void Profile(llvm::FoldingSetNodeID &ID) {
4749 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4750 }
4751
4752 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4753 QualType modified, QualType equivalent) {
4754 ID.AddInteger(attrKind);
4755 ID.AddPointer(modified.getAsOpaquePtr());
4756 ID.AddPointer(equivalent.getAsOpaquePtr());
4757 }
4758
4759 static bool classof(const Type *T) {
4760 return T->getTypeClass() == Attributed;
4761 }
4762};
4763
4764class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4765 friend class ASTContext; // ASTContext creates these
4766
4767 // Helper data collector for canonical types.
4768 struct CanonicalTTPTInfo {
4769 unsigned Depth : 15;
4770 unsigned ParameterPack : 1;
4771 unsigned Index : 16;
4772 };
4773
4774 union {
4775 // Info for the canonical type.
4776 CanonicalTTPTInfo CanTTPTInfo;
4777
4778 // Info for the non-canonical type.
4779 TemplateTypeParmDecl *TTPDecl;
4780 };
4781
4782 /// Build a non-canonical type.
4783 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4784 : Type(TemplateTypeParm, Canon,
4785 TypeDependence::DependentInstantiation |
4786 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4787 TTPDecl(TTPDecl) {}
4788
4789 /// Build the canonical type.
4790 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4791 : Type(TemplateTypeParm, QualType(this, 0),
4792 TypeDependence::DependentInstantiation |
4793 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4794 CanTTPTInfo.Depth = D;
4795 CanTTPTInfo.Index = I;
4796 CanTTPTInfo.ParameterPack = PP;
4797 }
4798
4799 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4800 QualType Can = getCanonicalTypeInternal();
4801 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4802 }
4803
4804public:
4805 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4806 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4807 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4808
4809 TemplateTypeParmDecl *getDecl() const {
4810 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4811 }
4812
4813 IdentifierInfo *getIdentifier() const;
4814
4815 bool isSugared() const { return false; }
4816 QualType desugar() const { return QualType(this, 0); }
4817
4818 void Profile(llvm::FoldingSetNodeID &ID) {
4819 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4820 }
4821
4822 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4823 unsigned Index, bool ParameterPack,
4824 TemplateTypeParmDecl *TTPDecl) {
4825 ID.AddInteger(Depth);
4826 ID.AddInteger(Index);
4827 ID.AddBoolean(ParameterPack);
4828 ID.AddPointer(TTPDecl);
4829 }
4830
4831 static bool classof(const Type *T) {
4832 return T->getTypeClass() == TemplateTypeParm;
4833 }
4834};
4835
4836/// Represents the result of substituting a type for a template
4837/// type parameter.
4838///
4839/// Within an instantiated template, all template type parameters have
4840/// been replaced with these. They are used solely to record that a
4841/// type was originally written as a template type parameter;
4842/// therefore they are never canonical.
4843class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4844 friend class ASTContext;
4845
4846 // The original type parameter.
4847 const TemplateTypeParmType *Replaced;
4848
4849 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4850 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()),
4851 Replaced(Param) {}
4852
4853public:
4854 /// Gets the template parameter that was substituted for.
4855 const TemplateTypeParmType *getReplacedParameter() const {
4856 return Replaced;
4857 }
4858
4859 /// Gets the type that was substituted for the template
4860 /// parameter.
4861 QualType getReplacementType() const {
4862 return getCanonicalTypeInternal();
4863 }
4864
4865 bool isSugared() const { return true; }
4866 QualType desugar() const { return getReplacementType(); }
4867
4868 void Profile(llvm::FoldingSetNodeID &ID) {
4869 Profile(ID, getReplacedParameter(), getReplacementType());
4870 }
4871
4872 static void Profile(llvm::FoldingSetNodeID &ID,
4873 const TemplateTypeParmType *Replaced,
4874 QualType Replacement) {
4875 ID.AddPointer(Replaced);
4876 ID.AddPointer(Replacement.getAsOpaquePtr());
4877 }
4878
4879 static bool classof(const Type *T) {
4880 return T->getTypeClass() == SubstTemplateTypeParm;
4881 }
4882};
4883
4884/// Represents the result of substituting a set of types for a template
4885/// type parameter pack.
4886///
4887/// When a pack expansion in the source code contains multiple parameter packs
4888/// and those parameter packs correspond to different levels of template
4889/// parameter lists, this type node is used to represent a template type
4890/// parameter pack from an outer level, which has already had its argument pack
4891/// substituted but that still lives within a pack expansion that itself
4892/// could not be instantiated. When actually performing a substitution into
4893/// that pack expansion (e.g., when all template parameters have corresponding
4894/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4895/// at the current pack substitution index.
4896class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4897 friend class ASTContext;
4898
4899 /// The original type parameter.
4900 const TemplateTypeParmType *Replaced;
4901
4902 /// A pointer to the set of template arguments that this
4903 /// parameter pack is instantiated with.
4904 const TemplateArgument *Arguments;
4905
4906 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4907 QualType Canon,
4908 const TemplateArgument &ArgPack);
4909
4910public:
4911 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4912
4913 /// Gets the template parameter that was substituted for.
4914 const TemplateTypeParmType *getReplacedParameter() const {
4915 return Replaced;
4916 }
4917
4918 unsigned getNumArgs() const {
4919 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4920 }
4921
4922 bool isSugared() const { return false; }
4923 QualType desugar() const { return QualType(this, 0); }
4924
4925 TemplateArgument getArgumentPack() const;
4926
4927 void Profile(llvm::FoldingSetNodeID &ID);
4928 static void Profile(llvm::FoldingSetNodeID &ID,
4929 const TemplateTypeParmType *Replaced,
4930 const TemplateArgument &ArgPack);
4931
4932 static bool classof(const Type *T) {
4933 return T->getTypeClass() == SubstTemplateTypeParmPack;
4934 }
4935};
4936
4937/// Common base class for placeholders for types that get replaced by
4938/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4939/// class template types, and constrained type names.
4940///
4941/// These types are usually a placeholder for a deduced type. However, before
4942/// the initializer is attached, or (usually) if the initializer is
4943/// type-dependent, there is no deduced type and the type is canonical. In
4944/// the latter case, it is also a dependent type.
4945class DeducedType : public Type {
4946protected:
4947 DeducedType(TypeClass TC, QualType DeducedAsType,
4948 TypeDependence ExtraDependence)
4949 : Type(TC,
4950 // FIXME: Retain the sugared deduced type?
4951 DeducedAsType.isNull() ? QualType(this, 0)
4952 : DeducedAsType.getCanonicalType(),
4953 ExtraDependence | (DeducedAsType.isNull()
4954 ? TypeDependence::None
4955 : DeducedAsType->getDependence() &
4956 ~TypeDependence::VariablyModified)) {}
4957
4958public:
4959 bool isSugared() const { return !isCanonicalUnqualified(); }
4960 QualType desugar() const { return getCanonicalTypeInternal(); }
4961
4962 /// Get the type deduced for this placeholder type, or null if it's
4963 /// either not been deduced or was deduced to a dependent type.
4964 QualType getDeducedType() const {
4965 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4966 }
4967 bool isDeduced() const {
4968 return !isCanonicalUnqualified() || isDependentType();
4969 }
4970
4971 static bool classof(const Type *T) {
4972 return T->getTypeClass() == Auto ||
4973 T->getTypeClass() == DeducedTemplateSpecialization;
4974 }
4975};
4976
4977/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4978/// by a type-constraint.
4979class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4980 friend class ASTContext; // ASTContext creates these
4981
4982 ConceptDecl *TypeConstraintConcept;
4983
4984 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4985 TypeDependence ExtraDependence, ConceptDecl *CD,
4986 ArrayRef<TemplateArgument> TypeConstraintArgs);
4987
4988 const TemplateArgument *getArgBuffer() const {
4989 return reinterpret_cast<const TemplateArgument*>(this+1);
4990 }
4991
4992 TemplateArgument *getArgBuffer() {
4993 return reinterpret_cast<TemplateArgument*>(this+1);
4994 }
4995
4996public:
4997 /// Retrieve the template arguments.
4998 const TemplateArgument *getArgs() const {
4999 return getArgBuffer();
5000 }
5001
5002 /// Retrieve the number of template arguments.
5003 unsigned getNumArgs() const {
5004 return AutoTypeBits.NumArgs;
5005 }
5006
5007 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5008
5009 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
5010 return {getArgs(), getNumArgs()};
5011 }
5012
5013 ConceptDecl *getTypeConstraintConcept() const {
5014 return TypeConstraintConcept;
5015 }
5016
5017 bool isConstrained() const {
5018 return TypeConstraintConcept != nullptr;
5019 }
5020
5021 bool isDecltypeAuto() const {
5022 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5023 }
5024
5025 AutoTypeKeyword getKeyword() const {
5026 return (AutoTypeKeyword)AutoTypeBits.Keyword;
5027 }
5028
5029 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5030 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5031 getTypeConstraintConcept(), getTypeConstraintArguments());
5032 }
5033
5034 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5035 QualType Deduced, AutoTypeKeyword Keyword,
5036 bool IsDependent, ConceptDecl *CD,
5037 ArrayRef<TemplateArgument> Arguments);
5038
5039 static bool classof(const Type *T) {
5040 return T->getTypeClass() == Auto;
5041 }
5042};
5043
5044/// Represents a C++17 deduced template specialization type.
5045class DeducedTemplateSpecializationType : public DeducedType,
5046 public llvm::FoldingSetNode {
5047 friend class ASTContext; // ASTContext creates these
5048
5049 /// The name of the template whose arguments will be deduced.
5050 TemplateName Template;
5051
5052 DeducedTemplateSpecializationType(TemplateName Template,
5053 QualType DeducedAsType,
5054 bool IsDeducedAsDependent)
5055 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5056 toTypeDependence(Template.getDependence()) |
5057 (IsDeducedAsDependent
5058 ? TypeDependence::DependentInstantiation
5059 : TypeDependence::None)),
5060 Template(Template) {}
5061
5062public:
5063 /// Retrieve the name of the template that we are deducing.
5064 TemplateName getTemplateName() const { return Template;}
5065
5066 void Profile(llvm::FoldingSetNodeID &ID) {
5067 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5068 }
5069
5070 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5071 QualType Deduced, bool IsDependent) {
5072 Template.Profile(ID);
5073 ID.AddPointer(Deduced.getAsOpaquePtr());
5074 ID.AddBoolean(IsDependent);
5075 }
5076
5077 static bool classof(const Type *T) {
5078 return T->getTypeClass() == DeducedTemplateSpecialization;
5079 }
5080};
5081
5082/// Represents a type template specialization; the template
5083/// must be a class template, a type alias template, or a template
5084/// template parameter. A template which cannot be resolved to one of
5085/// these, e.g. because it is written with a dependent scope
5086/// specifier, is instead represented as a
5087/// @c DependentTemplateSpecializationType.
5088///
5089/// A non-dependent template specialization type is always "sugar",
5090/// typically for a \c RecordType. For example, a class template
5091/// specialization type of \c vector<int> will refer to a tag type for
5092/// the instantiation \c std::vector<int, std::allocator<int>>
5093///
5094/// Template specializations are dependent if either the template or
5095/// any of the template arguments are dependent, in which case the
5096/// type may also be canonical.
5097///
5098/// Instances of this type are allocated with a trailing array of
5099/// TemplateArguments, followed by a QualType representing the
5100/// non-canonical aliased type when the template is a type alias
5101/// template.
5102class alignas(8) TemplateSpecializationType
5103 : public Type,
5104 public llvm::FoldingSetNode {
5105 friend class ASTContext; // ASTContext creates these
5106
5107 /// The name of the template being specialized. This is
5108 /// either a TemplateName::Template (in which case it is a
5109 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5110 /// TypeAliasTemplateDecl*), a
5111 /// TemplateName::SubstTemplateTemplateParmPack, or a
5112 /// TemplateName::SubstTemplateTemplateParm (in which case the
5113 /// replacement must, recursively, be one of these).
5114 TemplateName Template;
5115
5116 TemplateSpecializationType(TemplateName T,
5117 ArrayRef<TemplateArgument> Args,
5118 QualType Canon,
5119 QualType Aliased);
5120
5121public:
5122 /// Determine whether any of the given template arguments are dependent.
5123 ///
5124 /// The converted arguments should be supplied when known; whether an
5125 /// argument is dependent can depend on the conversions performed on it
5126 /// (for example, a 'const int' passed as a template argument might be
5127 /// dependent if the parameter is a reference but non-dependent if the
5128 /// parameter is an int).
5129 ///
5130 /// Note that the \p Args parameter is unused: this is intentional, to remind
5131 /// the caller that they need to pass in the converted arguments, not the
5132 /// specified arguments.
5133 static bool
5134 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5135 ArrayRef<TemplateArgument> Converted);
5136 static bool
5137 anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5138 ArrayRef<TemplateArgument> Converted);
5139 static bool anyInstantiationDependentTemplateArguments(
5140 ArrayRef<TemplateArgumentLoc> Args);
5141
5142 /// True if this template specialization type matches a current
5143 /// instantiation in the context in which it is found.
5144 bool isCurrentInstantiation() const {
5145 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5146 }
5147
5148 /// Determine if this template specialization type is for a type alias
5149 /// template that has been substituted.
5150 ///
5151 /// Nearly every template specialization type whose template is an alias
5152 /// template will be substituted. However, this is not the case when
5153 /// the specialization contains a pack expansion but the template alias
5154 /// does not have a corresponding parameter pack, e.g.,
5155 ///
5156 /// \code
5157 /// template<typename T, typename U, typename V> struct S;
5158 /// template<typename T, typename U> using A = S<T, int, U>;
5159 /// template<typename... Ts> struct X {
5160 /// typedef A<Ts...> type; // not a type alias
5161 /// };
5162 /// \endcode
5163 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5164
5165 /// Get the aliased type, if this is a specialization of a type alias
5166 /// template.
5167 QualType getAliasedType() const {
5168 assert(isTypeAlias() && "not a type alias template specialization")(static_cast<void> (0));
5169 return *reinterpret_cast<const QualType*>(end());
5170 }
5171
5172 using iterator = const TemplateArgument *;
5173
5174 iterator begin() const { return getArgs(); }
5175 iterator end() const; // defined inline in TemplateBase.h
5176
5177 /// Retrieve the name of the template that we are specializing.
5178 TemplateName getTemplateName() const { return Template; }
5179
5180 /// Retrieve the template arguments.
5181 const TemplateArgument *getArgs() const {
5182 return reinterpret_cast<const TemplateArgument *>(this + 1);
5183 }
5184
5185 /// Retrieve the number of template arguments.
5186 unsigned getNumArgs() const {
5187 return TemplateSpecializationTypeBits.NumArgs;
5188 }
5189
5190 /// Retrieve a specific template argument as a type.
5191 /// \pre \c isArgType(Arg)
5192 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5193
5194 ArrayRef<TemplateArgument> template_arguments() const {
5195 return {getArgs(), getNumArgs()};
5196 }
5197
5198 bool isSugared() const {
5199 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5200 }
5201
5202 QualType desugar() const {
5203 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5204 }
5205
5206 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5207 Profile(ID, Template, template_arguments(), Ctx);
5208 if (isTypeAlias())
5209 getAliasedType().Profile(ID);
5210 }
5211
5212 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5213 ArrayRef<TemplateArgument> Args,
5214 const ASTContext &Context);
5215
5216 static bool classof(const Type *T) {
5217 return T->getTypeClass() == TemplateSpecialization;
5218 }
5219};
5220
5221/// Print a template argument list, including the '<' and '>'
5222/// enclosing the template arguments.
5223void printTemplateArgumentList(raw_ostream &OS,
5224 ArrayRef<TemplateArgument> Args,
5225 const PrintingPolicy &Policy,
5226 const TemplateParameterList *TPL = nullptr);
5227
5228void printTemplateArgumentList(raw_ostream &OS,
5229 ArrayRef<TemplateArgumentLoc> Args,
5230 const PrintingPolicy &Policy,
5231 const TemplateParameterList *TPL = nullptr);
5232
5233void printTemplateArgumentList(raw_ostream &OS,
5234 const TemplateArgumentListInfo &Args,
5235 const PrintingPolicy &Policy,
5236 const TemplateParameterList *TPL = nullptr);
5237
5238/// The injected class name of a C++ class template or class
5239/// template partial specialization. Used to record that a type was
5240/// spelled with a bare identifier rather than as a template-id; the
5241/// equivalent for non-templated classes is just RecordType.
5242///
5243/// Injected class name types are always dependent. Template
5244/// instantiation turns these into RecordTypes.
5245///
5246/// Injected class name types are always canonical. This works
5247/// because it is impossible to compare an injected class name type
5248/// with the corresponding non-injected template type, for the same
5249/// reason that it is impossible to directly compare template
5250/// parameters from different dependent contexts: injected class name
5251/// types can only occur within the scope of a particular templated
5252/// declaration, and within that scope every template specialization
5253/// will canonicalize to the injected class name (when appropriate
5254/// according to the rules of the language).
5255class InjectedClassNameType : public Type {
5256 friend class ASTContext; // ASTContext creates these.
5257 friend class ASTNodeImporter;
5258 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5259 // currently suitable for AST reading, too much
5260 // interdependencies.
5261 template <class T> friend class serialization::AbstractTypeReader;
5262
5263 CXXRecordDecl *Decl;
5264
5265 /// The template specialization which this type represents.
5266 /// For example, in
5267 /// template <class T> class A { ... };
5268 /// this is A<T>, whereas in
5269 /// template <class X, class Y> class A<B<X,Y> > { ... };
5270 /// this is A<B<X,Y> >.
5271 ///
5272 /// It is always unqualified, always a template specialization type,
5273 /// and always dependent.
5274 QualType InjectedType;
5275
5276 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5277 : Type(InjectedClassName, QualType(),
5278 TypeDependence::DependentInstantiation),
5279 Decl(D), InjectedType(TST) {
5280 assert(isa<TemplateSpecializationType>(TST))(static_cast<void> (0));
5281 assert(!TST.hasQualifiers())(static_cast<void> (0));
5282 assert(TST->isDependentType())(static_cast<void> (0));
5283 }
5284
5285public:
5286 QualType getInjectedSpecializationType() const { return InjectedType; }
5287
5288 const TemplateSpecializationType *getInjectedTST() const {
5289 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5290 }
5291
5292 TemplateName getTemplateName() const {
5293 return getInjectedTST()->getTemplateName();
5294 }
5295
5296 CXXRecordDecl *getDecl() const;
5297
5298 bool isSugared() const { return false; }
5299 QualType desugar() const { return QualType(this, 0); }
5300
5301 static bool classof(const Type *T) {
5302 return T->getTypeClass() == InjectedClassName;
5303 }
5304};
5305
5306/// The kind of a tag type.
5307enum TagTypeKind {
5308 /// The "struct" keyword.
5309 TTK_Struct,
5310
5311 /// The "__interface" keyword.
5312 TTK_Interface,
5313
5314 /// The "union" keyword.
5315 TTK_Union,
5316
5317 /// The "class" keyword.
5318 TTK_Class,
5319
5320 /// The "enum" keyword.
5321 TTK_Enum
5322};
5323
5324/// The elaboration keyword that precedes a qualified type name or
5325/// introduces an elaborated-type-specifier.
5326enum ElaboratedTypeKeyword {
5327 /// The "struct" keyword introduces the elaborated-type-specifier.
5328 ETK_Struct,
5329
5330 /// The "__interface" keyword introduces the elaborated-type-specifier.
5331 ETK_Interface,
5332
5333 /// The "union" keyword introduces the elaborated-type-specifier.
5334 ETK_Union,
5335
5336 /// The "class" keyword introduces the elaborated-type-specifier.
5337 ETK_Class,
5338
5339 /// The "enum" keyword introduces the elaborated-type-specifier.
5340 ETK_Enum,
5341
5342 /// The "typename" keyword precedes the qualified type name, e.g.,
5343 /// \c typename T::type.
5344 ETK_Typename,
5345
5346 /// No keyword precedes the qualified type name.
5347 ETK_None
5348};
5349
5350/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5351/// The keyword in stored in the free bits of the base class.
5352/// Also provides a few static helpers for converting and printing
5353/// elaborated type keyword and tag type kind enumerations.
5354class TypeWithKeyword : public Type {
5355protected:
5356 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5357 QualType Canonical, TypeDependence Dependence)
5358 : Type(tc, Canonical, Dependence) {
5359 TypeWithKeywordBits.Keyword = Keyword;
5360 }
5361
5362public:
5363 ElaboratedTypeKeyword getKeyword() const {
5364 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5365 }
5366
5367 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5368 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5369
5370 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5371 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5372 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5373
5374 /// Converts a TagTypeKind into an elaborated type keyword.
5375 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5376
5377 /// Converts an elaborated type keyword into a TagTypeKind.
5378 /// It is an error to provide an elaborated type keyword
5379 /// which *isn't* a tag kind here.
5380 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5381
5382 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5383
5384 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5385
5386 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5387 return getKeywordName(getKeywordForTagTypeKind(Kind));
5388 }
5389
5390 class CannotCastToThisType {};
5391 static CannotCastToThisType classof(const Type *);
5392};
5393
5394/// Represents a type that was referred to using an elaborated type
5395/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5396/// or both.
5397///
5398/// This type is used to keep track of a type name as written in the
5399/// source code, including tag keywords and any nested-name-specifiers.
5400/// The type itself is always "sugar", used to express what was written
5401/// in the source code but containing no additional semantic information.
5402class ElaboratedType final
5403 : public TypeWithKeyword,
5404 public llvm::FoldingSetNode,
5405 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5406 friend class ASTContext; // ASTContext creates these
5407 friend TrailingObjects;
5408
5409 /// The nested name specifier containing the qualifier.
5410 NestedNameSpecifier *NNS;
5411
5412 /// The type that this qualified name refers to.
5413 QualType NamedType;
5414
5415 /// The (re)declaration of this tag type owned by this occurrence is stored
5416 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5417 /// it, or obtain a null pointer if there is none.
5418
5419 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5420 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5421 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5422 // Any semantic dependence on the qualifier will have
5423 // been incorporated into NamedType. We still need to
5424 // track syntactic (instantiation / error / pack)
5425 // dependence on the qualifier.
5426 NamedType->getDependence() |
5427 (NNS ? toSyntacticDependence(
5428 toTypeDependence(NNS->getDependence()))
5429 : TypeDependence::None)),
5430 NNS(NNS), NamedType(NamedType) {
5431 ElaboratedTypeBits.HasOwnedTagDecl = false;
5432 if (OwnedTagDecl) {
5433 ElaboratedTypeBits.HasOwnedTagDecl = true;
5434 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5435 }
5436 assert(!(Keyword == ETK_None && NNS == nullptr) &&(static_cast<void> (0))
5437 "ElaboratedType cannot have elaborated type keyword "(static_cast<void> (0))
5438 "and name qualifier both null.")(static_cast<void> (0));
5439 }
5440
5441public:
5442 /// Retrieve the qualification on this type.
5443 NestedNameSpecifier *getQualifier() const { return NNS; }
5444
5445 /// Retrieve the type named by the qualified-id.
5446 QualType getNamedType() const { return NamedType; }
5447
5448 /// Remove a single level of sugar.
5449 QualType desugar() const { return getNamedType(); }
5450
5451 /// Returns whether this type directly provides sugar.
5452 bool isSugared() const { return true; }
5453
5454 /// Return the (re)declaration of this type owned by this occurrence of this
5455 /// type, or nullptr if there is none.
5456 TagDecl *getOwnedTagDecl() const {
5457 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5458 : nullptr;
5459 }
5460
5461 void Profile(llvm::FoldingSetNodeID &ID) {
5462 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5463 }
5464
5465 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5466 NestedNameSpecifier *NNS, QualType NamedType,
5467 TagDecl *OwnedTagDecl) {
5468 ID.AddInteger(Keyword);
5469 ID.AddPointer(NNS);
5470 NamedType.Profile(ID);
5471 ID.AddPointer(OwnedTagDecl);
5472 }
5473
5474 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5475};
5476
5477/// Represents a qualified type name for which the type name is
5478/// dependent.
5479///
5480/// DependentNameType represents a class of dependent types that involve a
5481/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5482/// name of a type. The DependentNameType may start with a "typename" (for a
5483/// typename-specifier), "class", "struct", "union", or "enum" (for a
5484/// dependent elaborated-type-specifier), or nothing (in contexts where we
5485/// know that we must be referring to a type, e.g., in a base class specifier).
5486/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5487/// mode, this type is used with non-dependent names to delay name lookup until
5488/// instantiation.
5489class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5490 friend class ASTContext; // ASTContext creates these
5491
5492 /// The nested name specifier containing the qualifier.
5493 NestedNameSpecifier *NNS;
5494
5495 /// The type that this typename specifier refers to.
5496 const IdentifierInfo *Name;
5497
5498 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5499 const IdentifierInfo *Name, QualType CanonType)
5500 : TypeWithKeyword(Keyword, DependentName, CanonType,
5501 TypeDependence::DependentInstantiation |
5502 toTypeDependence(NNS->getDependence())),
5503 NNS(NNS), Name(Name) {}
5504
5505public:
5506 /// Retrieve the qualification on this type.
5507 NestedNameSpecifier *getQualifier() const { return NNS; }
5508
5509 /// Retrieve the type named by the typename specifier as an identifier.
5510 ///
5511 /// This routine will return a non-NULL identifier pointer when the
5512 /// form of the original typename was terminated by an identifier,
5513 /// e.g., "typename T::type".
5514 const IdentifierInfo *getIdentifier() const {
5515 return Name;
5516 }
5517
5518 bool isSugared() const { return false; }
5519 QualType desugar() const { return QualType(this, 0); }
5520
5521 void Profile(llvm::FoldingSetNodeID &ID) {
5522 Profile(ID, getKeyword(), NNS, Name);
5523 }
5524
5525 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5526 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5527 ID.AddInteger(Keyword);
5528 ID.AddPointer(NNS);
5529 ID.AddPointer(Name);
5530 }
5531
5532 static bool classof(const Type *T) {
5533 return T->getTypeClass() == DependentName;
5534 }
5535};
5536
5537/// Represents a template specialization type whose template cannot be
5538/// resolved, e.g.
5539/// A<T>::template B<T>
5540class alignas(8) DependentTemplateSpecializationType
5541 : public TypeWithKeyword,
5542 public llvm::FoldingSetNode {
5543 friend class ASTContext; // ASTContext creates these
5544
5545 /// The nested name specifier containing the qualifier.
5546 NestedNameSpecifier *NNS;
5547
5548 /// The identifier of the template.
5549 const IdentifierInfo *Name;
5550
5551 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5552 NestedNameSpecifier *NNS,
5553 const IdentifierInfo *Name,
5554 ArrayRef<TemplateArgument> Args,
5555 QualType Canon);
5556
5557 const TemplateArgument *getArgBuffer() const {
5558 return reinterpret_cast<const TemplateArgument*>(this+1);
5559 }
5560
5561 TemplateArgument *getArgBuffer() {
5562 return reinterpret_cast<TemplateArgument*>(this+1);
5563 }
5564
5565public:
5566 NestedNameSpecifier *getQualifier() const { return NNS; }
5567 const IdentifierInfo *getIdentifier() const { return Name; }
5568
5569 /// Retrieve the template arguments.
5570 const TemplateArgument *getArgs() const {
5571 return getArgBuffer();
5572 }
5573
5574 /// Retrieve the number of template arguments.
5575 unsigned getNumArgs() const {
5576 return DependentTemplateSpecializationTypeBits.NumArgs;
5577 }
5578
5579 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5580
5581 ArrayRef<TemplateArgument> template_arguments() const {
5582 return {getArgs(), getNumArgs()};
5583 }
5584
5585 using iterator = const TemplateArgument *;
5586
5587 iterator begin() const { return getArgs(); }
5588 iterator end() const; // inline in TemplateBase.h
5589
5590 bool isSugared() const { return false; }
5591 QualType desugar() const { return QualType(this, 0); }
5592
5593 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5594 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5595 }
5596
5597 static void Profile(llvm::FoldingSetNodeID &ID,
5598 const ASTContext &Context,
5599 ElaboratedTypeKeyword Keyword,
5600 NestedNameSpecifier *Qualifier,
5601 const IdentifierInfo *Name,
5602 ArrayRef<TemplateArgument> Args);
5603
5604 static bool classof(const Type *T) {
5605 return T->getTypeClass() == DependentTemplateSpecialization;
5606 }
5607};
5608
5609/// Represents a pack expansion of types.
5610///
5611/// Pack expansions are part of C++11 variadic templates. A pack
5612/// expansion contains a pattern, which itself contains one or more
5613/// "unexpanded" parameter packs. When instantiated, a pack expansion
5614/// produces a series of types, each instantiated from the pattern of
5615/// the expansion, where the Ith instantiation of the pattern uses the
5616/// Ith arguments bound to each of the unexpanded parameter packs. The
5617/// pack expansion is considered to "expand" these unexpanded
5618/// parameter packs.
5619///
5620/// \code
5621/// template<typename ...Types> struct tuple;
5622///
5623/// template<typename ...Types>
5624/// struct tuple_of_references {
5625/// typedef tuple<Types&...> type;
5626/// };
5627/// \endcode
5628///
5629/// Here, the pack expansion \c Types&... is represented via a
5630/// PackExpansionType whose pattern is Types&.
5631class PackExpansionType : public Type, public llvm::FoldingSetNode {
5632 friend class ASTContext; // ASTContext creates these
5633
5634 /// The pattern of the pack expansion.
5635 QualType Pattern;
5636
5637 PackExpansionType(QualType Pattern, QualType Canon,
5638 Optional<unsigned> NumExpansions)
5639 : Type(PackExpansion, Canon,
5640 (Pattern->getDependence() | TypeDependence::Dependent |
5641 TypeDependence::Instantiation) &
5642 ~TypeDependence::UnexpandedPack),
5643 Pattern(Pattern) {
5644 PackExpansionTypeBits.NumExpansions =
5645 NumExpansions ? *NumExpansions + 1 : 0;
5646 }
5647
5648public:
5649 /// Retrieve the pattern of this pack expansion, which is the
5650 /// type that will be repeatedly instantiated when instantiating the
5651 /// pack expansion itself.
5652 QualType getPattern() const { return Pattern; }
5653
5654 /// Retrieve the number of expansions that this pack expansion will
5655 /// generate, if known.
5656 Optional<unsigned> getNumExpansions() const {
5657 if (PackExpansionTypeBits.NumExpansions)
5658 return PackExpansionTypeBits.NumExpansions - 1;
5659 return None;
5660 }
5661
5662 bool isSugared() const { return false; }
5663 QualType desugar() const { return QualType(this, 0); }
5664
5665 void Profile(llvm::FoldingSetNodeID &ID) {
5666 Profile(ID, getPattern(), getNumExpansions());
5667 }
5668
5669 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5670 Optional<unsigned> NumExpansions) {
5671 ID.AddPointer(Pattern.getAsOpaquePtr());
5672 ID.AddBoolean(NumExpansions.hasValue());
5673 if (NumExpansions)
5674 ID.AddInteger(*NumExpansions);
5675 }
5676
5677 static bool classof(const Type *T) {
5678 return T->getTypeClass() == PackExpansion;
5679 }
5680};
5681
5682/// This class wraps the list of protocol qualifiers. For types that can
5683/// take ObjC protocol qualifers, they can subclass this class.
5684template <class T>
5685class ObjCProtocolQualifiers {
5686protected:
5687 ObjCProtocolQualifiers() = default;
5688
5689 ObjCProtocolDecl * const *getProtocolStorage() const {
5690 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5691 }
5692
5693 ObjCProtocolDecl **getProtocolStorage() {
5694 return static_cast<T*>(this)->getProtocolStorageImpl();
5695 }
5696
5697 void setNumProtocols(unsigned N) {
5698 static_cast<T*>(this)->setNumProtocolsImpl(N);
5699 }
5700
5701 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5702 setNumProtocols(protocols.size());
5703 assert(getNumProtocols() == protocols.size() &&(static_cast<void> (0))
5704 "bitfield overflow in protocol count")(static_cast<void> (0));
5705 if (!protocols.empty())
5706 memcpy(getProtocolStorage(), protocols.data(),
5707 protocols.size() * sizeof(ObjCProtocolDecl*));
5708 }
5709
5710public:
5711 using qual_iterator = ObjCProtocolDecl * const *;
5712 using qual_range = llvm::iterator_range<qual_iterator>;
5713
5714 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5715 qual_iterator qual_begin() const { return getProtocolStorage(); }
5716 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5717
5718 bool qual_empty() const { return getNumProtocols() == 0; }
5719
5720 /// Return the number of qualifying protocols in this type, or 0 if
5721 /// there are none.
5722 unsigned getNumProtocols() const {
5723 return static_cast<const T*>(this)->getNumProtocolsImpl();
5724 }
5725
5726 /// Fetch a protocol by index.
5727 ObjCProtocolDecl *getProtocol(unsigned I) const {
5728 assert(I < getNumProtocols() && "Out-of-range protocol access")(static_cast<void> (0));
5729 return qual_begin()[I];
5730 }
5731
5732 /// Retrieve all of the protocol qualifiers.
5733 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5734 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5735 }
5736};
5737
5738/// Represents a type parameter type in Objective C. It can take
5739/// a list of protocols.
5740class ObjCTypeParamType : public Type,
5741 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5742 public llvm::FoldingSetNode {
5743 friend class ASTContext;
5744 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5745
5746 /// The number of protocols stored on this type.
5747 unsigned NumProtocols : 6;
5748
5749 ObjCTypeParamDecl *OTPDecl;
5750
5751 /// The protocols are stored after the ObjCTypeParamType node. In the
5752 /// canonical type, the list of protocols are sorted alphabetically
5753 /// and uniqued.
5754 ObjCProtocolDecl **getProtocolStorageImpl();
5755
5756 /// Return the number of qualifying protocols in this interface type,
5757 /// or 0 if there are none.
5758 unsigned getNumProtocolsImpl() const {
5759 return NumProtocols;
5760 }
5761
5762 void setNumProtocolsImpl(unsigned N) {
5763 NumProtocols = N;
5764 }
5765
5766 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5767 QualType can,
5768 ArrayRef<ObjCProtocolDecl *> protocols);
5769
5770public:
5771 bool isSugared() const { return true; }
5772 QualType desugar() const { return getCanonicalTypeInternal(); }
5773
5774 static bool classof(const Type *T) {
5775 return T->getTypeClass() == ObjCTypeParam;
5776 }
5777
5778 void Profile(llvm::FoldingSetNodeID &ID);
5779 static void Profile(llvm::FoldingSetNodeID &ID,
5780 const ObjCTypeParamDecl *OTPDecl,
5781 QualType CanonicalType,
5782 ArrayRef<ObjCProtocolDecl *> protocols);
5783
5784 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5785};
5786
5787/// Represents a class type in Objective C.
5788///
5789/// Every Objective C type is a combination of a base type, a set of
5790/// type arguments (optional, for parameterized classes) and a list of
5791/// protocols.
5792///
5793/// Given the following declarations:
5794/// \code
5795/// \@class C<T>;
5796/// \@protocol P;
5797/// \endcode
5798///
5799/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5800/// with base C and no protocols.
5801///
5802/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5803/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5804/// protocol list.
5805/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5806/// and protocol list [P].
5807///
5808/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5809/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5810/// and no protocols.
5811///
5812/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5813/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5814/// this should get its own sugar class to better represent the source.
5815class ObjCObjectType : public Type,
5816 public ObjCProtocolQualifiers<ObjCObjectType> {
5817 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5818
5819 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5820 // after the ObjCObjectPointerType node.
5821 // ObjCObjectType.NumProtocols - the number of protocols stored
5822 // after the type arguments of ObjCObjectPointerType node.
5823 //
5824 // These protocols are those written directly on the type. If
5825 // protocol qualifiers ever become additive, the iterators will need
5826 // to get kindof complicated.
5827 //
5828 // In the canonical object type, these are sorted alphabetically
5829 // and uniqued.
5830
5831 /// Either a BuiltinType or an InterfaceType or sugar for either.
5832 QualType BaseType;
5833
5834 /// Cached superclass type.
5835 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5836 CachedSuperClassType;
5837
5838 QualType *getTypeArgStorage();
5839 const QualType *getTypeArgStorage() const {
5840 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5841 }
5842
5843 ObjCProtocolDecl **getProtocolStorageImpl();
5844 /// Return the number of qualifying protocols in this interface type,
5845 /// or 0 if there are none.
5846 unsigned getNumProtocolsImpl() const {
5847 return ObjCObjectTypeBits.NumProtocols;
5848 }
5849 void setNumProtocolsImpl(unsigned N) {
5850 ObjCObjectTypeBits.NumProtocols = N;
5851 }
5852
5853protected:
5854 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5855
5856 ObjCObjectType(QualType Canonical, QualType Base,
5857 ArrayRef<QualType> typeArgs,
5858 ArrayRef<ObjCProtocolDecl *> protocols,
5859 bool isKindOf);
5860
5861 ObjCObjectType(enum Nonce_ObjCInterface)
5862 : Type(ObjCInterface, QualType(), TypeDependence::None),
5863 BaseType(QualType(this_(), 0)) {
5864 ObjCObjectTypeBits.NumProtocols = 0;
5865 ObjCObjectTypeBits.NumTypeArgs = 0;
5866 ObjCObjectTypeBits.IsKindOf = 0;
5867 }
5868
5869 void computeSuperClassTypeSlow() const;
5870
5871public:
5872 /// Gets the base type of this object type. This is always (possibly
5873 /// sugar for) one of:
5874 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5875 /// user, which is a typedef for an ObjCObjectPointerType)
5876 /// - the 'Class' builtin type (same caveat)
5877 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5878 QualType getBaseType() const { return BaseType; }
5879
5880 bool isObjCId() const {
5881 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5882 }
5883
5884 bool isObjCClass() const {
5885 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5886 }
5887
5888 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5889 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5890 bool isObjCUnqualifiedIdOrClass() const {
5891 if (!qual_empty()) return false;
5892 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5893 return T->getKind() == BuiltinType::ObjCId ||
5894 T->getKind() == BuiltinType::ObjCClass;
5895 return false;
5896 }
5897 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5898 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5899
5900 /// Gets the interface declaration for this object type, if the base type
5901 /// really is an interface.
5902 ObjCInterfaceDecl *getInterface() const;
5903
5904 /// Determine whether this object type is "specialized", meaning
5905 /// that it has type arguments.
5906 bool isSpecialized() const;
5907
5908 /// Determine whether this object type was written with type arguments.
5909 bool isSpecializedAsWritten() const {
5910 return ObjCObjectTypeBits.NumTypeArgs > 0;
5911 }
5912
5913 /// Determine whether this object type is "unspecialized", meaning
5914 /// that it has no type arguments.
5915 bool isUnspecialized() const { return !isSpecialized(); }
5916
5917 /// Determine whether this object type is "unspecialized" as
5918 /// written, meaning that it has no type arguments.
5919 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5920
5921 /// Retrieve the type arguments of this object type (semantically).
5922 ArrayRef<QualType> getTypeArgs() const;
5923
5924 /// Retrieve the type arguments of this object type as they were
5925 /// written.
5926 ArrayRef<QualType> getTypeArgsAsWritten() const {
5927 return llvm::makeArrayRef(getTypeArgStorage(),
5928 ObjCObjectTypeBits.NumTypeArgs);
5929 }
5930
5931 /// Whether this is a "__kindof" type as written.
5932 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5933
5934 /// Whether this ia a "__kindof" type (semantically).
5935 bool isKindOfType() const;
5936
5937 /// Retrieve the type of the superclass of this object type.
5938 ///
5939 /// This operation substitutes any type arguments into the
5940 /// superclass of the current class type, potentially producing a
5941 /// specialization of the superclass type. Produces a null type if
5942 /// there is no superclass.
5943 QualType getSuperClassType() const {
5944 if (!CachedSuperClassType.getInt())
5945 computeSuperClassTypeSlow();
5946
5947 assert(CachedSuperClassType.getInt() && "Superclass not set?")(static_cast<void> (0));
5948 return QualType(CachedSuperClassType.getPointer(), 0);
5949 }
5950
5951 /// Strip off the Objective-C "kindof" type and (with it) any
5952 /// protocol qualifiers.
5953 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5954
5955 bool isSugared() const { return false; }
5956 QualType desugar() const { return QualType(this, 0); }
5957
5958 static bool classof(const Type *T) {
5959 return T->getTypeClass() == ObjCObject ||
5960 T->getTypeClass() == ObjCInterface;
5961 }
5962};
5963
5964/// A class providing a concrete implementation
5965/// of ObjCObjectType, so as to not increase the footprint of
5966/// ObjCInterfaceType. Code outside of ASTContext and the core type
5967/// system should not reference this type.
5968class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5969 friend class ASTContext;
5970
5971 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5972 // will need to be modified.
5973
5974 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5975 ArrayRef<QualType> typeArgs,
5976 ArrayRef<ObjCProtocolDecl *> protocols,
5977 bool isKindOf)
5978 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5979
5980public:
5981 void Profile(llvm::FoldingSetNodeID &ID);
5982 static void Profile(llvm::FoldingSetNodeID &ID,
5983 QualType Base,
5984 ArrayRef<QualType> typeArgs,
5985 ArrayRef<ObjCProtocolDecl *> protocols,
5986 bool isKindOf);
5987};
5988
5989inline QualType *ObjCObjectType::getTypeArgStorage() {
5990 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5991}
5992
5993inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5994 return reinterpret_cast<ObjCProtocolDecl**>(
5995 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5996}
5997
5998inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5999 return reinterpret_cast<ObjCProtocolDecl**>(
6000 static_cast<ObjCTypeParamType*>(this)+1);
6001}
6002
6003/// Interfaces are the core concept in Objective-C for object oriented design.
6004/// They basically correspond to C++ classes. There are two kinds of interface
6005/// types: normal interfaces like `NSString`, and qualified interfaces, which
6006/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
6007///
6008/// ObjCInterfaceType guarantees the following properties when considered
6009/// as a subtype of its superclass, ObjCObjectType:
6010/// - There are no protocol qualifiers. To reinforce this, code which
6011/// tries to invoke the protocol methods via an ObjCInterfaceType will
6012/// fail to compile.
6013/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
6014/// T->getBaseType() == QualType(T, 0).
6015class ObjCInterfaceType : public ObjCObjectType {
6016 friend class ASTContext; // ASTContext creates these.
6017 friend class ASTReader;
6018 friend class ObjCInterfaceDecl;
6019 template <class T> friend class serialization::AbstractTypeReader;
6020
6021 mutable ObjCInterfaceDecl *Decl;
6022
6023 ObjCInterfaceType(const ObjCInterfaceDecl *D)
6024 : ObjCObjectType(Nonce_ObjCInterface),
6025 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
6026
6027public:
6028 /// Get the declaration of this interface.
6029 ObjCInterfaceDecl *getDecl() const { return Decl; }
6030
6031 bool isSugared() const { return false; }
6032 QualType desugar() const { return QualType(this, 0); }
6033
6034 static bool classof(const Type *T) {
6035 return T->getTypeClass() == ObjCInterface;
6036 }
6037
6038 // Nonsense to "hide" certain members of ObjCObjectType within this
6039 // class. People asking for protocols on an ObjCInterfaceType are
6040 // not going to get what they want: ObjCInterfaceTypes are
6041 // guaranteed to have no protocols.
6042 enum {
6043 qual_iterator,
6044 qual_begin,
6045 qual_end,
6046 getNumProtocols,
6047 getProtocol
6048 };
6049};
6050
6051inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
6052 QualType baseType = getBaseType();
6053 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
6054 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
6055 return T->getDecl();
6056
6057 baseType = ObjT->getBaseType();
6058 }
6059
6060 return nullptr;
6061}
6062
6063/// Represents a pointer to an Objective C object.
6064///
6065/// These are constructed from pointer declarators when the pointee type is
6066/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
6067/// types are typedefs for these, and the protocol-qualified types 'id<P>'
6068/// and 'Class<P>' are translated into these.
6069///
6070/// Pointers to pointers to Objective C objects are still PointerTypes;
6071/// only the first level of pointer gets it own type implementation.
6072class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
6073 friend class ASTContext; // ASTContext creates these.
6074
6075 QualType PointeeType;
6076
6077 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
6078 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()),
6079 PointeeType(Pointee) {}
6080
6081public:
6082 /// Gets the type pointed to by this ObjC pointer.
6083 /// The result will always be an ObjCObjectType or sugar thereof.
6084 QualType getPointeeType() const { return PointeeType; }
6085
6086 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
6087 ///
6088 /// This method is equivalent to getPointeeType() except that
6089 /// it discards any typedefs (or other sugar) between this
6090 /// type and the "outermost" object type. So for:
6091 /// \code
6092 /// \@class A; \@protocol P; \@protocol Q;
6093 /// typedef A<P> AP;
6094 /// typedef A A1;
6095 /// typedef A1<P> A1P;
6096 /// typedef A1P<Q> A1PQ;
6097 /// \endcode
6098 /// For 'A*', getObjectType() will return 'A'.
6099 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6100 /// For 'AP*', getObjectType() will return 'A<P>'.
6101 /// For 'A1*', getObjectType() will return 'A'.
6102 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6103 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6104 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6105 /// adding protocols to a protocol-qualified base discards the
6106 /// old qualifiers (for now). But if it didn't, getObjectType()
6107 /// would return 'A1P<Q>' (and we'd have to make iterating over
6108 /// qualifiers more complicated).
6109 const ObjCObjectType *getObjectType() const {
6110 return PointeeType->castAs<ObjCObjectType>();
6111 }
6112
6113 /// If this pointer points to an Objective C
6114 /// \@interface type, gets the type for that interface. Any protocol
6115 /// qualifiers on the interface are ignored.
6116 ///
6117 /// \return null if the base type for this pointer is 'id' or 'Class'
6118 const ObjCInterfaceType *getInterfaceType() const;
6119
6120 /// If this pointer points to an Objective \@interface
6121 /// type, gets the declaration for that interface.
6122 ///
6123 /// \return null if the base type for this pointer is 'id' or 'Class'
6124 ObjCInterfaceDecl *getInterfaceDecl() const {
6125 return getObjectType()->getInterface();
6126 }
6127
6128 /// True if this is equivalent to the 'id' type, i.e. if
6129 /// its object type is the primitive 'id' type with no protocols.
6130 bool isObjCIdType() const {
6131 return getObjectType()->isObjCUnqualifiedId();
6132 }
6133
6134 /// True if this is equivalent to the 'Class' type,
6135 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6136 bool isObjCClassType() const {
6137 return getObjectType()->isObjCUnqualifiedClass();
6138 }
6139
6140 /// True if this is equivalent to the 'id' or 'Class' type,
6141 bool isObjCIdOrClassType() const {
6142 return getObjectType()->isObjCUnqualifiedIdOrClass();
6143 }
6144
6145 /// True if this is equivalent to 'id<P>' for some non-empty set of
6146 /// protocols.
6147 bool isObjCQualifiedIdType() const {
6148 return getObjectType()->isObjCQualifiedId();
6149 }
6150
6151 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6152 /// protocols.
6153 bool isObjCQualifiedClassType() const {
6154 return getObjectType()->isObjCQualifiedClass();
6155 }
6156
6157 /// Whether this is a "__kindof" type.
6158 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6159
6160 /// Whether this type is specialized, meaning that it has type arguments.
6161 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6162
6163 /// Whether this type is specialized, meaning that it has type arguments.
6164 bool isSpecializedAsWritten() const {
6165 return getObjectType()->isSpecializedAsWritten();
6166 }
6167
6168 /// Whether this type is unspecialized, meaning that is has no type arguments.
6169 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6170
6171 /// Determine whether this object type is "unspecialized" as
6172 /// written, meaning that it has no type arguments.
6173 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6174
6175 /// Retrieve the type arguments for this type.
6176 ArrayRef<QualType> getTypeArgs() const {
6177 return getObjectType()->getTypeArgs();
6178 }
6179
6180 /// Retrieve the type arguments for this type.
6181 ArrayRef<QualType> getTypeArgsAsWritten() const {
6182 return getObjectType()->getTypeArgsAsWritten();
6183 }
6184
6185 /// An iterator over the qualifiers on the object type. Provided
6186 /// for convenience. This will always iterate over the full set of
6187 /// protocols on a type, not just those provided directly.
6188 using qual_iterator = ObjCObjectType::qual_iterator;
6189 using qual_range = llvm::iterator_range<qual_iterator>;
6190
6191 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6192
6193 qual_iterator qual_begin() const {
6194 return getObjectType()->qual_begin();
6195 }
6196
6197 qual_iterator qual_end() const {
6198 return getObjectType()->qual_end();
6199 }
6200
6201 bool qual_empty() const { return getObjectType()->qual_empty(); }
6202
6203 /// Return the number of qualifying protocols on the object type.
6204 unsigned getNumProtocols() const {
6205 return getObjectType()->getNumProtocols();
6206 }
6207
6208 /// Retrieve a qualifying protocol by index on the object type.
6209 ObjCProtocolDecl *getProtocol(unsigned I) const {
6210 return getObjectType()->getProtocol(I);
6211 }
6212
6213 bool isSugared() const { return false; }
6214 QualType desugar() const { return QualType(this, 0); }
6215
6216 /// Retrieve the type of the superclass of this object pointer type.
6217 ///
6218 /// This operation substitutes any type arguments into the
6219 /// superclass of the current class type, potentially producing a
6220 /// pointer to a specialization of the superclass type. Produces a
6221 /// null type if there is no superclass.
6222 QualType getSuperClassType() const;
6223
6224 /// Strip off the Objective-C "kindof" type and (with it) any
6225 /// protocol qualifiers.
6226 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6227 const ASTContext &ctx) const;
6228
6229 void Profile(llvm::FoldingSetNodeID &ID) {
6230 Profile(ID, getPointeeType());
6231 }
6232
6233 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6234 ID.AddPointer(T.getAsOpaquePtr());
6235 }
6236
6237 static bool classof(const Type *T) {
6238 return T->getTypeClass() == ObjCObjectPointer;
6239 }
6240};
6241
6242class AtomicType : public Type, public llvm::FoldingSetNode {
6243 friend class ASTContext; // ASTContext creates these.
6244
6245 QualType ValueType;
6246
6247 AtomicType(QualType ValTy, QualType Canonical)
6248 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {}
6249
6250public:
6251 /// Gets the type contained by this atomic type, i.e.
6252 /// the type returned by performing an atomic load of this atomic type.
6253 QualType getValueType() const { return ValueType; }
6254
6255 bool isSugared() const { return false; }
6256 QualType desugar() const { return QualType(this, 0); }
6257
6258 void Profile(llvm::FoldingSetNodeID &ID) {
6259 Profile(ID, getValueType());
6260 }
6261
6262 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6263 ID.AddPointer(T.getAsOpaquePtr());
6264 }
6265
6266 static bool classof(const Type *T) {
6267 return T->getTypeClass() == Atomic;
6268 }
6269};
6270
6271/// PipeType - OpenCL20.
6272class PipeType : public Type, public llvm::FoldingSetNode {
6273 friend class ASTContext; // ASTContext creates these.
6274
6275 QualType ElementType;
6276 bool isRead;
6277
6278 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6279 : Type(Pipe, CanonicalPtr, elemType->getDependence()),
6280 ElementType(elemType), isRead(isRead) {}
6281
6282public:
6283 QualType getElementType() const { return ElementType; }
6284
6285 bool isSugared() const { return false; }
6286
6287 QualType desugar() const { return QualType(this, 0); }
6288
6289 void Profile(llvm::FoldingSetNodeID &ID) {
6290 Profile(ID, getElementType(), isReadOnly());
6291 }
6292
6293 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6294 ID.AddPointer(T.getAsOpaquePtr());
6295 ID.AddBoolean(isRead);
6296 }
6297
6298 static bool classof(const Type *T) {
6299 return T->getTypeClass() == Pipe;
6300 }
6301
6302 bool isReadOnly() const { return isRead; }
6303};
6304
6305/// A fixed int type of a specified bitwidth.
6306class ExtIntType final : public Type, public llvm::FoldingSetNode {
6307 friend class ASTContext;
6308 unsigned IsUnsigned : 1;
6309 unsigned NumBits : 24;
6310
6311protected:
6312 ExtIntType(bool isUnsigned, unsigned NumBits);
6313
6314public:
6315 bool isUnsigned() const { return IsUnsigned; }
6316 bool isSigned() const { return !IsUnsigned; }
6317 unsigned getNumBits() const { return NumBits; }
6318
6319 bool isSugared() const { return false; }
6320 QualType desugar() const { return QualType(this, 0); }
6321
6322 void Profile(llvm::FoldingSetNodeID &ID) {
6323 Profile(ID, isUnsigned(), getNumBits());
6324 }
6325
6326 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned,
6327 unsigned NumBits) {
6328 ID.AddBoolean(IsUnsigned);
6329 ID.AddInteger(NumBits);
6330 }
6331
6332 static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; }
6333};
6334
6335class DependentExtIntType final : public Type, public llvm::FoldingSetNode {
6336 friend class ASTContext;
6337 const ASTContext &Context;
6338 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned;
6339
6340protected:
6341 DependentExtIntType(const ASTContext &Context, bool IsUnsigned,
6342 Expr *NumBits);
6343
6344public:
6345 bool isUnsigned() const;
6346 bool isSigned() const { return !isUnsigned(); }
6347 Expr *getNumBitsExpr() const;
6348
6349 bool isSugared() const { return false; }
6350 QualType desugar() const { return QualType(this, 0); }
6351
6352 void Profile(llvm::FoldingSetNodeID &ID) {
6353 Profile(ID, Context, isUnsigned(), getNumBitsExpr());
6354 }
6355 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
6356 bool IsUnsigned, Expr *NumBitsExpr);
6357
6358 static bool classof(const Type *T) {
6359 return T->getTypeClass() == DependentExtInt;
6360 }
6361};
6362
6363/// A qualifier set is used to build a set of qualifiers.
6364class QualifierCollector : public Qualifiers {
6365public:
6366 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6367
6368 /// Collect any qualifiers on the given type and return an
6369 /// unqualified type. The qualifiers are assumed to be consistent
6370 /// with those already in the type.
6371 const Type *strip(QualType type) {
6372 addFastQualifiers(type.getLocalFastQualifiers());
6373 if (!type.hasLocalNonFastQualifiers())
6374 return type.getTypePtrUnsafe();
6375
6376 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6377 addConsistentQualifiers(extQuals->getQualifiers());
6378 return extQuals->getBaseType();
6379 }
6380
6381 /// Apply the collected qualifiers to the given type.
6382 QualType apply(const ASTContext &Context, QualType QT) const;
6383
6384 /// Apply the collected qualifiers to the given type.
6385 QualType apply(const ASTContext &Context, const Type* T) const;
6386};
6387
6388/// A container of type source information.
6389///
6390/// A client can read the relevant info using TypeLoc wrappers, e.g:
6391/// @code
6392/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6393/// TL.getBeginLoc().print(OS, SrcMgr);
6394/// @endcode
6395class alignas(8) TypeSourceInfo {
6396 // Contains a memory block after the class, used for type source information,
6397 // allocated by ASTContext.
6398 friend class ASTContext;
6399
6400 QualType Ty;
6401
6402 TypeSourceInfo(QualType ty) : Ty(ty) {}
6403
6404public:
6405 /// Return the type wrapped by this type source info.
6406 QualType getType() const { return Ty; }
6407
6408 /// Return the TypeLoc wrapper for the type source info.
6409 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6410
6411 /// Override the type stored in this TypeSourceInfo. Use with caution!
6412 void overrideType(QualType T) { Ty = T; }
6413};
6414
6415// Inline function definitions.
6416
6417inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6418 SplitQualType desugar =
6419 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6420 desugar.Quals.addConsistentQualifiers(Quals);
6421 return desugar;
6422}
6423
6424inline const Type *QualType::getTypePtr() const {
6425 return getCommonPtr()->BaseType;
6426}
6427
6428inline const Type *QualType::getTypePtrOrNull() const {
6429 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6430}
6431
6432inline SplitQualType QualType::split() const {
6433 if (!hasLocalNonFastQualifiers())
6434 return SplitQualType(getTypePtrUnsafe(),
6435 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6436
6437 const ExtQuals *eq = getExtQualsUnsafe();
6438 Qualifiers qs = eq->getQualifiers();
6439 qs.addFastQualifiers(getLocalFastQualifiers());
6440 return SplitQualType(eq->getBaseType(), qs);
6441}
6442
6443inline Qualifiers QualType::getLocalQualifiers() const {
6444 Qualifiers Quals;
6445 if (hasLocalNonFastQualifiers())
6446 Quals = getExtQualsUnsafe()->getQualifiers();
6447 Quals.addFastQualifiers(getLocalFastQualifiers());
6448 return Quals;
6449}
6450
6451inline Qualifiers QualType::getQualifiers() const {
6452 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6453 quals.addFastQualifiers(getLocalFastQualifiers());
6454 return quals;
6455}
6456
6457inline unsigned QualType::getCVRQualifiers() const {
6458 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6459 cvr |= getLocalCVRQualifiers();
6460 return cvr;
6461}
6462
6463inline QualType QualType::getCanonicalType() const {
6464 QualType canon = getCommonPtr()->CanonicalType;
6465 return canon.withFastQualifiers(getLocalFastQualifiers());
6466}
6467
6468inline bool QualType::isCanonical() const {
6469 return getTypePtr()->isCanonicalUnqualified();
6470}
6471
6472inline bool QualType::isCanonicalAsParam() const {
6473 if (!isCanonical()) return false;
6474 if (hasLocalQualifiers()) return false;
6475
6476 const Type *T = getTypePtr();
6477 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6478 return false;
6479
6480 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6481}
6482
6483inline bool QualType::isConstQualified() const {
6484 return isLocalConstQualified() ||
6485 getCommonPtr()->CanonicalType.isLocalConstQualified();
6486}
6487
6488inline bool QualType::isRestrictQualified() const {
6489 return isLocalRestrictQualified() ||
6490 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6491}
6492
6493
6494inline bool QualType::isVolatileQualified() const {
6495 return isLocalVolatileQualified() ||
6496 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6497}
6498
6499inline bool QualType::hasQualifiers() const {
6500 return hasLocalQualifiers() ||
6501 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6502}
6503
6504inline QualType QualType::getUnqualifiedType() const {
6505 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6506 return QualType(getTypePtr(), 0);
6507
6508 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6509}
6510
6511inline SplitQualType QualType::getSplitUnqualifiedType() const {
6512 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6513 return split();
6514
6515 return getSplitUnqualifiedTypeImpl(*this);
6516}
6517
6518inline void QualType::removeLocalConst() {
6519 removeLocalFastQualifiers(Qualifiers::Const);
6520}
6521
6522inline void QualType::removeLocalRestrict() {
6523 removeLocalFastQualifiers(Qualifiers::Restrict);
6524}
6525
6526inline void QualType::removeLocalVolatile() {
6527 removeLocalFastQualifiers(Qualifiers::Volatile);
6528}
6529
6530inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6531 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")(static_cast<void> (0));
6532 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6533 "Fast bits differ from CVR bits!");
6534
6535 // Fast path: we don't need to touch the slow qualifiers.
6536 removeLocalFastQualifiers(Mask);
6537}
6538
6539/// Check if this type has any address space qualifier.
6540inline bool QualType::hasAddressSpace() const {
6541 return getQualifiers().hasAddressSpace();
6542}
6543
6544/// Return the address space of this type.
6545inline LangAS QualType::getAddressSpace() const {
6546 return getQualifiers().getAddressSpace();
6547}
6548
6549/// Return the gc attribute of this type.
6550inline Qualifiers::GC QualType::getObjCGCAttr() const {
6551 return getQualifiers().getObjCGCAttr();
6552}
6553
6554inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6555 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6556 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6557 return false;
6558}
6559
6560inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6561 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6562 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6563 return false;
6564}
6565
6566inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6567 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6568 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6569 return false;
6570}
6571
6572inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6573 if (const auto *PT = t.getAs<PointerType>()) {
6574 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6575 return FT->getExtInfo();
6576 } else if (const auto *FT = t.getAs<FunctionType>())
6577 return FT->getExtInfo();
6578
6579 return FunctionType::ExtInfo();
6580}
6581
6582inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6583 return getFunctionExtInfo(*t);
6584}
6585
6586/// Determine whether this type is more
6587/// qualified than the Other type. For example, "const volatile int"
6588/// is more qualified than "const int", "volatile int", and
6589/// "int". However, it is not more qualified than "const volatile
6590/// int".
6591inline bool QualType::isMoreQualifiedThan(QualType other) const {
6592 Qualifiers MyQuals = getQualifiers();
6593 Qualifiers OtherQuals = other.getQualifiers();
6594 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6595}
6596
6597/// Determine whether this type is at last
6598/// as qualified as the Other type. For example, "const volatile
6599/// int" is at least as qualified as "const int", "volatile int",
6600/// "int", and "const volatile int".
6601inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6602 Qualifiers OtherQuals = other.getQualifiers();
6603
6604 // Ignore __unaligned qualifier if this type is a void.
6605 if (getUnqualifiedType()->isVoidType())
6606 OtherQuals.removeUnaligned();
6607
6608 return getQualifiers().compatiblyIncludes(OtherQuals);
6609}
6610
6611/// If Type is a reference type (e.g., const
6612/// int&), returns the type that the reference refers to ("const
6613/// int"). Otherwise, returns the type itself. This routine is used
6614/// throughout Sema to implement C++ 5p6:
6615///
6616/// If an expression initially has the type "reference to T" (8.3.2,
6617/// 8.5.3), the type is adjusted to "T" prior to any further
6618/// analysis, the expression designates the object or function
6619/// denoted by the reference, and the expression is an lvalue.
6620inline QualType QualType::getNonReferenceType() const {
6621 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6622 return RefType->getPointeeType();
6623 else
6624 return *this;
6625}
6626
6627inline bool QualType::isCForbiddenLValueType() const {
6628 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6629 getTypePtr()->isFunctionType());
6630}
6631
6632/// Tests whether the type is categorized as a fundamental type.
6633///
6634/// \returns True for types specified in C++0x [basic.fundamental].
6635inline bool Type::isFundamentalType() const {
6636 return isVoidType() ||
6637 isNullPtrType() ||
6638 // FIXME: It's really annoying that we don't have an
6639 // 'isArithmeticType()' which agrees with the standard definition.
6640 (isArithmeticType() && !isEnumeralType());
6641}
6642
6643/// Tests whether the type is categorized as a compound type.
6644///
6645/// \returns True for types specified in C++0x [basic.compound].
6646inline bool Type::isCompoundType() const {
6647 // C++0x [basic.compound]p1:
6648 // Compound types can be constructed in the following ways:
6649 // -- arrays of objects of a given type [...];
6650 return isArrayType() ||
6651 // -- functions, which have parameters of given types [...];
6652 isFunctionType() ||
6653 // -- pointers to void or objects or functions [...];
6654 isPointerType() ||
6655 // -- references to objects or functions of a given type. [...]
6656 isReferenceType() ||
6657 // -- classes containing a sequence of objects of various types, [...];
6658 isRecordType() ||
6659 // -- unions, which are classes capable of containing objects of different
6660 // types at different times;
6661 isUnionType() ||
6662 // -- enumerations, which comprise a set of named constant values. [...];
6663 isEnumeralType() ||
6664 // -- pointers to non-static class members, [...].
6665 isMemberPointerType();
6666}
6667
6668inline bool Type::isFunctionType() const {
6669 return isa<FunctionType>(CanonicalType);
6670}
6671
6672inline bool Type::isPointerType() const {
6673 return isa<PointerType>(CanonicalType);
6674}
6675
6676inline bool Type::isAnyPointerType() const {
6677 return isPointerType() || isObjCObjectPointerType();
6678}
6679
6680inline bool Type::isBlockPointerType() const {
6681 return isa<BlockPointerType>(CanonicalType);
6682}
6683
6684inline bool Type::isReferenceType() const {
6685 return isa<ReferenceType>(CanonicalType);
6686}
6687
6688inline bool Type::isLValueReferenceType() const {
6689 return isa<LValueReferenceType>(CanonicalType);
6690}
6691
6692inline bool Type::isRValueReferenceType() const {
6693 return isa<RValueReferenceType>(CanonicalType);
6694}
6695
6696inline bool Type::isObjectPointerType() const {
6697 // Note: an "object pointer type" is not the same thing as a pointer to an
6698 // object type; rather, it is a pointer to an object type or a pointer to cv
6699 // void.
6700 if (const auto *T = getAs<PointerType>())
6701 return !T->getPointeeType()->isFunctionType();
6702 else
6703 return false;
6704}
6705
6706inline bool Type::isFunctionPointerType() const {
6707 if (const auto *T = getAs<PointerType>())
6708 return T->getPointeeType()->isFunctionType();
6709 else
6710 return false;
6711}
6712
6713inline bool Type::isFunctionReferenceType() const {
6714 if (const auto *T = getAs<ReferenceType>())
6715 return T->getPointeeType()->isFunctionType();
6716 else
6717 return false;
6718}
6719
6720inline bool Type::isMemberPointerType() const {
6721 return isa<MemberPointerType>(CanonicalType);
6722}
6723
6724inline bool Type::isMemberFunctionPointerType() const {
6725 if (const auto *T = getAs<MemberPointerType>())
6726 return T->isMemberFunctionPointer();
6727 else
6728 return false;
6729}
6730
6731inline bool Type::isMemberDataPointerType() const {
6732 if (const auto *T = getAs<MemberPointerType>())
6733 return T->isMemberDataPointer();
6734 else
6735 return false;
6736}
6737
6738inline bool Type::isArrayType() const {
6739 return isa<ArrayType>(CanonicalType);
6740}
6741
6742inline bool Type::isConstantArrayType() const {
6743 return isa<ConstantArrayType>(CanonicalType);
6744}
6745
6746inline bool Type::isIncompleteArrayType() const {
6747 return isa<IncompleteArrayType>(CanonicalType);
6748}
6749
6750inline bool Type::isVariableArrayType() const {
6751 return isa<VariableArrayType>(CanonicalType);
6752}
6753
6754inline bool Type::isDependentSizedArrayType() const {
6755 return isa<DependentSizedArrayType>(CanonicalType);
6756}
6757
6758inline bool Type::isBuiltinType() const {
6759 return isa<BuiltinType>(CanonicalType);
6760}
6761
6762inline bool Type::isRecordType() const {
6763 return isa<RecordType>(CanonicalType);
6764}
6765
6766inline bool Type::isEnumeralType() const {
6767 return isa<EnumType>(CanonicalType);
6768}
6769
6770inline bool Type::isAnyComplexType() const {
6771 return isa<ComplexType>(CanonicalType);
6772}
6773
6774inline bool Type::isVectorType() const {
6775 return isa<VectorType>(CanonicalType);
6776}
6777
6778inline bool Type::isExtVectorType() const {
6779 return isa<ExtVectorType>(CanonicalType);
6780}
6781
6782inline bool Type::isMatrixType() const {
6783 return isa<MatrixType>(CanonicalType);
6784}
6785
6786inline bool Type::isConstantMatrixType() const {
6787 return isa<ConstantMatrixType>(CanonicalType);
6788}
6789
6790inline bool Type::isDependentAddressSpaceType() const {
6791 return isa<DependentAddressSpaceType>(CanonicalType);
6792}
6793
6794inline bool Type::isObjCObjectPointerType() const {
6795 return isa<ObjCObjectPointerType>(CanonicalType);
19
Assuming field 'CanonicalType' is a 'ObjCObjectPointerType'
20
Returning the value 1, which participates in a condition later
6796}
6797
6798inline bool Type::isObjCObjectType() const {
6799 return isa<ObjCObjectType>(CanonicalType);
6800}
6801
6802inline bool Type::isObjCObjectOrInterfaceType() const {
6803 return isa<ObjCInterfaceType>(CanonicalType) ||
6804 isa<ObjCObjectType>(CanonicalType);
6805}
6806
6807inline bool Type::isAtomicType() const {
6808 return isa<AtomicType>(CanonicalType);
6809}
6810
6811inline bool Type::isUndeducedAutoType() const {
6812 return isa<AutoType>(CanonicalType);
6813}
6814
6815inline bool Type::isObjCQualifiedIdType() const {
6816 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6817 return OPT->isObjCQualifiedIdType();
6818 return false;
6819}
6820
6821inline bool Type::isObjCQualifiedClassType() const {
6822 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6823 return OPT->isObjCQualifiedClassType();
6824 return false;
6825}
6826
6827inline bool Type::isObjCIdType() const {
6828 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6829 return OPT->isObjCIdType();
6830 return false;
6831}
6832
6833inline bool Type::isObjCClassType() const {
6834 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6835 return OPT->isObjCClassType();
6836 return false;
6837}
6838
6839inline bool Type::isObjCSelType() const {
6840 if (const auto *OPT = getAs<PointerType>())
6841 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6842 return false;
6843}
6844
6845inline bool Type::isObjCBuiltinType() const {
6846 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6847}
6848
6849inline bool Type::isDecltypeType() const {
6850 return isa<DecltypeType>(this);
6851}
6852
6853#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6854 inline bool Type::is##Id##Type() const { \
6855 return isSpecificBuiltinType(BuiltinType::Id); \
6856 }
6857#include "clang/Basic/OpenCLImageTypes.def"
6858
6859inline bool Type::isSamplerT() const {
6860 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6861}
6862
6863inline bool Type::isEventT() const {
6864 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6865}
6866
6867inline bool Type::isClkEventT() const {
6868 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6869}
6870
6871inline bool Type::isQueueT() const {
6872 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6873}
6874
6875inline bool Type::isReserveIDT() const {
6876 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6877}
6878
6879inline bool Type::isImageType() const {
6880#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6881 return
6882#include "clang/Basic/OpenCLImageTypes.def"
6883 false; // end boolean or operation
6884}
6885
6886inline bool Type::isPipeType() const {
6887 return isa<PipeType>(CanonicalType);
6888}
6889
6890inline bool Type::isExtIntType() const {
6891 return isa<ExtIntType>(CanonicalType);
6892}
6893
6894#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6895 inline bool Type::is##Id##Type() const { \
6896 return isSpecificBuiltinType(BuiltinType::Id); \
6897 }
6898#include "clang/Basic/OpenCLExtensionTypes.def"
6899
6900inline bool Type::isOCLIntelSubgroupAVCType() const {
6901#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6902 isOCLIntelSubgroupAVC##Id##Type() ||
6903 return
6904#include "clang/Basic/OpenCLExtensionTypes.def"
6905 false; // end of boolean or operation
6906}
6907
6908inline bool Type::isOCLExtOpaqueType() const {
6909#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6910 return
6911#include "clang/Basic/OpenCLExtensionTypes.def"
6912 false; // end of boolean or operation
6913}
6914
6915inline bool Type::isOpenCLSpecificType() const {
6916 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6917 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6918}
6919
6920inline bool Type::isTemplateTypeParmType() const {
6921 return isa<TemplateTypeParmType>(CanonicalType);
6922}
6923
6924inline bool Type::isSpecificBuiltinType(unsigned K) const {
6925 if (const BuiltinType *BT = getAs<BuiltinType>()) {
6926 return BT->getKind() == static_cast<BuiltinType::Kind>(K);
6927 }
6928 return false;
6929}
6930
6931inline bool Type::isPlaceholderType() const {
6932 if (const auto *BT = dyn_cast<BuiltinType>(this))
6933 return BT->isPlaceholderType();
6934 return false;
6935}
6936
6937inline const BuiltinType *Type::getAsPlaceholderType() const {
6938 if (const auto *BT = dyn_cast<BuiltinType>(this))
6939 if (BT->isPlaceholderType())
6940 return BT;
6941 return nullptr;
6942}
6943
6944inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6945 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))(static_cast<void> (0));
6946 return isSpecificBuiltinType(K);
6947}
6948
6949inline bool Type::isNonOverloadPlaceholderType() const {
6950 if (const auto *BT = dyn_cast<BuiltinType>(this))
6951 return BT->isNonOverloadPlaceholderType();
6952 return false;
6953}
6954
6955inline bool Type::isVoidType() const {
6956 return isSpecificBuiltinType(BuiltinType::Void);
6957}
6958
6959inline bool Type::isHalfType() const {
6960 // FIXME: Should we allow complex __fp16? Probably not.
6961 return isSpecificBuiltinType(BuiltinType::Half);
6962}
6963
6964inline bool Type::isFloat16Type() const {
6965 return isSpecificBuiltinType(BuiltinType::Float16);
6966}
6967
6968inline bool Type::isBFloat16Type() const {
6969 return isSpecificBuiltinType(BuiltinType::BFloat16);
6970}
6971
6972inline bool Type::isFloat128Type() const {
6973 return isSpecificBuiltinType(BuiltinType::Float128);
6974}
6975
6976inline bool Type::isNullPtrType() const {
6977 return isSpecificBuiltinType(BuiltinType::NullPtr);
6978}
6979
6980bool IsEnumDeclComplete(EnumDecl *);
6981bool IsEnumDeclScoped(EnumDecl *);
6982
6983inline bool Type::isIntegerType() const {
6984 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6985 return BT->getKind() >= BuiltinType::Bool &&
6986 BT->getKind() <= BuiltinType::Int128;
6987 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6988 // Incomplete enum types are not treated as integer types.
6989 // FIXME: In C++, enum types are never integer types.
6990 return IsEnumDeclComplete(ET->getDecl()) &&
6991 !IsEnumDeclScoped(ET->getDecl());
6992 }
6993 return isExtIntType();
6994}
6995
6996inline bool Type::isFixedPointType() const {
6997 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6998 return BT->getKind() >= BuiltinType::ShortAccum &&
6999 BT->getKind() <= BuiltinType::SatULongFract;
7000 }
7001 return false;
7002}
7003
7004inline bool Type::isFixedPointOrIntegerType() const {
7005 return isFixedPointType() || isIntegerType();
7006}
7007
7008inline bool Type::isSaturatedFixedPointType() const {
7009 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7010 return BT->getKind() >= BuiltinType::SatShortAccum &&
7011 BT->getKind() <= BuiltinType::SatULongFract;
7012 }
7013 return false;
7014}
7015
7016inline bool Type::isUnsaturatedFixedPointType() const {
7017 return isFixedPointType() && !isSaturatedFixedPointType();
7018}
7019
7020inline bool Type::isSignedFixedPointType() const {
7021 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7022 return ((BT->getKind() >= BuiltinType::ShortAccum &&
7023 BT->getKind() <= BuiltinType::LongAccum) ||
7024 (BT->getKind() >= BuiltinType::ShortFract &&
7025 BT->getKind() <= BuiltinType::LongFract) ||
7026 (BT->getKind() >= BuiltinType::SatShortAccum &&
7027 BT->getKind() <= BuiltinType::SatLongAccum) ||
7028 (BT->getKind() >= BuiltinType::SatShortFract &&
7029 BT->getKind() <= BuiltinType::SatLongFract));
7030 }
7031 return false;
7032}
7033
7034inline bool Type::isUnsignedFixedPointType() const {
7035 return isFixedPointType() && !isSignedFixedPointType();
7036}
7037
7038inline bool Type::isScalarType() const {
7039 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7040 return BT->getKind() > BuiltinType::Void &&
7041 BT->getKind() <= BuiltinType::NullPtr;
7042 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
7043 // Enums are scalar types, but only if they are defined. Incomplete enums
7044 // are not treated as scalar types.
7045 return IsEnumDeclComplete(ET->getDecl());
7046 return isa<PointerType>(CanonicalType) ||
7047 isa<BlockPointerType>(CanonicalType) ||
7048 isa<MemberPointerType>(CanonicalType) ||
7049 isa<ComplexType>(CanonicalType) ||
7050 isa<ObjCObjectPointerType>(CanonicalType) ||
7051 isExtIntType();
7052}
7053
7054inline bool Type::isIntegralOrEnumerationType() const {
7055 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7056 return BT->getKind() >= BuiltinType::Bool &&
7057 BT->getKind() <= BuiltinType::Int128;
7058
7059 // Check for a complete enum type; incomplete enum types are not properly an
7060 // enumeration type in the sense required here.
7061 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
7062 return IsEnumDeclComplete(ET->getDecl());
7063
7064 return isExtIntType();
7065}
7066
7067inline bool Type::isBooleanType() const {
7068 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7069 return BT->getKind() == BuiltinType::Bool;
7070 return false;
7071}
7072
7073inline bool Type::isUndeducedType() const {
7074 auto *DT = getContainedDeducedType();
7075 return DT && !DT->isDeduced();
7076}
7077
7078/// Determines whether this is a type for which one can define
7079/// an overloaded operator.
7080inline bool Type::isOverloadableType() const {
7081 return isDependentType() || isRecordType() || isEnumeralType();
7082}
7083
7084/// Determines whether this type is written as a typedef-name.
7085inline bool Type::isTypedefNameType() const {
7086 if (getAs<TypedefType>())
7087 return true;
7088 if (auto *TST = getAs<TemplateSpecializationType>())
7089 return TST->isTypeAlias();
7090 return false;
7091}
7092
7093/// Determines whether this type can decay to a pointer type.
7094inline bool Type::canDecayToPointerType() const {
7095 return isFunctionType() || isArrayType();
7096}
7097
7098inline bool Type::hasPointerRepresentation() const {
7099 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
7100 isObjCObjectPointerType() || isNullPtrType());
7101}
7102
7103inline bool Type::hasObjCPointerRepresentation() const {
7104 return isObjCObjectPointerType();
7105}
7106
7107inline const Type *Type::getBaseElementTypeUnsafe() const {
7108 const Type *type = this;
7109 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
7110 type = arrayType->getElementType().getTypePtr();
7111 return type;
7112}
7113
7114inline const Type *Type::getPointeeOrArrayElementType() const {
7115 const Type *type = this;
7116 if (type->isAnyPointerType())
7117 return type->getPointeeType().getTypePtr();
7118 else if (type->isArrayType())
7119 return type->getBaseElementTypeUnsafe();
7120 return type;
7121}
7122/// Insertion operator for partial diagnostics. This allows sending adress
7123/// spaces into a diagnostic with <<.
7124inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7125 LangAS AS) {
7126 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
7127 DiagnosticsEngine::ArgumentKind::ak_addrspace);
7128 return PD;
7129}
7130
7131/// Insertion operator for partial diagnostics. This allows sending Qualifiers
7132/// into a diagnostic with <<.
7133inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7134 Qualifiers Q) {
7135 PD.AddTaggedVal(Q.getAsOpaqueValue(),
7136 DiagnosticsEngine::ArgumentKind::ak_qual);
7137 return PD;
7138}
7139
7140/// Insertion operator for partial diagnostics. This allows sending QualType's
7141/// into a diagnostic with <<.
7142inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7143 QualType T) {
7144 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7145 DiagnosticsEngine::ak_qualtype);
7146 return PD;
7147}
7148
7149// Helper class template that is used by Type::getAs to ensure that one does
7150// not try to look through a qualified type to get to an array type.
7151template <typename T>
7152using TypeIsArrayType =
7153 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7154 std::is_base_of<ArrayType, T>::value>;
7155
7156// Member-template getAs<specific type>'.
7157template <typename T> const T *Type::getAs() const {
7158 static_assert(!TypeIsArrayType<T>::value,
7159 "ArrayType cannot be used with getAs!");
7160
7161 // If this is directly a T type, return it.
7162 if (const auto *Ty = dyn_cast<T>(this))
7163 return Ty;
7164
7165 // If the canonical form of this type isn't the right kind, reject it.
7166 if (!isa<T>(CanonicalType))
7167 return nullptr;
7168
7169 // If this is a typedef for the type, strip the typedef off without
7170 // losing all typedef information.
7171 return cast<T>(getUnqualifiedDesugaredType());
7172}
7173
7174template <typename T> const T *Type::getAsAdjusted() const {
7175 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7176
7177 // If this is directly a T type, return it.
7178 if (const auto *Ty = dyn_cast<T>(this))
7179 return Ty;
7180
7181 // If the canonical form of this type isn't the right kind, reject it.
7182 if (!isa<T>(CanonicalType))
7183 return nullptr;
7184
7185 // Strip off type adjustments that do not modify the underlying nature of the
7186 // type.
7187 const Type *Ty = this;
7188 while (Ty) {
7189 if (const auto *A = dyn_cast<AttributedType>(Ty))
7190 Ty = A->getModifiedType().getTypePtr();
7191 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7192 Ty = E->desugar().getTypePtr();
7193 else if (const auto *P = dyn_cast<ParenType>(Ty))
7194 Ty = P->desugar().getTypePtr();
7195 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7196 Ty = A->desugar().getTypePtr();
7197 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7198 Ty = M->desugar().getTypePtr();
7199 else
7200 break;
7201 }
7202
7203 // Just because the canonical type is correct does not mean we can use cast<>,
7204 // since we may not have stripped off all the sugar down to the base type.
7205 return dyn_cast<T>(Ty);
7206}
7207
7208inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7209 // If this is directly an array type, return it.
7210 if (const auto *arr = dyn_cast<ArrayType>(this))
7211 return arr;
7212
7213 // If the canonical form of this type isn't the right kind, reject it.
7214 if (!isa<ArrayType>(CanonicalType))
7215 return nullptr;
7216
7217 // If this is a typedef for the type, strip the typedef off without
7218 // losing all typedef information.
7219 return cast<ArrayType>(getUnqualifiedDesugaredType());
7220}
7221
7222template <typename T> const T *Type::castAs() const {
7223 static_assert(!TypeIsArrayType<T>::value,
7224 "ArrayType cannot be used with castAs!");
7225
7226 if (const auto *ty = dyn_cast<T>(this)) return ty;
7227 assert(isa<T>(CanonicalType))(static_cast<void> (0));
7228 return cast<T>(getUnqualifiedDesugaredType());
7229}
7230
7231inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7232 assert(isa<ArrayType>(CanonicalType))(static_cast<void> (0));
7233 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7234 return cast<ArrayType>(getUnqualifiedDesugaredType());
7235}
7236
7237DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7238 QualType CanonicalPtr)
7239 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7240#ifndef NDEBUG1
7241 QualType Adjusted = getAdjustedType();
7242 (void)AttributedType::stripOuterNullability(Adjusted);
7243 assert(isa<PointerType>(Adjusted))(static_cast<void> (0));
7244#endif
7245}
7246
7247QualType DecayedType::getPointeeType() const {
7248 QualType Decayed = getDecayedType();
7249 (void)AttributedType::stripOuterNullability(Decayed);
7250 return cast<PointerType>(Decayed)->getPointeeType();
7251}
7252
7253// Get the decimal string representation of a fixed point type, represented
7254// as a scaled integer.
7255// TODO: At some point, we should change the arguments to instead just accept an
7256// APFixedPoint instead of APSInt and scale.
7257void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7258 unsigned Scale);
7259
7260} // namespace clang
7261
7262#endif // LLVM_CLANG_AST_TYPE_H

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the PointerUnion class, which is a discriminated union of
10// pointer types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERUNION_H
15#define LLVM_ADT_POINTERUNION_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include <cassert>
21#include <cstddef>
22#include <cstdint>
23
24namespace llvm {
25
26namespace pointer_union_detail {
27 /// Determine the number of bits required to store integers with values < n.
28 /// This is ceil(log2(n)).
29 constexpr int bitsRequired(unsigned n) {
30 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
31 }
32
33 template <typename... Ts> constexpr int lowBitsAvailable() {
34 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
35 }
36
37 /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
38 /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
39 /// list.
40 template <typename T, typename ...Us> struct TypeIndex;
41 template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> {
42 static constexpr int Index = 0;
43 };
44 template <typename T, typename U, typename... Us>
45 struct TypeIndex<T, U, Us...> {
46 static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
47 };
48 template <typename T> struct TypeIndex<T> {
49 static constexpr int Index = 0;
50 };
51
52 /// Find the first type in a list of types.
53 template <typename T, typename...> struct GetFirstType {
54 using type = T;
55 };
56
57 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
58 /// for the template arguments.
59 template <typename ...PTs> class PointerUnionUIntTraits {
60 public:
61 static inline void *getAsVoidPointer(void *P) { return P; }
62 static inline void *getFromVoidPointer(void *P) { return P; }
63 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
64 };
65
66 template <typename Derived, typename ValTy, int I, typename ...Types>
67 class PointerUnionMembers;
68
69 template <typename Derived, typename ValTy, int I>
70 class PointerUnionMembers<Derived, ValTy, I> {
71 protected:
72 ValTy Val;
73 PointerUnionMembers() = default;
74 PointerUnionMembers(ValTy Val) : Val(Val) {}
75
76 friend struct PointerLikeTypeTraits<Derived>;
77 };
78
79 template <typename Derived, typename ValTy, int I, typename Type,
80 typename ...Types>
81 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
82 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
83 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
84 public:
85 using Base::Base;
86 PointerUnionMembers() = default;
87 PointerUnionMembers(Type V)
88 : Base(ValTy(const_cast<void *>(
89 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
90 I)) {}
91
92 using Base::operator=;
93 Derived &operator=(Type V) {
94 this->Val = ValTy(
95 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
96 I);
97 return static_cast<Derived &>(*this);
98 };
99 };
100}
101
102/// A discriminated union of two or more pointer types, with the discriminator
103/// in the low bit of the pointer.
104///
105/// This implementation is extremely efficient in space due to leveraging the
106/// low bits of the pointer, while exposing a natural and type-safe API.
107///
108/// Common use patterns would be something like this:
109/// PointerUnion<int*, float*> P;
110/// P = (int*)0;
111/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
112/// X = P.get<int*>(); // ok.
113/// Y = P.get<float*>(); // runtime assertion failure.
114/// Z = P.get<double*>(); // compile time failure.
115/// P = (float*)0;
116/// Y = P.get<float*>(); // ok.
117/// X = P.get<int*>(); // runtime assertion failure.
118template <typename... PTs>
119class PointerUnion
120 : public pointer_union_detail::PointerUnionMembers<
121 PointerUnion<PTs...>,
122 PointerIntPair<
123 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
124 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
125 0, PTs...> {
126 // The first type is special because we want to directly cast a pointer to a
127 // default-initialized union to a pointer to the first type. But we don't
128 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
129 // because it's much more convenient to have a name for the whole pack. So
130 // split off the first type here.
131 using First = typename pointer_union_detail::GetFirstType<PTs...>::type;
132 using Base = typename PointerUnion::PointerUnionMembers;
133
134public:
135 PointerUnion() = default;
136
137 PointerUnion(std::nullptr_t) : PointerUnion() {}
138 using Base::Base;
139
140 /// Test if the pointer held in the union is null, regardless of
141 /// which type it is.
142 bool isNull() const { return !this->Val.getPointer(); }
13
Assuming the condition is false
14
Returning zero, which participates in a condition later
143
144 explicit operator bool() const { return !isNull(); }
145
146 /// Test if the Union currently holds the type matching T.
147 template <typename T> bool is() const {
148 constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index;
149 static_assert(Index < sizeof...(PTs),
150 "PointerUnion::is<T> given type not in the union");
151 return this->Val.getInt() == Index;
152 }
153
154 /// Returns the value of the specified pointer type.
155 ///
156 /// If the specified pointer type is incorrect, assert.
157 template <typename T> T get() const {
158 assert(is<T>() && "Invalid accessor called")(static_cast<void> (0));
159 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
160 }
161
162 /// Returns the current pointer if it is of the specified pointer type,
163 /// otherwise returns null.
164 template <typename T> T dyn_cast() const {
165 if (is<T>())
166 return get<T>();
167 return T();
168 }
169
170 /// If the union is set to the first pointer type get an address pointing to
171 /// it.
172 First const *getAddrOfPtr1() const {
173 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
174 }
175
176 /// If the union is set to the first pointer type get an address pointing to
177 /// it.
178 First *getAddrOfPtr1() {
179 assert(is<First>() && "Val is not the first pointer")(static_cast<void> (0));
180 assert((static_cast<void> (0))
181 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==(static_cast<void> (0))
182 this->Val.getPointer() &&(static_cast<void> (0))
183 "Can't get the address because PointerLikeTypeTraits changes the ptr")(static_cast<void> (0));
184 return const_cast<First *>(
185 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
186 }
187
188 /// Assignment from nullptr which just clears the union.
189 const PointerUnion &operator=(std::nullptr_t) {
190 this->Val.initWithPointer(nullptr);
191 return *this;
192 }
193
194 /// Assignment from elements of the union.
195 using Base::operator=;
196
197 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
198 static inline PointerUnion getFromOpaqueValue(void *VP) {
199 PointerUnion V;
200 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
201 return V;
202 }
203};
204
205template <typename ...PTs>
206bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
207 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
208}
209
210template <typename ...PTs>
211bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
212 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
213}
214
215template <typename ...PTs>
216bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
217 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
218}
219
220// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
221// # low bits available = min(PT1bits,PT2bits)-1.
222template <typename ...PTs>
223struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
224 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
225 return P.getOpaqueValue();
226 }
227
228 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
229 return PointerUnion<PTs...>::getFromOpaqueValue(P);
230 }
231
232 // The number of bits available are the min of the pointer types minus the
233 // bits needed for the discriminator.
234 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
235 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
236};
237
238// Teach DenseMap how to use PointerUnions as keys.
239template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
240 using Union = PointerUnion<PTs...>;
241 using FirstInfo =
242 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
243
244 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
245
246 static inline Union getTombstoneKey() {
247 return Union(FirstInfo::getTombstoneKey());
248 }
249
250 static unsigned getHashValue(const Union &UnionVal) {
251 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
252 return DenseMapInfo<intptr_t>::getHashValue(key);
253 }
254
255 static bool isEqual(const Union &LHS, const Union &RHS) {
256 return LHS == RHS;
257 }
258};
259
260} // end namespace llvm
261
262#endif // LLVM_ADT_POINTERUNION_H