1 //===--- AST.cpp - Utility AST functions -----------------------*- 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 #include "AST.h"
10
11 #include "SourceCode.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/ASTTypeTraits.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclBase.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/DeclarationName.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/NestedNameSpecifier.h"
21 #include "clang/AST/PrettyPrinter.h"
22 #include "clang/AST/RecursiveASTVisitor.h"
23 #include "clang/AST/Stmt.h"
24 #include "clang/AST/TemplateBase.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/SourceLocation.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Index/USRGeneration.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/None.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <iterator>
40 #include <string>
41 #include <vector>
42
43 namespace clang {
44 namespace clangd {
45
46 namespace {
47 llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>>
getTemplateSpecializationArgLocs(const NamedDecl & ND)48 getTemplateSpecializationArgLocs(const NamedDecl &ND) {
49 if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) {
50 if (const ASTTemplateArgumentListInfo *Args =
51 Func->getTemplateSpecializationArgsAsWritten())
52 return Args->arguments();
53 } else if (auto *Cls =
54 llvm::dyn_cast<ClassTemplatePartialSpecializationDecl>(&ND)) {
55 if (auto *Args = Cls->getTemplateArgsAsWritten())
56 return Args->arguments();
57 } else if (auto *Var =
58 llvm::dyn_cast<VarTemplatePartialSpecializationDecl>(&ND)) {
59 if (auto *Args = Var->getTemplateArgsAsWritten())
60 return Args->arguments();
61 } else if (auto *Var = llvm::dyn_cast<VarTemplateSpecializationDecl>(&ND)) {
62 if (auto *Args = Var->getTemplateArgsInfo())
63 return Args->arguments();
64 }
65 // We return None for ClassTemplateSpecializationDecls because it does not
66 // contain TemplateArgumentLoc information.
67 return llvm::None;
68 }
69
70 template <class T>
isTemplateSpecializationKind(const NamedDecl * D,TemplateSpecializationKind Kind)71 bool isTemplateSpecializationKind(const NamedDecl *D,
72 TemplateSpecializationKind Kind) {
73 if (const auto *TD = dyn_cast<T>(D))
74 return TD->getTemplateSpecializationKind() == Kind;
75 return false;
76 }
77
isTemplateSpecializationKind(const NamedDecl * D,TemplateSpecializationKind Kind)78 bool isTemplateSpecializationKind(const NamedDecl *D,
79 TemplateSpecializationKind Kind) {
80 return isTemplateSpecializationKind<FunctionDecl>(D, Kind) ||
81 isTemplateSpecializationKind<CXXRecordDecl>(D, Kind) ||
82 isTemplateSpecializationKind<VarDecl>(D, Kind);
83 }
84
85 // Store all UsingDirectiveDecls in parent contexts of DestContext, that were
86 // introduced before InsertionPoint.
87 llvm::DenseSet<const NamespaceDecl *>
getUsingNamespaceDirectives(const DeclContext * DestContext,SourceLocation Until)88 getUsingNamespaceDirectives(const DeclContext *DestContext,
89 SourceLocation Until) {
90 const auto &SM = DestContext->getParentASTContext().getSourceManager();
91 llvm::DenseSet<const NamespaceDecl *> VisibleNamespaceDecls;
92 for (const auto *DC = DestContext; DC; DC = DC->getLookupParent()) {
93 for (const auto *D : DC->decls()) {
94 if (!SM.isWrittenInSameFile(D->getLocation(), Until) ||
95 !SM.isBeforeInTranslationUnit(D->getLocation(), Until))
96 continue;
97 if (auto *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D))
98 VisibleNamespaceDecls.insert(
99 UDD->getNominatedNamespace()->getCanonicalDecl());
100 }
101 }
102 return VisibleNamespaceDecls;
103 }
104
105 // Goes over all parents of SourceContext until we find a common ancestor for
106 // DestContext and SourceContext. Any qualifier including and above common
107 // ancestor is redundant, therefore we stop at lowest common ancestor.
108 // In addition to that stops early whenever IsVisible returns true. This can be
109 // used to implement support for "using namespace" decls.
110 std::string
getQualification(ASTContext & Context,const DeclContext * DestContext,const DeclContext * SourceContext,llvm::function_ref<bool (NestedNameSpecifier *)> IsVisible)111 getQualification(ASTContext &Context, const DeclContext *DestContext,
112 const DeclContext *SourceContext,
113 llvm::function_ref<bool(NestedNameSpecifier *)> IsVisible) {
114 std::vector<const NestedNameSpecifier *> Parents;
115 bool ReachedNS = false;
116 for (const DeclContext *CurContext = SourceContext; CurContext;
117 CurContext = CurContext->getLookupParent()) {
118 // Stop once we reach a common ancestor.
119 if (CurContext->Encloses(DestContext))
120 break;
121
122 NestedNameSpecifier *NNS = nullptr;
123 if (auto *TD = llvm::dyn_cast<TagDecl>(CurContext)) {
124 // There can't be any more tag parents after hitting a namespace.
125 assert(!ReachedNS);
126 (void)ReachedNS;
127 NNS = NestedNameSpecifier::Create(Context, nullptr, false,
128 TD->getTypeForDecl());
129 } else if (auto *NSD = llvm::dyn_cast<NamespaceDecl>(CurContext)) {
130 ReachedNS = true;
131 NNS = NestedNameSpecifier::Create(Context, nullptr, NSD);
132 // Anonymous and inline namespace names are not spelled while qualifying
133 // a name, so skip those.
134 if (NSD->isAnonymousNamespace() || NSD->isInlineNamespace())
135 continue;
136 } else {
137 // Other types of contexts cannot be spelled in code, just skip over
138 // them.
139 continue;
140 }
141 // Stop if this namespace is already visible at DestContext.
142 if (IsVisible(NNS))
143 break;
144
145 Parents.push_back(NNS);
146 }
147
148 // Go over name-specifiers in reverse order to create necessary qualification,
149 // since we stored inner-most parent first.
150 std::string Result;
151 llvm::raw_string_ostream OS(Result);
152 for (const auto *Parent : llvm::reverse(Parents))
153 Parent->print(OS, Context.getPrintingPolicy());
154 return OS.str();
155 }
156
157 } // namespace
158
isImplicitTemplateInstantiation(const NamedDecl * D)159 bool isImplicitTemplateInstantiation(const NamedDecl *D) {
160 return isTemplateSpecializationKind(D, TSK_ImplicitInstantiation);
161 }
162
isExplicitTemplateSpecialization(const NamedDecl * D)163 bool isExplicitTemplateSpecialization(const NamedDecl *D) {
164 return isTemplateSpecializationKind(D, TSK_ExplicitSpecialization);
165 }
166
isImplementationDetail(const Decl * D)167 bool isImplementationDetail(const Decl *D) {
168 return !isSpelledInSource(D->getLocation(),
169 D->getASTContext().getSourceManager());
170 }
171
nameLocation(const clang::Decl & D,const SourceManager & SM)172 SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM) {
173 auto L = D.getLocation();
174 // For `- (void)foo` we want `foo` not the `-`.
175 if (const auto *MD = dyn_cast<ObjCMethodDecl>(&D))
176 L = MD->getSelectorStartLoc();
177 if (isSpelledInSource(L, SM))
178 return SM.getSpellingLoc(L);
179 return SM.getExpansionLoc(L);
180 }
181
printQualifiedName(const NamedDecl & ND)182 std::string printQualifiedName(const NamedDecl &ND) {
183 std::string QName;
184 llvm::raw_string_ostream OS(QName);
185 PrintingPolicy Policy(ND.getASTContext().getLangOpts());
186 // Note that inline namespaces are treated as transparent scopes. This
187 // reflects the way they're most commonly used for lookup. Ideally we'd
188 // include them, but at query time it's hard to find all the inline
189 // namespaces to query: the preamble doesn't have a dedicated list.
190 Policy.SuppressUnwrittenScope = true;
191 ND.printQualifiedName(OS, Policy);
192 OS.flush();
193 assert(!StringRef(QName).startswith("::"));
194 return QName;
195 }
196
isAnonymous(const DeclarationName & N)197 static bool isAnonymous(const DeclarationName &N) {
198 return N.isIdentifier() && !N.getAsIdentifierInfo();
199 }
200
getQualifierLoc(const NamedDecl & ND)201 NestedNameSpecifierLoc getQualifierLoc(const NamedDecl &ND) {
202 if (auto *V = llvm::dyn_cast<DeclaratorDecl>(&ND))
203 return V->getQualifierLoc();
204 if (auto *T = llvm::dyn_cast<TagDecl>(&ND))
205 return T->getQualifierLoc();
206 return NestedNameSpecifierLoc();
207 }
208
printUsingNamespaceName(const ASTContext & Ctx,const UsingDirectiveDecl & D)209 std::string printUsingNamespaceName(const ASTContext &Ctx,
210 const UsingDirectiveDecl &D) {
211 PrintingPolicy PP(Ctx.getLangOpts());
212 std::string Name;
213 llvm::raw_string_ostream Out(Name);
214
215 if (auto *Qual = D.getQualifier())
216 Qual->print(Out, PP);
217 D.getNominatedNamespaceAsWritten()->printName(Out);
218 return Out.str();
219 }
220
printName(const ASTContext & Ctx,const NamedDecl & ND)221 std::string printName(const ASTContext &Ctx, const NamedDecl &ND) {
222 std::string Name;
223 llvm::raw_string_ostream Out(Name);
224 PrintingPolicy PP(Ctx.getLangOpts());
225 // We don't consider a class template's args part of the constructor name.
226 PP.SuppressTemplateArgsInCXXConstructors = true;
227
228 // Handle 'using namespace'. They all have the same name - <using-directive>.
229 if (auto *UD = llvm::dyn_cast<UsingDirectiveDecl>(&ND)) {
230 Out << "using namespace ";
231 if (auto *Qual = UD->getQualifier())
232 Qual->print(Out, PP);
233 UD->getNominatedNamespaceAsWritten()->printName(Out);
234 return Out.str();
235 }
236
237 if (isAnonymous(ND.getDeclName())) {
238 // Come up with a presentation for an anonymous entity.
239 if (isa<NamespaceDecl>(ND))
240 return "(anonymous namespace)";
241 if (auto *Cls = llvm::dyn_cast<RecordDecl>(&ND)) {
242 if (Cls->isLambda())
243 return "(lambda)";
244 return ("(anonymous " + Cls->getKindName() + ")").str();
245 }
246 if (isa<EnumDecl>(ND))
247 return "(anonymous enum)";
248 return "(anonymous)";
249 }
250
251 // Print nested name qualifier if it was written in the source code.
252 if (auto *Qualifier = getQualifierLoc(ND).getNestedNameSpecifier())
253 Qualifier->print(Out, PP);
254 // Print the name itself.
255 ND.getDeclName().print(Out, PP);
256 // Print template arguments.
257 Out << printTemplateSpecializationArgs(ND);
258
259 return Out.str();
260 }
261
printTemplateSpecializationArgs(const NamedDecl & ND)262 std::string printTemplateSpecializationArgs(const NamedDecl &ND) {
263 std::string TemplateArgs;
264 llvm::raw_string_ostream OS(TemplateArgs);
265 PrintingPolicy Policy(ND.getASTContext().getLangOpts());
266 if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
267 getTemplateSpecializationArgLocs(ND)) {
268 printTemplateArgumentList(OS, *Args, Policy);
269 } else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) {
270 if (const TypeSourceInfo *TSI = Cls->getTypeAsWritten()) {
271 // ClassTemplateSpecializationDecls do not contain
272 // TemplateArgumentTypeLocs, they only have TemplateArgumentTypes. So we
273 // create a new argument location list from TypeSourceInfo.
274 auto STL = TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
275 llvm::SmallVector<TemplateArgumentLoc> ArgLocs;
276 ArgLocs.reserve(STL.getNumArgs());
277 for (unsigned I = 0; I < STL.getNumArgs(); ++I)
278 ArgLocs.push_back(STL.getArgLoc(I));
279 printTemplateArgumentList(OS, ArgLocs, Policy);
280 } else {
281 // FIXME: Fix cases when getTypeAsWritten returns null inside clang AST,
282 // e.g. friend decls. Currently we fallback to Template Arguments without
283 // location information.
284 printTemplateArgumentList(OS, Cls->getTemplateArgs().asArray(), Policy);
285 }
286 }
287 OS.flush();
288 return TemplateArgs;
289 }
290
printNamespaceScope(const DeclContext & DC)291 std::string printNamespaceScope(const DeclContext &DC) {
292 for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent())
293 if (const auto *NS = dyn_cast<NamespaceDecl>(Ctx))
294 if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
295 return printQualifiedName(*NS) + "::";
296 return "";
297 }
298
299 static llvm::StringRef
getNameOrErrForObjCInterface(const ObjCInterfaceDecl * ID)300 getNameOrErrForObjCInterface(const ObjCInterfaceDecl *ID) {
301 return ID ? ID->getName() : "<<error-type>>";
302 }
303
printObjCMethod(const ObjCMethodDecl & Method)304 std::string printObjCMethod(const ObjCMethodDecl &Method) {
305 std::string Name;
306 llvm::raw_string_ostream OS(Name);
307
308 OS << (Method.isInstanceMethod() ? '-' : '+') << '[';
309
310 // Should always be true.
311 if (const ObjCContainerDecl *C =
312 dyn_cast<ObjCContainerDecl>(Method.getDeclContext()))
313 OS << printObjCContainer(*C);
314
315 Method.getSelector().print(OS << ' ');
316 if (Method.isVariadic())
317 OS << ", ...";
318
319 OS << ']';
320 OS.flush();
321 return Name;
322 }
323
printObjCContainer(const ObjCContainerDecl & C)324 std::string printObjCContainer(const ObjCContainerDecl &C) {
325 if (const ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(&C)) {
326 std::string Name;
327 llvm::raw_string_ostream OS(Name);
328 const ObjCInterfaceDecl *Class = Category->getClassInterface();
329 OS << getNameOrErrForObjCInterface(Class) << '(' << Category->getName()
330 << ')';
331 OS.flush();
332 return Name;
333 }
334 if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(&C)) {
335 std::string Name;
336 llvm::raw_string_ostream OS(Name);
337 const ObjCInterfaceDecl *Class = CID->getClassInterface();
338 OS << getNameOrErrForObjCInterface(Class) << '(' << CID->getName() << ')';
339 OS.flush();
340 return Name;
341 }
342 return C.getNameAsString();
343 }
344
getSymbolID(const Decl * D)345 SymbolID getSymbolID(const Decl *D) {
346 llvm::SmallString<128> USR;
347 if (index::generateUSRForDecl(D, USR))
348 return {};
349 return SymbolID(USR);
350 }
351
getSymbolID(const llvm::StringRef MacroName,const MacroInfo * MI,const SourceManager & SM)352 SymbolID getSymbolID(const llvm::StringRef MacroName, const MacroInfo *MI,
353 const SourceManager &SM) {
354 if (MI == nullptr)
355 return {};
356 llvm::SmallString<128> USR;
357 if (index::generateUSRForMacro(MacroName, MI->getDefinitionLoc(), SM, USR))
358 return {};
359 return SymbolID(USR);
360 }
361
getCorrespondingObjCImpl(const ObjCContainerDecl * D)362 const ObjCImplDecl *getCorrespondingObjCImpl(const ObjCContainerDecl *D) {
363 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
364 return ID->getImplementation();
365 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
366 if (CD->IsClassExtension()) {
367 if (const auto *ID = CD->getClassInterface())
368 return ID->getImplementation();
369 return nullptr;
370 }
371 return CD->getImplementation();
372 }
373 return nullptr;
374 }
375
printType(const QualType QT,const DeclContext & CurContext,const llvm::StringRef Placeholder)376 std::string printType(const QualType QT, const DeclContext &CurContext,
377 const llvm::StringRef Placeholder) {
378 std::string Result;
379 llvm::raw_string_ostream OS(Result);
380 PrintingPolicy PP(CurContext.getParentASTContext().getPrintingPolicy());
381 PP.SuppressTagKeyword = true;
382 PP.SuppressUnwrittenScope = true;
383
384 class PrintCB : public PrintingCallbacks {
385 public:
386 PrintCB(const DeclContext *CurContext) : CurContext(CurContext) {}
387 virtual ~PrintCB() {}
388 bool isScopeVisible(const DeclContext *DC) const override {
389 return DC->Encloses(CurContext);
390 }
391
392 private:
393 const DeclContext *CurContext;
394 };
395 PrintCB PCB(&CurContext);
396 PP.Callbacks = &PCB;
397
398 QT.print(OS, PP, Placeholder);
399 return OS.str();
400 }
401
hasReservedName(const Decl & D)402 bool hasReservedName(const Decl &D) {
403 if (const auto *ND = llvm::dyn_cast<NamedDecl>(&D))
404 if (const auto *II = ND->getIdentifier())
405 return isReservedName(II->getName());
406 return false;
407 }
408
hasReservedScope(const DeclContext & DC)409 bool hasReservedScope(const DeclContext &DC) {
410 for (const DeclContext *D = &DC; D; D = D->getParent()) {
411 if (D->isTransparentContext() || D->isInlineNamespace())
412 continue;
413 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
414 if (hasReservedName(*ND))
415 return true;
416 }
417 return false;
418 }
419
declaredType(const TypeDecl * D)420 QualType declaredType(const TypeDecl *D) {
421 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D))
422 if (const auto *TSI = CTSD->getTypeAsWritten())
423 return TSI->getType();
424 return D->getASTContext().getTypeDeclType(D);
425 }
426
427 namespace {
428 /// Computes the deduced type at a given location by visiting the relevant
429 /// nodes. We use this to display the actual type when hovering over an "auto"
430 /// keyword or "decltype()" expression.
431 /// FIXME: This could have been a lot simpler by visiting AutoTypeLocs but it
432 /// seems that the AutoTypeLocs that can be visited along with their AutoType do
433 /// not have the deduced type set. Instead, we have to go to the appropriate
434 /// DeclaratorDecl/FunctionDecl and work our back to the AutoType that does have
435 /// a deduced type set. The AST should be improved to simplify this scenario.
436 class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> {
437 SourceLocation SearchedLocation;
438
439 public:
DeducedTypeVisitor(SourceLocation SearchedLocation)440 DeducedTypeVisitor(SourceLocation SearchedLocation)
441 : SearchedLocation(SearchedLocation) {}
442
443 // Handle auto initializers:
444 //- auto i = 1;
445 //- decltype(auto) i = 1;
446 //- auto& i = 1;
447 //- auto* i = &a;
VisitDeclaratorDecl(DeclaratorDecl * D)448 bool VisitDeclaratorDecl(DeclaratorDecl *D) {
449 if (!D->getTypeSourceInfo() ||
450 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc() != SearchedLocation)
451 return true;
452
453 if (auto *AT = D->getType()->getContainedAutoType()) {
454 DeducedType = AT->desugar();
455 }
456 return true;
457 }
458
459 // Handle auto return types:
460 //- auto foo() {}
461 //- auto& foo() {}
462 //- auto foo() -> int {}
463 //- auto foo() -> decltype(1+1) {}
464 //- operator auto() const { return 10; }
VisitFunctionDecl(FunctionDecl * D)465 bool VisitFunctionDecl(FunctionDecl *D) {
466 if (!D->getTypeSourceInfo())
467 return true;
468 // Loc of auto in return type (c++14).
469 auto CurLoc = D->getReturnTypeSourceRange().getBegin();
470 // Loc of "auto" in operator auto()
471 if (CurLoc.isInvalid() && isa<CXXConversionDecl>(D))
472 CurLoc = D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
473 // Loc of "auto" in function with trailing return type (c++11).
474 if (CurLoc.isInvalid())
475 CurLoc = D->getSourceRange().getBegin();
476 if (CurLoc != SearchedLocation)
477 return true;
478
479 const AutoType *AT = D->getReturnType()->getContainedAutoType();
480 if (AT && !AT->getDeducedType().isNull()) {
481 DeducedType = AT->getDeducedType();
482 } else if (auto *DT = dyn_cast<DecltypeType>(D->getReturnType())) {
483 // auto in a trailing return type just points to a DecltypeType and
484 // getContainedAutoType does not unwrap it.
485 if (!DT->getUnderlyingType().isNull())
486 DeducedType = DT->getUnderlyingType();
487 } else if (!D->getReturnType().isNull()) {
488 DeducedType = D->getReturnType();
489 }
490 return true;
491 }
492
493 // Handle non-auto decltype, e.g.:
494 // - auto foo() -> decltype(expr) {}
495 // - decltype(expr);
VisitDecltypeTypeLoc(DecltypeTypeLoc TL)496 bool VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
497 if (TL.getBeginLoc() != SearchedLocation)
498 return true;
499
500 // A DecltypeType's underlying type can be another DecltypeType! E.g.
501 // int I = 0;
502 // decltype(I) J = I;
503 // decltype(J) K = J;
504 const DecltypeType *DT = dyn_cast<DecltypeType>(TL.getTypePtr());
505 while (DT && !DT->getUnderlyingType().isNull()) {
506 DeducedType = DT->getUnderlyingType();
507 DT = dyn_cast<DecltypeType>(DeducedType.getTypePtr());
508 }
509 return true;
510 }
511
512 // Handle functions/lambdas with `auto` typed parameters.
513 // We deduce the type if there's exactly one instantiation visible.
VisitParmVarDecl(ParmVarDecl * PVD)514 bool VisitParmVarDecl(ParmVarDecl *PVD) {
515 if (!PVD->getType()->isDependentType())
516 return true;
517 // 'auto' here does not name an AutoType, but an implicit template param.
518 TemplateTypeParmTypeLoc Auto =
519 getContainedAutoParamType(PVD->getTypeSourceInfo()->getTypeLoc());
520 if (Auto.isNull() || Auto.getNameLoc() != SearchedLocation)
521 return true;
522
523 // We expect the TTP to be attached to this function template.
524 // Find the template and the param index.
525 auto *Templated = llvm::dyn_cast<FunctionDecl>(PVD->getDeclContext());
526 if (!Templated)
527 return true;
528 auto *FTD = Templated->getDescribedFunctionTemplate();
529 if (!FTD)
530 return true;
531 int ParamIndex = paramIndex(*FTD, *Auto.getDecl());
532 if (ParamIndex < 0) {
533 assert(false && "auto TTP is not from enclosing function?");
534 return true;
535 }
536
537 // Now find the instantiation and the deduced template type arg.
538 auto *Instantiation =
539 llvm::dyn_cast_or_null<FunctionDecl>(getOnlyInstantiation(Templated));
540 if (!Instantiation)
541 return true;
542 const auto *Args = Instantiation->getTemplateSpecializationArgs();
543 if (Args->size() != FTD->getTemplateParameters()->size())
544 return true; // no weird variadic stuff
545 DeducedType = Args->get(ParamIndex).getAsType();
546 return true;
547 }
548
paramIndex(const TemplateDecl & TD,NamedDecl & Param)549 static int paramIndex(const TemplateDecl &TD, NamedDecl &Param) {
550 unsigned I = 0;
551 for (auto *ND : *TD.getTemplateParameters()) {
552 if (&Param == ND)
553 return I;
554 ++I;
555 }
556 return -1;
557 }
558
559 QualType DeducedType;
560 };
561 } // namespace
562
getDeducedType(ASTContext & ASTCtx,SourceLocation Loc)563 llvm::Optional<QualType> getDeducedType(ASTContext &ASTCtx,
564 SourceLocation Loc) {
565 if (!Loc.isValid())
566 return {};
567 DeducedTypeVisitor V(Loc);
568 V.TraverseAST(ASTCtx);
569 if (V.DeducedType.isNull())
570 return llvm::None;
571 return V.DeducedType;
572 }
573
getContainedAutoParamType(TypeLoc TL)574 TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL) {
575 if (auto QTL = TL.getAs<QualifiedTypeLoc>())
576 return getContainedAutoParamType(QTL.getUnqualifiedLoc());
577 if (llvm::isa<PointerType, ReferenceType, ParenType>(TL.getTypePtr()))
578 return getContainedAutoParamType(TL.getNextTypeLoc());
579 if (auto FTL = TL.getAs<FunctionTypeLoc>())
580 return getContainedAutoParamType(FTL.getReturnLoc());
581 if (auto TTPTL = TL.getAs<TemplateTypeParmTypeLoc>()) {
582 if (TTPTL.getTypePtr()->getDecl()->isImplicit())
583 return TTPTL;
584 }
585 return {};
586 }
587
588 template <typename TemplateDeclTy>
getOnlyInstantiationImpl(TemplateDeclTy * TD)589 static NamedDecl *getOnlyInstantiationImpl(TemplateDeclTy *TD) {
590 NamedDecl *Only = nullptr;
591 for (auto *Spec : TD->specializations()) {
592 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
593 continue;
594 if (Only != nullptr)
595 return nullptr;
596 Only = Spec;
597 }
598 return Only;
599 }
600
getOnlyInstantiation(NamedDecl * TemplatedDecl)601 NamedDecl *getOnlyInstantiation(NamedDecl *TemplatedDecl) {
602 if (TemplateDecl *TD = TemplatedDecl->getDescribedTemplate()) {
603 if (auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(TD))
604 return getOnlyInstantiationImpl(CTD);
605 if (auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(TD))
606 return getOnlyInstantiationImpl(FTD);
607 if (auto *VTD = llvm::dyn_cast<VarTemplateDecl>(TD))
608 return getOnlyInstantiationImpl(VTD);
609 }
610 return nullptr;
611 }
612
getAttributes(const DynTypedNode & N)613 std::vector<const Attr *> getAttributes(const DynTypedNode &N) {
614 std::vector<const Attr *> Result;
615 if (const auto *TL = N.get<TypeLoc>()) {
616 for (AttributedTypeLoc ATL = TL->getAs<AttributedTypeLoc>(); !ATL.isNull();
617 ATL = ATL.getModifiedLoc().getAs<AttributedTypeLoc>()) {
618 if (const Attr *A = ATL.getAttr())
619 Result.push_back(A);
620 assert(!ATL.getModifiedLoc().isNull());
621 }
622 }
623 if (const auto *S = N.get<AttributedStmt>()) {
624 for (; S != nullptr; S = dyn_cast<AttributedStmt>(S->getSubStmt()))
625 for (const Attr *A : S->getAttrs())
626 if (A)
627 Result.push_back(A);
628 }
629 if (const auto *D = N.get<Decl>()) {
630 for (const Attr *A : D->attrs())
631 if (A)
632 Result.push_back(A);
633 }
634 return Result;
635 }
636
getQualification(ASTContext & Context,const DeclContext * DestContext,SourceLocation InsertionPoint,const NamedDecl * ND)637 std::string getQualification(ASTContext &Context,
638 const DeclContext *DestContext,
639 SourceLocation InsertionPoint,
640 const NamedDecl *ND) {
641 auto VisibleNamespaceDecls =
642 getUsingNamespaceDirectives(DestContext, InsertionPoint);
643 return getQualification(
644 Context, DestContext, ND->getDeclContext(),
645 [&](NestedNameSpecifier *NNS) {
646 if (NNS->getKind() != NestedNameSpecifier::Namespace)
647 return false;
648 const auto *CanonNSD = NNS->getAsNamespace()->getCanonicalDecl();
649 return llvm::any_of(VisibleNamespaceDecls,
650 [CanonNSD](const NamespaceDecl *NSD) {
651 return NSD->getCanonicalDecl() == CanonNSD;
652 });
653 });
654 }
655
getQualification(ASTContext & Context,const DeclContext * DestContext,const NamedDecl * ND,llvm::ArrayRef<std::string> VisibleNamespaces)656 std::string getQualification(ASTContext &Context,
657 const DeclContext *DestContext,
658 const NamedDecl *ND,
659 llvm::ArrayRef<std::string> VisibleNamespaces) {
660 for (llvm::StringRef NS : VisibleNamespaces) {
661 assert(NS.endswith("::"));
662 (void)NS;
663 }
664 return getQualification(
665 Context, DestContext, ND->getDeclContext(),
666 [&](NestedNameSpecifier *NNS) {
667 return llvm::any_of(VisibleNamespaces, [&](llvm::StringRef Namespace) {
668 std::string NS;
669 llvm::raw_string_ostream OS(NS);
670 NNS->print(OS, Context.getPrintingPolicy());
671 return OS.str() == Namespace;
672 });
673 });
674 }
675
hasUnstableLinkage(const Decl * D)676 bool hasUnstableLinkage(const Decl *D) {
677 // Linkage of a ValueDecl depends on the type.
678 // If that's not deduced yet, deducing it may change the linkage.
679 auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
680 return VD && !VD->getType().isNull() && VD->getType()->isUndeducedType();
681 }
682
isDeeplyNested(const Decl * D,unsigned MaxDepth)683 bool isDeeplyNested(const Decl *D, unsigned MaxDepth) {
684 size_t ContextDepth = 0;
685 for (auto *Ctx = D->getDeclContext(); Ctx && !Ctx->isTranslationUnit();
686 Ctx = Ctx->getParent()) {
687 if (++ContextDepth == MaxDepth)
688 return true;
689 }
690 return false;
691 }
692
693 namespace {
694
695 // returns true for `X` in `template <typename... X> void foo()`
isTemplateTypeParameterPack(NamedDecl * D)696 bool isTemplateTypeParameterPack(NamedDecl *D) {
697 if (const auto *TTPD = dyn_cast<TemplateTypeParmDecl>(D)) {
698 return TTPD->isParameterPack();
699 }
700 return false;
701 }
702
703 // Returns the template parameter pack type from an instantiated function
704 // template, if it exists, nullptr otherwise.
getFunctionPackType(const FunctionDecl * Callee)705 const TemplateTypeParmType *getFunctionPackType(const FunctionDecl *Callee) {
706 if (const auto *TemplateDecl = Callee->getPrimaryTemplate()) {
707 auto TemplateParams = TemplateDecl->getTemplateParameters()->asArray();
708 // find the template parameter pack from the back
709 const auto It = std::find_if(TemplateParams.rbegin(), TemplateParams.rend(),
710 isTemplateTypeParameterPack);
711 if (It != TemplateParams.rend()) {
712 const auto *TTPD = dyn_cast<TemplateTypeParmDecl>(*It);
713 return TTPD->getTypeForDecl()->castAs<TemplateTypeParmType>();
714 }
715 }
716 return nullptr;
717 }
718
719 // Returns the template parameter pack type that this parameter was expanded
720 // from (if in the Args... or Args&... or Args&&... form), if this is the case,
721 // nullptr otherwise.
getUnderylingPackType(const ParmVarDecl * Param)722 const TemplateTypeParmType *getUnderylingPackType(const ParmVarDecl *Param) {
723 const auto *PlainType = Param->getType().getTypePtr();
724 if (auto *RT = dyn_cast<ReferenceType>(PlainType))
725 PlainType = RT->getPointeeTypeAsWritten().getTypePtr();
726 if (const auto *SubstType = dyn_cast<SubstTemplateTypeParmType>(PlainType)) {
727 const auto *ReplacedParameter = SubstType->getReplacedParameter();
728 if (ReplacedParameter->isParameterPack()) {
729 return dyn_cast<TemplateTypeParmType>(
730 ReplacedParameter->getCanonicalTypeUnqualified()->getTypePtr());
731 }
732 }
733 return nullptr;
734 }
735
736 // This visitor walks over the body of an instantiated function template.
737 // The template accepts a parameter pack and the visitor records whether
738 // the pack parameters were forwarded to another call. For example, given:
739 //
740 // template <typename T, typename... Args>
741 // auto make_unique(Args... args) {
742 // return unique_ptr<T>(new T(args...));
743 // }
744 //
745 // When called as `make_unique<std::string>(2, 'x')` this yields a function
746 // `make_unique<std::string, int, char>` with two parameters.
747 // The visitor records that those two parameters are forwarded to the
748 // `constructor std::string(int, char);`.
749 //
750 // This information is recorded in the `ForwardingInfo` split into fully
751 // resolved parameters (passed as argument to a parameter that is not an
752 // expanded template type parameter pack) and forwarding parameters (passed to a
753 // parameter that is an expanded template type parameter pack).
754 class ForwardingCallVisitor
755 : public RecursiveASTVisitor<ForwardingCallVisitor> {
756 public:
ForwardingCallVisitor(ArrayRef<const ParmVarDecl * > Parameters)757 ForwardingCallVisitor(ArrayRef<const ParmVarDecl *> Parameters)
758 : Parameters{Parameters}, PackType{getUnderylingPackType(
759 Parameters.front())} {}
760
VisitCallExpr(CallExpr * E)761 bool VisitCallExpr(CallExpr *E) {
762 auto *Callee = getCalleeDeclOrUniqueOverload(E);
763 if (Callee) {
764 handleCall(Callee, E->arguments());
765 }
766 return !Info.has_value();
767 }
768
VisitCXXConstructExpr(CXXConstructExpr * E)769 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
770 auto *Callee = E->getConstructor();
771 if (Callee) {
772 handleCall(Callee, E->arguments());
773 }
774 return !Info.has_value();
775 }
776
777 // The expanded parameter pack to be resolved
778 ArrayRef<const ParmVarDecl *> Parameters;
779 // The type of the parameter pack
780 const TemplateTypeParmType *PackType;
781
782 struct ForwardingInfo {
783 // If the parameters were resolved to another FunctionDecl, these are its
784 // first non-variadic parameters (i.e. the first entries of the parameter
785 // pack that are passed as arguments bound to a non-pack parameter.)
786 ArrayRef<const ParmVarDecl *> Head;
787 // If the parameters were resolved to another FunctionDecl, these are its
788 // variadic parameters (i.e. the entries of the parameter pack that are
789 // passed as arguments bound to a pack parameter.)
790 ArrayRef<const ParmVarDecl *> Pack;
791 // If the parameters were resolved to another FunctionDecl, these are its
792 // last non-variadic parameters (i.e. the last entries of the parameter pack
793 // that are passed as arguments bound to a non-pack parameter.)
794 ArrayRef<const ParmVarDecl *> Tail;
795 // If the parameters were resolved to another forwarding FunctionDecl, this
796 // is it.
797 Optional<FunctionDecl *> PackTarget;
798 };
799
800 // The output of this visitor
801 Optional<ForwardingInfo> Info;
802
803 private:
804 // inspects the given callee with the given args to check whether it
805 // contains Parameters, and sets Info accordingly.
handleCall(FunctionDecl * Callee,typename CallExpr::arg_range Args)806 void handleCall(FunctionDecl *Callee, typename CallExpr::arg_range Args) {
807 // Skip functions with less parameters, they can't be the target.
808 if (Callee->parameters().size() < Parameters.size())
809 return;
810 if (std::any_of(Args.begin(), Args.end(), [](const Expr *E) {
811 return dyn_cast<PackExpansionExpr>(E) != nullptr;
812 })) {
813 return;
814 }
815 auto PackLocation = findPack(Args);
816 if (!PackLocation)
817 return;
818 ArrayRef<ParmVarDecl *> MatchingParams =
819 Callee->parameters().slice(*PackLocation, Parameters.size());
820 // Check whether the function has a parameter pack as the last template
821 // parameter
822 if (const auto *TTPT = getFunctionPackType(Callee)) {
823 // In this case: Separate the parameters into head, pack and tail
824 auto IsExpandedPack = [&](const ParmVarDecl *P) {
825 return getUnderylingPackType(P) == TTPT;
826 };
827 ForwardingInfo FI;
828 FI.Head = MatchingParams.take_until(IsExpandedPack);
829 FI.Pack =
830 MatchingParams.drop_front(FI.Head.size()).take_while(IsExpandedPack);
831 FI.Tail = MatchingParams.drop_front(FI.Head.size() + FI.Pack.size());
832 FI.PackTarget = Callee;
833 Info = FI;
834 return;
835 }
836 // Default case: assume all parameters were fully resolved
837 ForwardingInfo FI;
838 FI.Head = MatchingParams;
839 Info = FI;
840 }
841
842 // Returns the beginning of the expanded pack represented by Parameters
843 // in the given arguments, if it is there.
findPack(typename CallExpr::arg_range Args)844 llvm::Optional<size_t> findPack(typename CallExpr::arg_range Args) {
845 // find the argument directly referring to the first parameter
846 assert(Parameters.size() <= static_cast<size_t>(llvm::size(Args)));
847 for (auto Begin = Args.begin(), End = Args.end() - Parameters.size() + 1;
848 Begin != End; ++Begin) {
849 if (const auto *RefArg = unwrapForward(*Begin)) {
850 if (Parameters.front() != RefArg->getDecl())
851 continue;
852 // Check that this expands all the way until the last parameter.
853 // It's enough to look at the last parameter, because it isn't possible
854 // to expand without expanding all of them.
855 auto ParamEnd = Begin + Parameters.size() - 1;
856 RefArg = unwrapForward(*ParamEnd);
857 if (!RefArg || Parameters.back() != RefArg->getDecl())
858 continue;
859 return std::distance(Args.begin(), Begin);
860 }
861 }
862 return llvm::None;
863 }
864
getCalleeDeclOrUniqueOverload(CallExpr * E)865 static FunctionDecl *getCalleeDeclOrUniqueOverload(CallExpr *E) {
866 Decl *CalleeDecl = E->getCalleeDecl();
867 auto *Callee = dyn_cast_or_null<FunctionDecl>(CalleeDecl);
868 if (!Callee) {
869 if (auto *Lookup = dyn_cast<UnresolvedLookupExpr>(E->getCallee())) {
870 Callee = resolveOverload(Lookup, E);
871 }
872 }
873 // Ignore the callee if the number of arguments is wrong (deal with va_args)
874 if (Callee && Callee->getNumParams() == E->getNumArgs())
875 return Callee;
876 return nullptr;
877 }
878
resolveOverload(UnresolvedLookupExpr * Lookup,CallExpr * E)879 static FunctionDecl *resolveOverload(UnresolvedLookupExpr *Lookup,
880 CallExpr *E) {
881 FunctionDecl *MatchingDecl = nullptr;
882 if (!Lookup->requiresADL()) {
883 // Check whether there is a single overload with this number of
884 // parameters
885 for (auto *Candidate : Lookup->decls()) {
886 if (auto *FuncCandidate = dyn_cast_or_null<FunctionDecl>(Candidate)) {
887 if (FuncCandidate->getNumParams() == E->getNumArgs()) {
888 if (MatchingDecl) {
889 // there are multiple candidates - abort
890 return nullptr;
891 }
892 MatchingDecl = FuncCandidate;
893 }
894 }
895 }
896 }
897 return MatchingDecl;
898 }
899
900 // Tries to get to the underlying argument by unwrapping implicit nodes and
901 // std::forward.
unwrapForward(const Expr * E)902 static const DeclRefExpr *unwrapForward(const Expr *E) {
903 E = E->IgnoreImplicitAsWritten();
904 // There might be an implicit copy/move constructor call on top of the
905 // forwarded arg.
906 // FIXME: Maybe mark implicit calls in the AST to properly filter here.
907 if (const auto *Const = dyn_cast<CXXConstructExpr>(E))
908 if (Const->getConstructor()->isCopyOrMoveConstructor())
909 E = Const->getArg(0)->IgnoreImplicitAsWritten();
910 if (const auto *Call = dyn_cast<CallExpr>(E)) {
911 const auto Callee = Call->getBuiltinCallee();
912 if (Callee == Builtin::BIforward) {
913 return dyn_cast<DeclRefExpr>(
914 Call->getArg(0)->IgnoreImplicitAsWritten());
915 }
916 }
917 return dyn_cast<DeclRefExpr>(E);
918 }
919 };
920
921 } // namespace
922
923 SmallVector<const ParmVarDecl *>
resolveForwardingParameters(const FunctionDecl * D,unsigned MaxDepth)924 resolveForwardingParameters(const FunctionDecl *D, unsigned MaxDepth) {
925 auto Parameters = D->parameters();
926 // If the function has a template parameter pack
927 if (const auto *TTPT = getFunctionPackType(D)) {
928 // Split the parameters into head, pack and tail
929 auto IsExpandedPack = [TTPT](const ParmVarDecl *P) {
930 return getUnderylingPackType(P) == TTPT;
931 };
932 ArrayRef<const ParmVarDecl *> Head = Parameters.take_until(IsExpandedPack);
933 ArrayRef<const ParmVarDecl *> Pack =
934 Parameters.drop_front(Head.size()).take_while(IsExpandedPack);
935 ArrayRef<const ParmVarDecl *> Tail =
936 Parameters.drop_front(Head.size() + Pack.size());
937 SmallVector<const ParmVarDecl *> Result(Parameters.size());
938 // Fill in non-pack parameters
939 auto HeadIt = std::copy(Head.begin(), Head.end(), Result.begin());
940 auto TailIt = std::copy(Tail.rbegin(), Tail.rend(), Result.rbegin());
941 // Recurse on pack parameters
942 size_t Depth = 0;
943 const FunctionDecl *CurrentFunction = D;
944 llvm::SmallSet<const FunctionTemplateDecl *, 4> SeenTemplates;
945 if (const auto *Template = D->getPrimaryTemplate()) {
946 SeenTemplates.insert(Template);
947 }
948 while (!Pack.empty() && CurrentFunction && Depth < MaxDepth) {
949 // Find call expressions involving the pack
950 ForwardingCallVisitor V{Pack};
951 V.TraverseStmt(CurrentFunction->getBody());
952 if (!V.Info) {
953 break;
954 }
955 // If we found something: Fill in non-pack parameters
956 auto Info = V.Info.value();
957 HeadIt = std::copy(Info.Head.begin(), Info.Head.end(), HeadIt);
958 TailIt = std::copy(Info.Tail.rbegin(), Info.Tail.rend(), TailIt);
959 // Prepare next recursion level
960 Pack = Info.Pack;
961 CurrentFunction = Info.PackTarget.value_or(nullptr);
962 Depth++;
963 // If we are recursing into a previously encountered function: Abort
964 if (CurrentFunction) {
965 if (const auto *Template = CurrentFunction->getPrimaryTemplate()) {
966 bool NewFunction = SeenTemplates.insert(Template).second;
967 if (!NewFunction) {
968 return {Parameters.begin(), Parameters.end()};
969 }
970 }
971 }
972 }
973 // Fill in the remaining unresolved pack parameters
974 HeadIt = std::copy(Pack.begin(), Pack.end(), HeadIt);
975 assert(TailIt.base() == HeadIt);
976 return Result;
977 }
978 return {Parameters.begin(), Parameters.end()};
979 }
980
isExpandedFromParameterPack(const ParmVarDecl * D)981 bool isExpandedFromParameterPack(const ParmVarDecl *D) {
982 return getUnderylingPackType(D) != nullptr;
983 }
984
985 } // namespace clangd
986 } // namespace clang
987