Debian Codegraph @

clang_delta/TemplateArgToInt.cpp

raw symbols SCIP
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2012, 2013, 2014, 2015, 2017, 2020 The University of Utah
4 // All rights reserved.
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See the file COPYING for details.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #if HAVE_CONFIG_H
12 # include <config.h>
13 #endif
14
15 #include "TemplateArgToInt.h"
16
17 #include "clang/Lex/Lexer.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/Basic/SourceManager.h"
21
22 #include "TransformationManager.h"
23 #include "CommonTemplateArgumentVisitor.h"
24
25 using namespace clang;
26 using namespace clang_delta_common_visitor;
27
28 static const char *DescriptionMsg =
29 "This pass replaces a template argument in an instantiation with \
30 int if the argument: \n\
31 * is type of CXXRecord; \n\
32 * the corresponding template parameter T is not used as T::x, \n\
33 nor template<typename T> class : T { ... };\n\
34 For example, from:\n\
35 struct S {};\n\
36 template <typename T> struct C {};\n\
37 C<S> c;\n\
38 to:\n\
39 struct S {};\n\
40 template <typename T> struct C {};\n\
41 C<int> c;\n\
42 ";
43
44 static RegisterTransformation<TemplateArgToInt>
45 Trans("template-arg-to-int", DescriptionMsg);
46
47 class TemplateArgToIntASTVisitor : public
48 RecursiveASTVisitor<TemplateArgToIntASTVisitor> {
49
50 public:
51 explicit TemplateArgToIntASTVisitor(
52 TemplateArgToInt *Instance)
53 : ConsumerInstance(Instance)
54 { }
55
56 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
57
58 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
59
60 private:
61 TemplateArgToInt *ConsumerInstance;
62
63 };
64
65 class TemplateArgToIntArgCollector : public
66 CommonTemplateArgumentVisitor<TemplateArgToIntArgCollector,
67 TemplateArgToInt> {
68
69 public:
70 explicit TemplateArgToIntArgCollector(TemplateArgToInt *Instance)
71 : CommonTemplateArgumentVisitor<TemplateArgToIntArgCollector,
72 TemplateArgToInt>(Instance)
73 { }
74 };
75
76 typedef llvm::SmallPtrSet<const NamedDecl *, 8> TemplateParameterSet;
77
78 // rule out cases like:
79 //template <typename T1> struct S { typedef T1 type; };
80 // struct S1 { void foo() {} };
81 // struct S2 {
82 // typedef S<S1>::type type;
83 // S<S1>::type s1;
84 // type s2;
85 // void bar() { s1.foo(); s2.foo(); }
86 // };
87 class TemplateGlobalInvalidParameterVisitor : public
88 RecursiveASTVisitor<TemplateGlobalInvalidParameterVisitor> {
89
90 public:
91 explicit TemplateGlobalInvalidParameterVisitor(
92 TemplateArgToInt *Instance)
93 : ConsumerInstance(Instance)
94 { }
95
96 ~TemplateGlobalInvalidParameterVisitor() { };
97
98 bool VisitMemberExpr(MemberExpr *ME);
99
100 bool VisitCXXRecordDecl(CXXRecordDecl *D);
101
102 private:
103 TemplateArgToInt *ConsumerInstance;
104 };
105
106 bool TemplateGlobalInvalidParameterVisitor::VisitMemberExpr(MemberExpr *ME)
107 {
108 const Expr *Base = ME->getBase();
109 if (dyn_cast<CXXThisExpr>(Base))
110 return true;
111
112 const Type *Ty = Base->getType().getTypePtr();
113 ConsumerInstance->handleOneType(Ty);
114 return true;
115 }
116
117 bool TemplateGlobalInvalidParameterVisitor::VisitCXXRecordDecl(CXXRecordDecl *D)
118 {
119 if (!D->isCompleteDefinition())
120 return true;
121 for (CXXRecordDecl::base_class_const_iterator I = D->bases_begin(),
122 E = D->bases_end(); I != E; ++I) {
123 const CXXBaseSpecifier *BS = I;
124 const Type *Ty = BS->getType().getTypePtr();
125 ConsumerInstance->handleOneType(Ty);
126 }
127 return true;
128 }
129
130 class TemplateInvalidParameterVisitor : public
131 RecursiveASTVisitor<TemplateInvalidParameterVisitor> {
132
133 public:
134 TemplateInvalidParameterVisitor(TemplateParameterSet &Params,
135 TemplateArgToInt *Instance)
136 : Parameters(Params),
137 ConsumerInstance(Instance)
138 { }
139
140 ~TemplateInvalidParameterVisitor() { };
141
142 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc Loc);
143
144 bool VisitCXXRecordDecl(CXXRecordDecl *D);
145
146 private:
147 TemplateParameterSet &Parameters;
148
149 TemplateArgToInt *ConsumerInstance;
150 };
151
152 bool TemplateInvalidParameterVisitor::VisitTemplateTypeParmTypeLoc(
153 TemplateTypeParmTypeLoc Loc)
154 {
155 const NamedDecl *ND = Loc.getDecl();
156 if (ConsumerInstance->isBeforeColonColon(Loc))
157 Parameters.insert(ND);
158
159 return true;
160 }
161
162 bool TemplateInvalidParameterVisitor::VisitCXXRecordDecl(CXXRecordDecl *D)
163 {
164 if (!D->isCompleteDefinition())
165 return true;
166 for (CXXRecordDecl::base_class_const_iterator I = D->bases_begin(),
167 E = D->bases_end(); I != E; ++I) {
168 const CXXBaseSpecifier *BS = I;
169 const Type *Ty = BS->getType().getTypePtr();
170 const TemplateTypeParmType *ParmTy = dyn_cast<TemplateTypeParmType>(Ty);
171 if (!ParmTy)
172 continue;
173 const TemplateTypeParmDecl *ParmD = ParmTy->getDecl();
174 Parameters.insert(ParmD);
175 }
176 return true;
177 }
178
179 bool TemplateArgToIntASTVisitor::VisitClassTemplateDecl(
180 ClassTemplateDecl *D)
181 {
182 if (D->isThisDeclarationADefinition())
183 ConsumerInstance->handleOneTemplateDecl(D);
184 return true;
185 }
186
187 bool TemplateArgToIntASTVisitor::VisitFunctionTemplateDecl(
188 FunctionTemplateDecl *D)
189 {
190 if (D->isThisDeclarationADefinition())
191 ConsumerInstance->handleOneTemplateDecl(D);
192 return true;
193 }
194
195 void TemplateArgToInt::Initialize(ASTContext &context)
196 {
197 Transformation::Initialize(context);
198 CollectionVisitor = new TemplateArgToIntASTVisitor(this);
199 ArgCollector = new TemplateArgToIntArgCollector(this);
200 GlobalParamFilter = new TemplateGlobalInvalidParameterVisitor(this);
201 }
202
203 void TemplateArgToInt::HandleTranslationUnit(ASTContext &Ctx)
204 {
205 if (TransformationManager::isCLangOpt() ||
206 TransformationManager::isOpenCLLangOpt()) {
207 ValidInstanceNum = 0;
208 }
209 else {
210 CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
211 GlobalParamFilter->TraverseDecl(Ctx.getTranslationUnitDecl());
212 ArgCollector->TraverseDecl(Ctx.getTranslationUnitDecl());
213 }
214
215 if (QueryInstanceOnly)
216 return;
217
218 if (TransformationCounter > ValidInstanceNum) {
219 TransError = TransMaxInstanceError;
220 return;
221 }
222
223 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
224 rewriteTemplateArgument();
225
226 if (Ctx.getDiagnostics().hasErrorOccurred() ||
227 Ctx.getDiagnostics().hasFatalErrorOccurred())
228 TransError = TransInternalError;
229 }
230
231 void TemplateArgToInt::collectInvalidParamIdx(
232 const TemplateDecl *D,
233 TemplateParameterIdxSet &InvalidParamIdx)
234 {
235 TemplateParameterSet InvalidParams;
236 NamedDecl *ND = D->getTemplatedDecl();
237 TemplateInvalidParameterVisitor ParameterVisitor(InvalidParams, this);
238 ParameterVisitor.TraverseDecl(ND);
239
240 TemplateParameterList *TPList = D->getTemplateParameters();
241 unsigned Idx = 0;
242 for (TemplateParameterList::const_iterator I = TPList->begin(),
243 E = TPList->end(); I != E; ++I) {
244 const NamedDecl *ParamND = (*I);
245 ParamToTemplateDecl[ParamND] = D;
246 if (InvalidParams.count(ParamND)) {
247 TransAssert(!InvalidParamIdx.count(Idx) && "Duplicate Index!");
248 InvalidParamIdx.insert(Idx);
249 }
250 Idx++;
251 }
252 }
253
254 void TemplateArgToInt::handleOneTemplateDecl(const TemplateDecl *D)
255 {
256 TemplateParameterIdxSet *InvalidIdx = new TemplateParameterIdxSet();
257 collectInvalidParamIdx(D, *InvalidIdx);
258 TransAssert(!DeclToParamIdx[D] && "Duplicate TemplateDecl!");
259 DeclToParamIdx[dyn_cast<TemplateDecl>(D->getCanonicalDecl())] = InvalidIdx;
260 }
261
262 void TemplateArgToInt::handleOneTemplateArgumentLoc(
263 const TemplateArgumentLoc &ArgLoc)
264 {
265 if (ArgLoc.getLocation().isInvalid() ||
266 isInIncludedFile(ArgLoc.getLocation()))
267 return;
268 const TemplateArgument &Arg = ArgLoc.getArgument();
269
270 if (Arg.getKind() != TemplateArgument::Type)
271 return;
272 const Type *Ty = Arg.getAsType().getTypePtr();
273 if (!Ty->getAsCXXRecordDecl() && !Ty->getPointeeCXXRecordDecl())
274 return;
275
276 ValidInstanceNum++;
277 if (ValidInstanceNum == TransformationCounter)
278 TheTypeSourceInfo = ArgLoc.getTypeSourceInfo();
279 }
280
281 void TemplateArgToInt::handleTemplateArgumentLocs(
282 const TemplateDecl *D, const TemplateArgumentLoc *TAL, unsigned NumArgs)
283 {
284 TransAssert(D && "NULL TemplateDecl!");
285 if (!TAL)
286 return;
287 TemplateParameterIdxSet *InvalidIdx =
288 DeclToParamIdx[dyn_cast<TemplateDecl>(D->getCanonicalDecl())];
289 if (!InvalidIdx)
290 return;
291 for (unsigned I = 0; I < NumArgs; ++I) {
292 if (!InvalidIdx->count(I))
293 handleOneTemplateArgumentLoc(TAL[I]);
294 }
295 }
296
297 void TemplateArgToInt::handleTemplateSpecializationTypeLoc(
298 const TemplateSpecializationTypeLoc &TLoc)
299 {
300 const Type *Ty = TLoc.getTypePtr();
301 const TemplateSpecializationType *TST =
302 Ty->getAs<TemplateSpecializationType>();
303 TemplateName TplName = TST->getTemplateName();
304 const TemplateDecl *TplD = TplName.getAsTemplateDecl();
305
306 TemplateParameterIdxSet *InvalidIdx =
307 DeclToParamIdx[dyn_cast<TemplateDecl>(TplD->getCanonicalDecl())];
308 if (!InvalidIdx)
309 return;
310 for (unsigned I = 0; I < TLoc.getNumArgs(); ++I) {
311 if (!InvalidIdx->count(I))
312 handleOneTemplateArgumentLoc(TLoc.getArgLoc(I));
313 }
314 }
315
316 void TemplateArgToInt::rewriteTemplateArgument()
317 {
318 TransAssert(TheTypeSourceInfo && "NULL TheTypeSourceInfo");
319 SourceRange Range = TheTypeSourceInfo->getTypeLoc().getSourceRange();
320 TheRewriter.ReplaceText(Range, "int");
321 }
322
323 const SubstTemplateTypeParmType *
324 TemplateArgToInt::getSubstTemplateTypeParmType(const Type *Ty)
325 {
326 Type::TypeClass TC = Ty->getTypeClass();
327 switch (TC) {
328 case Type::Elaborated: {
329 const ElaboratedType *ETy = dyn_cast<ElaboratedType>(Ty);
330 const Type *NamedT = ETy->getNamedType().getTypePtr();
331 return getSubstTemplateTypeParmType(NamedT);
332 }
333
334 case Type::Typedef: {
335 const TypedefType *TdefTy = dyn_cast<TypedefType>(Ty);
336 const TypedefNameDecl *TdefD = TdefTy->getDecl();
337 const Type *UnderlyingTy = TdefD->getUnderlyingType().getTypePtr();
338 return getSubstTemplateTypeParmType(UnderlyingTy);
339 }
340
341 case Type::SubstTemplateTypeParm: {
342 return dyn_cast<SubstTemplateTypeParmType>(Ty);
343 }
344
345 default:
346 return NULL;
347 }
348
349 return NULL;
350 }
351
352 void TemplateArgToInt::handleOneType(const Type *Ty)
353 {
354 if (Ty->isPointerType() || Ty->isReferenceType())
355 Ty = getBasePointerElemType(Ty);
356 const SubstTemplateTypeParmType *SubstType = getSubstTemplateTypeParmType(Ty);
357 if (!SubstType)
358 return;
359
360 const TemplateTypeParmDecl *ParmDecl = SubstType->getReplacedParameter();
361 TransAssert(ParmDecl && "Invalid ParmDecl!");
362 const TemplateDecl *TmplD = ParamToTemplateDecl[ParmDecl];
363 if (TmplD == NULL) {
364 const DeclContext *Ctx = ParmDecl->getDeclContext();
365 TransAssert(Ctx && "NULL Ctx!");
366 const ClassTemplateSpecializationDecl *Spec =
367 dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
368 TransAssert(Spec && "Not a ClassTemplateSpecializationDecl!");
369 TmplD = Spec->getSpecializedTemplate();
370 }
371 if (const ClassTemplateDecl *ClassTmplD =
372 dyn_cast<ClassTemplateDecl>(TmplD)) {
373 if (!ClassTmplD->getTemplatedDecl()->hasDefinition())
374 return;
375 }
376 if (const FunctionTemplateDecl *FuncTmplD =
377 dyn_cast<FunctionTemplateDecl>(TmplD)) {
378 if (!FuncTmplD->getTemplatedDecl()->getDefinition())
379 return;
380 }
381
382 TransAssert(TmplD && "NULL TemplateDecl!");
383 TemplateParameterIdxSet *InvalidIdx =
384 DeclToParamIdx[dyn_cast<TemplateDecl>(TmplD->getCanonicalDecl())];
385 TransAssert(InvalidIdx && "NULL InvalidIdx!");
386 InvalidIdx->insert(ParmDecl->getIndex());
387 }
388
389 TemplateArgToInt::~TemplateArgToInt()
390 {
391 for (TemplateDeclToParamIdxMap::iterator I = DeclToParamIdx.begin(),
392 E = DeclToParamIdx.end(); I != E; ++I) {
393 delete (*I).second;
394 }
395 delete CollectionVisitor;
396 delete ArgCollector;
397 delete GlobalParamFilter;
398 }
399