xref: /llvm-project/clang/unittests/AST/DeclTest.cpp (revision dcbbdbe3e50214b550383510ba05d059dc38496a)
1 //===- unittests/AST/DeclTest.cpp --- Declaration tests -------------------===//
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 // Unit tests for Decl nodes in the AST.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Mangle.h"
16 #include "clang/ASTMatchers/ASTMatchFinder.h"
17 #include "clang/ASTMatchers/ASTMatchers.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Lex/Lexer.h"
21 #include "clang/Tooling/Tooling.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/Testing/Annotations/Annotations.h"
24 #include "gtest/gtest.h"
25 
26 using namespace clang::ast_matchers;
27 using namespace clang::tooling;
28 using namespace clang;
29 
30 TEST(Decl, CleansUpAPValues) {
31   MatchFinder Finder;
32   std::unique_ptr<FrontendActionFactory> Factory(
33       newFrontendActionFactory(&Finder));
34 
35   // This is a regression test for a memory leak in APValues for structs that
36   // allocate memory. This test only fails if run under valgrind with full leak
37   // checking enabled.
38   std::vector<std::string> Args(1, "-std=c++11");
39   Args.push_back("-fno-ms-extensions");
40   ASSERT_TRUE(runToolOnCodeWithArgs(
41       Factory->create(),
42       "struct X { int a; }; constexpr X x = { 42 };"
43       "union Y { constexpr Y(int a) : a(a) {} int a; }; constexpr Y y = { 42 };"
44       "constexpr int z[2] = { 42, 43 };"
45       "constexpr int __attribute__((vector_size(16))) v1 = {};"
46       "\n#ifdef __SIZEOF_INT128__\n"
47       "constexpr __uint128_t large_int = 0xffffffffffffffff;"
48       "constexpr __uint128_t small_int = 1;"
49       "\n#endif\n"
50       "constexpr double d1 = 42.42;"
51       "constexpr long double d2 = 42.42;"
52       "constexpr _Complex long double c1 = 42.0i;"
53       "constexpr _Complex long double c2 = 42.0;"
54       "template<int N> struct A : A<N-1> {};"
55       "template<> struct A<0> { int n; }; A<50> a;"
56       "constexpr int &r = a.n;"
57       "constexpr int A<50>::*p = &A<50>::n;"
58       "void f() { foo: bar: constexpr int k = __builtin_constant_p(0) ?"
59       "                         (char*)&&foo - (char*)&&bar : 0; }",
60       Args));
61 
62   // FIXME: Once this test starts breaking we can test APValue::needsCleanup
63   // for ComplexInt.
64   ASSERT_FALSE(runToolOnCodeWithArgs(
65       Factory->create(),
66       "constexpr _Complex __uint128_t c = 0xffffffffffffffff;",
67       Args));
68 }
69 
70 TEST(Decl, AsmLabelAttr) {
71   // Create two method decls: `f` and `g`.
72   StringRef Code = R"(
73     struct S {
74       void f() {}
75       void g() {}
76     };
77   )";
78   auto AST =
79       tooling::buildASTFromCodeWithArgs(Code, {"-target", "i386-apple-darwin"});
80   ASTContext &Ctx = AST->getASTContext();
81   assert(Ctx.getTargetInfo().getUserLabelPrefix() == StringRef("_") &&
82          "Expected target to have a global prefix");
83   DiagnosticsEngine &Diags = AST->getDiagnostics();
84 
85   const auto *DeclS =
86       selectFirst<CXXRecordDecl>("d", match(cxxRecordDecl().bind("d"), Ctx));
87   NamedDecl *DeclF = *DeclS->method_begin();
88   NamedDecl *DeclG = *(++DeclS->method_begin());
89 
90   // Attach asm labels to the decls: one literal, and one not.
91   DeclF->addAttr(AsmLabelAttr::Create(Ctx, "foo", /*LiteralLabel=*/true));
92   DeclG->addAttr(AsmLabelAttr::Create(Ctx, "goo", /*LiteralLabel=*/false));
93 
94   // Mangle the decl names.
95   std::string MangleF, MangleG;
96   std::unique_ptr<ItaniumMangleContext> MC(
97       ItaniumMangleContext::create(Ctx, Diags));
98   {
99     llvm::raw_string_ostream OS_F(MangleF);
100     llvm::raw_string_ostream OS_G(MangleG);
101     MC->mangleName(DeclF, OS_F);
102     MC->mangleName(DeclG, OS_G);
103   }
104 
105   ASSERT_TRUE(0 == MangleF.compare("\x01" "foo"));
106   ASSERT_TRUE(0 == MangleG.compare("goo"));
107 }
108 
109 TEST(Decl, MangleDependentSizedArray) {
110   StringRef Code = R"(
111     template <int ...N>
112     int A[] = {N...};
113 
114     template <typename T, int N>
115     struct S {
116       T B[N];
117     };
118   )";
119   auto AST =
120       tooling::buildASTFromCodeWithArgs(Code, {"-target", "i386-apple-darwin"});
121   ASTContext &Ctx = AST->getASTContext();
122   assert(Ctx.getTargetInfo().getUserLabelPrefix() == StringRef("_") &&
123          "Expected target to have a global prefix");
124   DiagnosticsEngine &Diags = AST->getDiagnostics();
125 
126   const auto *DeclA =
127       selectFirst<VarDecl>("A", match(varDecl().bind("A"), Ctx));
128   const auto *DeclB =
129       selectFirst<FieldDecl>("B", match(fieldDecl().bind("B"), Ctx));
130 
131   std::string MangleA, MangleB;
132   llvm::raw_string_ostream OS_A(MangleA), OS_B(MangleB);
133   std::unique_ptr<ItaniumMangleContext> MC(
134       ItaniumMangleContext::create(Ctx, Diags));
135 
136   MC->mangleTypeName(DeclA->getType(), OS_A);
137   MC->mangleTypeName(DeclB->getType(), OS_B);
138 
139   ASSERT_TRUE(0 == MangleA.compare("_ZTSA_i"));
140   ASSERT_TRUE(0 == MangleB.compare("_ZTSAT0__T_"));
141 }
142 
143 TEST(Decl, EnumDeclRange) {
144   llvm::Annotations Code(R"(
145     typedef int Foo;
146     [[enum Bar : Foo]];)");
147   auto AST = tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{});
148   ASTContext &Ctx = AST->getASTContext();
149   const auto &SM = Ctx.getSourceManager();
150 
151   const auto *Bar =
152       selectFirst<TagDecl>("Bar", match(enumDecl().bind("Bar"), Ctx));
153   auto BarRange =
154       Lexer::getAsCharRange(Bar->getSourceRange(), SM, Ctx.getLangOpts());
155   EXPECT_EQ(SM.getFileOffset(BarRange.getBegin()), Code.range().Begin);
156   EXPECT_EQ(SM.getFileOffset(BarRange.getEnd()), Code.range().End);
157 }
158 
159 TEST(Decl, IsInExportDeclContext) {
160   llvm::Annotations Code(R"(
161     export module m;
162     export template <class T>
163     void f() {})");
164   auto AST =
165       tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{"-std=c++20"});
166   ASTContext &Ctx = AST->getASTContext();
167 
168   const auto *f =
169       selectFirst<FunctionDecl>("f", match(functionDecl().bind("f"), Ctx));
170   EXPECT_TRUE(f->isInExportDeclContext());
171 }
172 
173 TEST(Decl, InConsistLinkageForTemplates) {
174   llvm::Annotations Code(R"(
175     export module m;
176     export template <class T>
177     void f() {}
178 
179     template <>
180     void f<int>() {}
181 
182     export template <class T>
183     class C {};
184 
185     template<>
186     class C<int> {};
187     )");
188 
189   auto AST =
190       tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{"-std=c++20"});
191   ASTContext &Ctx = AST->getASTContext();
192 
193   llvm::SmallVector<ast_matchers::BoundNodes, 2> Funcs =
194       match(functionDecl().bind("f"), Ctx);
195 
196   EXPECT_EQ(Funcs.size(), 2U);
197   const FunctionDecl *TemplateF = Funcs[0].getNodeAs<FunctionDecl>("f");
198   const FunctionDecl *SpecializedF = Funcs[1].getNodeAs<FunctionDecl>("f");
199   EXPECT_EQ(TemplateF->getLinkageInternal(),
200             SpecializedF->getLinkageInternal());
201 
202   llvm::SmallVector<ast_matchers::BoundNodes, 1> ClassTemplates =
203       match(classTemplateDecl().bind("C"), Ctx);
204   llvm::SmallVector<ast_matchers::BoundNodes, 1> ClassSpecializations =
205       match(classTemplateSpecializationDecl().bind("C"), Ctx);
206 
207   EXPECT_EQ(ClassTemplates.size(), 1U);
208   EXPECT_EQ(ClassSpecializations.size(), 1U);
209   const NamedDecl *TemplatedC = ClassTemplates[0].getNodeAs<NamedDecl>("C");
210   const NamedDecl *SpecializedC = ClassSpecializations[0].getNodeAs<NamedDecl>("C");
211   EXPECT_EQ(TemplatedC->getLinkageInternal(),
212             SpecializedC->getLinkageInternal());
213 }
214 
215 TEST(Decl, ModuleAndInternalLinkage) {
216   llvm::Annotations Code(R"(
217     export module M;
218     static int a;
219     static int f(int x);
220 
221     int b;
222     int g(int x);)");
223 
224   auto AST =
225       tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{"-std=c++20"});
226   ASTContext &Ctx = AST->getASTContext();
227 
228   const auto *a =
229       selectFirst<VarDecl>("a", match(varDecl(hasName("a")).bind("a"), Ctx));
230   const auto *f = selectFirst<FunctionDecl>(
231       "f", match(functionDecl(hasName("f")).bind("f"), Ctx));
232 
233   EXPECT_EQ(a->getFormalLinkage(), InternalLinkage);
234   EXPECT_EQ(f->getFormalLinkage(), InternalLinkage);
235 
236   const auto *b =
237       selectFirst<VarDecl>("b", match(varDecl(hasName("b")).bind("b"), Ctx));
238   const auto *g = selectFirst<FunctionDecl>(
239       "g", match(functionDecl(hasName("g")).bind("g"), Ctx));
240 
241   EXPECT_EQ(b->getFormalLinkage(), ModuleLinkage);
242   EXPECT_EQ(g->getFormalLinkage(), ModuleLinkage);
243 }
244 
245 TEST(Decl, GetNonTransparentDeclContext) {
246   llvm::Annotations Code(R"(
247     export module m3;
248     export template <class> struct X {
249       template <class Self> friend void f(Self &&self) {
250         (Self&)self;
251       }
252     };)");
253 
254   auto AST =
255       tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{"-std=c++20"});
256   ASTContext &Ctx = AST->getASTContext();
257 
258   auto *f = selectFirst<FunctionDecl>(
259       "f", match(functionDecl(hasName("f")).bind("f"), Ctx));
260 
261   EXPECT_TRUE(f->getNonTransparentDeclContext()->isFileContext());
262 }
263 
264 TEST(Decl, MemberFunctionInModules) {
265   llvm::Annotations Code(R"(
266     module;
267     class G {
268       void bar() {}
269     };
270     export module M;
271     class A {
272       void foo() {}
273     };
274     )");
275 
276   auto AST =
277       tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{"-std=c++20"});
278   ASTContext &Ctx = AST->getASTContext();
279 
280   auto *foo = selectFirst<FunctionDecl>(
281       "foo", match(functionDecl(hasName("foo")).bind("foo"), Ctx));
282 
283   // The function defined within a class definition is not implicitly inline
284   // if it is not attached to global module
285   EXPECT_FALSE(foo->isInlined());
286 
287   auto *bar = selectFirst<FunctionDecl>(
288       "bar", match(functionDecl(hasName("bar")).bind("bar"), Ctx));
289 
290   // In global module, the function defined within a class definition is
291   // implicitly inline.
292   EXPECT_TRUE(bar->isInlined());
293 }
294 
295 TEST(Decl, MemberFunctionInHeaderUnit) {
296   llvm::Annotations Code(R"(
297     class foo {
298     public:
299       int memFn() {
300         return 43;
301       }
302     };
303     )");
304 
305   auto AST = tooling::buildASTFromCodeWithArgs(
306       Code.code(), {"-std=c++20", " -xc++-user-header ", "-emit-header-unit"});
307   ASTContext &Ctx = AST->getASTContext();
308 
309   auto *memFn = selectFirst<FunctionDecl>(
310       "memFn", match(functionDecl(hasName("memFn")).bind("memFn"), Ctx));
311 
312   EXPECT_TRUE(memFn->isInlined());
313 }
314 
315 TEST(Decl, FriendFunctionWithinClassInHeaderUnit) {
316   llvm::Annotations Code(R"(
317     class foo {
318       int value;
319     public:
320       foo(int v) : value(v) {}
321 
322       friend int getFooValue(foo f) {
323         return f.value;
324       }
325     };
326     )");
327 
328   auto AST = tooling::buildASTFromCodeWithArgs(
329       Code.code(), {"-std=c++20", " -xc++-user-header ", "-emit-header-unit"});
330   ASTContext &Ctx = AST->getASTContext();
331 
332   auto *getFooValue = selectFirst<FunctionDecl>(
333       "getFooValue",
334       match(functionDecl(hasName("getFooValue")).bind("getFooValue"), Ctx));
335 
336   EXPECT_TRUE(getFooValue->isInlined());
337 }
338 
339 TEST(Decl, NoProtoFunctionDeclAttributes) {
340   llvm::Annotations Code(R"(
341     void f();
342     )");
343 
344   auto AST = tooling::buildASTFromCodeWithArgs(
345       Code.code(),
346       /*Args=*/{"-target", "i386-apple-darwin", "-x", "objective-c",
347                 "-std=c89"});
348   ASTContext &Ctx = AST->getASTContext();
349 
350   auto *f = selectFirst<FunctionDecl>(
351       "f", match(functionDecl(hasName("f")).bind("f"), Ctx));
352 
353   const auto *FPT = f->getType()->getAs<FunctionNoProtoType>();
354 
355   // Functions without prototypes always have 0 initialized qualifiers
356   EXPECT_FALSE(FPT->isConst());
357   EXPECT_FALSE(FPT->isVolatile());
358   EXPECT_FALSE(FPT->isRestrict());
359 }
360 
361 TEST(Decl, ImplicitlyDeclaredAllocationFunctionsInModules) {
362   // C++ [basic.stc.dynamic.general]p2:
363   //   The library provides default definitions for the global allocation
364   //   and deallocation functions. Some global allocation and deallocation
365   //   functions are replaceable ([new.delete]); these are attached to the
366   //   global module ([module.unit]).
367 
368   llvm::Annotations Code(R"(
369     export module base;
370 
371     export struct Base {
372         virtual void hello() = 0;
373         virtual ~Base() = default;
374     };
375   )");
376 
377   auto AST =
378       tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{"-std=c++20"});
379   ASTContext &Ctx = AST->getASTContext();
380 
381   // void* operator new(std::size_t);
382   auto *SizedOperatorNew = selectFirst<FunctionDecl>(
383       "operator new",
384       match(functionDecl(hasName("operator new"), parameterCountIs(1),
385                          hasParameter(0, hasType(isUnsignedInteger())))
386                 .bind("operator new"),
387             Ctx));
388   ASSERT_TRUE(SizedOperatorNew->getOwningModule());
389   EXPECT_TRUE(SizedOperatorNew->getOwningModule()->isGlobalModule());
390 
391   // void* operator new(std::size_t, std::align_val_t);
392   auto *SizedAlignedOperatorNew = selectFirst<FunctionDecl>(
393       "operator new",
394       match(functionDecl(
395                 hasName("operator new"), parameterCountIs(2),
396                 hasParameter(0, hasType(isUnsignedInteger())),
397                 hasParameter(1, hasType(enumDecl(hasName("std::align_val_t")))))
398                 .bind("operator new"),
399             Ctx));
400   ASSERT_TRUE(SizedAlignedOperatorNew->getOwningModule());
401   EXPECT_TRUE(SizedAlignedOperatorNew->getOwningModule()->isGlobalModule());
402 
403   // void* operator new[](std::size_t);
404   auto *SizedArrayOperatorNew = selectFirst<FunctionDecl>(
405       "operator new[]",
406       match(functionDecl(hasName("operator new[]"), parameterCountIs(1),
407                          hasParameter(0, hasType(isUnsignedInteger())))
408                 .bind("operator new[]"),
409             Ctx));
410   ASSERT_TRUE(SizedArrayOperatorNew->getOwningModule());
411   EXPECT_TRUE(SizedArrayOperatorNew->getOwningModule()->isGlobalModule());
412 
413   // void* operator new[](std::size_t, std::align_val_t);
414   auto *SizedAlignedArrayOperatorNew = selectFirst<FunctionDecl>(
415       "operator new[]",
416       match(functionDecl(
417                 hasName("operator new[]"), parameterCountIs(2),
418                 hasParameter(0, hasType(isUnsignedInteger())),
419                 hasParameter(1, hasType(enumDecl(hasName("std::align_val_t")))))
420                 .bind("operator new[]"),
421             Ctx));
422   ASSERT_TRUE(SizedAlignedArrayOperatorNew->getOwningModule());
423   EXPECT_TRUE(
424       SizedAlignedArrayOperatorNew->getOwningModule()->isGlobalModule());
425 
426   // void operator delete(void*) noexcept;
427   auto *Delete = selectFirst<FunctionDecl>(
428       "operator delete",
429       match(functionDecl(
430                 hasName("operator delete"), parameterCountIs(1),
431                 hasParameter(0, hasType(pointerType(pointee(voidType())))))
432                 .bind("operator delete"),
433             Ctx));
434   ASSERT_TRUE(Delete->getOwningModule());
435   EXPECT_TRUE(Delete->getOwningModule()->isGlobalModule());
436 
437   // void operator delete(void*, std::align_val_t) noexcept;
438   auto *AlignedDelete = selectFirst<FunctionDecl>(
439       "operator delete",
440       match(functionDecl(
441                 hasName("operator delete"), parameterCountIs(2),
442                 hasParameter(0, hasType(pointerType(pointee(voidType())))),
443                 hasParameter(1, hasType(enumDecl(hasName("std::align_val_t")))))
444                 .bind("operator delete"),
445             Ctx));
446   ASSERT_TRUE(AlignedDelete->getOwningModule());
447   EXPECT_TRUE(AlignedDelete->getOwningModule()->isGlobalModule());
448 
449   // Sized deallocation is not enabled by default. So we skip it here.
450 
451   // void operator delete[](void*) noexcept;
452   auto *ArrayDelete = selectFirst<FunctionDecl>(
453       "operator delete[]",
454       match(functionDecl(
455                 hasName("operator delete[]"), parameterCountIs(1),
456                 hasParameter(0, hasType(pointerType(pointee(voidType())))))
457                 .bind("operator delete[]"),
458             Ctx));
459   ASSERT_TRUE(ArrayDelete->getOwningModule());
460   EXPECT_TRUE(ArrayDelete->getOwningModule()->isGlobalModule());
461 
462   // void operator delete[](void*, std::align_val_t) noexcept;
463   auto *AlignedArrayDelete = selectFirst<FunctionDecl>(
464       "operator delete[]",
465       match(functionDecl(
466                 hasName("operator delete[]"), parameterCountIs(2),
467                 hasParameter(0, hasType(pointerType(pointee(voidType())))),
468                 hasParameter(1, hasType(enumDecl(hasName("std::align_val_t")))))
469                 .bind("operator delete[]"),
470             Ctx));
471   ASSERT_TRUE(AlignedArrayDelete->getOwningModule());
472   EXPECT_TRUE(AlignedArrayDelete->getOwningModule()->isGlobalModule());
473 }
474 
475 TEST(Decl, TemplateArgumentDefaulted) {
476   llvm::Annotations Code(R"cpp(
477     template<typename T1, typename T2>
478     struct Alloc {};
479 
480     template <typename T1,
481               typename T2 = double,
482               int      T3 = 42,
483               typename T4 = Alloc<T1, T2>>
484     struct Foo {
485     };
486 
487     Foo<char, int, 42, Alloc<char, int>> X;
488   )cpp");
489 
490   auto AST =
491       tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{"-std=c++20"});
492   ASTContext &Ctx = AST->getASTContext();
493 
494   auto const *CTSD = selectFirst<ClassTemplateSpecializationDecl>(
495       "id",
496       match(classTemplateSpecializationDecl(hasName("Foo")).bind("id"), Ctx));
497   ASSERT_NE(CTSD, nullptr);
498   auto const &ArgList = CTSD->getTemplateArgs();
499 
500   EXPECT_FALSE(ArgList.get(0).getIsDefaulted());
501   EXPECT_FALSE(ArgList.get(1).getIsDefaulted());
502   EXPECT_TRUE(ArgList.get(2).getIsDefaulted());
503   EXPECT_TRUE(ArgList.get(3).getIsDefaulted());
504 }
505