Debian Codegraph @

clang_delta/RenameCXXMethod.cpp

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2012, 2013, 2014, 2015, 2016, 2017, 2019 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 "RenameCXXMethod.h"
16
17 #include <sstream>
18
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/Basic/SourceManager.h"
22
23 #include "TransformationManager.h"
24
25 using namespace clang;
26
27 static const char *DescriptionMsg =
28 "Another pass to increase readability of reduced code. \
29 It renames CXX methods names to m_fn1, m_fn2, ...\n";
30
31 static RegisterTransformation<RenameCXXMethod>
32 Trans("rename-cxx-method", DescriptionMsg);
33
34 class RenameCXXMethodCollectionVisitor : public
35 RecursiveASTVisitor<RenameCXXMethodCollectionVisitor> {
36
37 public:
38
39 explicit RenameCXXMethodCollectionVisitor(RenameCXXMethod *Instance)
40 : ConsumerInstance(Instance)
41 { }
42
43 bool VisitCXXRecordDecl(CXXRecordDecl *FD);
44
45 bool VisitCXXMethodDecl(CXXMethodDecl *MD);
46
47 private:
48
49 RenameCXXMethod *ConsumerInstance;
50
51 };
52
53 // ISSUE:
54 // we can't handle the case below:
55 // struct A {
56 // int abc;
57 // static int test(int);
58 // enum {
59 // value = (1 == sizeof(test(abc)))
60 // };
61 // };
62 // The reason is that somehow expr (1== sizeof(test(abc)))
63 // is not presented in Clang's AST representation.
64 class RenameCXXMethodVisitor :
65 public RecursiveASTVisitor<RenameCXXMethodVisitor> {
66
67 public:
68
69 explicit RenameCXXMethodVisitor(RenameCXXMethod *Instance)
70 : ConsumerInstance(Instance)
71 { }
72
73 bool TraverseClassTemplateDecl(ClassTemplateDecl *D);
74
75 bool VisitCXXMethodDecl(CXXMethodDecl *MD);
76
77 bool VisitFunctionDecl(FunctionDecl *FD);
78
79 bool VisitCXXRecordDecl(CXXRecordDecl *FD);
80
81 bool VisitDeclRefExpr(DeclRefExpr *DRE);
82
83 bool VisitMemberExpr(MemberExpr *ME);
84
85 bool VisitCallExpr(CallExpr *CE);
86
87 // we have to enable visiting template instantiations, otherwise,
88 // we won't be able to see some explicit instantiation code, e.g.:
89 // template<typename T> class A {
90 // T* foo(T* __p) <--- foo would be missing
91 // { __p; }
92 // };
93 // extern template class basic_string<char>;
94 bool shouldVisitTemplateInstantiations() {
95 return true;
96 }
97
98 private:
99 void TraverseClassInstantiations(ClassTemplateDecl *D);
100
101 RenameCXXMethod *ConsumerInstance;
102 };
103
104 bool RenameCXXMethodCollectionVisitor::VisitCXXRecordDecl(CXXRecordDecl *RD)
105 {
106 if (ConsumerInstance->isInIncludedFile(RD) || !RD->hasDefinition())
107 return true;
108 const CXXRecordDecl *RDDef = RD->getDefinition();
109 ConsumerInstance->handleOneCXXRecordDecl(RDDef);
110 return true;
111 }
112
113 bool RenameCXXMethodCollectionVisitor::VisitCXXMethodDecl(CXXMethodDecl *MD)
114 {
115 if (ConsumerInstance->isInIncludedFile(MD))
116 return true;
117 const CXXMethodDecl *CanonicalMD = MD->getCanonicalDecl();
118 if(ConsumerInstance->NewMethodNames.find(CanonicalMD) !=
119 ConsumerInstance->NewMethodNames.end())
120 return true;
121
122 ConsumerInstance->handleOneMemberTemplateFunction(CanonicalMD);
123 return true;
124 }
125
126 bool RenameCXXMethodVisitor::VisitCXXRecordDecl(CXXRecordDecl *RD)
127 {
128 ConsumerInstance->setClassInstantiationFlag(RD);
129 ConsumerInstance->clearFunctionInstantiationFlag();
130 return true;
131 }
132
133 bool RenameCXXMethodVisitor::VisitFunctionDecl(FunctionDecl *FD)
134 {
135 ConsumerInstance->CurrentFD = FD;
136 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
137 if (!MD) {
138 ConsumerInstance->setFunctionInstantiationFlag(FD);
139 ConsumerInstance->clearClassInstantiationFlag();
140 }
141 return true;
142 }
143
144 void RenameCXXMethodVisitor::TraverseClassInstantiations(
145 ClassTemplateDecl *D)
146 {
147 for (ClassTemplateDecl::spec_iterator I = D->spec_begin(),
148 E = D->spec_end(); I != E; ++I) {
149 ClassTemplateSpecializationDecl* SpecD = (*I);
150
151 switch (SpecD->getSpecializationKind()) {
152 case TSK_Undeclared:
153 case TSK_ImplicitInstantiation:
154 // Keep track if we are inside class instantiations.
155 // We use a queue because we could have nested CXXRecord definition
156 // and implicit instantiations
157 ConsumerInstance->InstantiationQueue.push_back(SpecD);
158 TraverseDecl(SpecD);
159 ConsumerInstance->InstantiationQueue.pop_back();
160 break;
161
162 default:
163 // TSK_ExplicitInstantiationDeclaration:
164 // TSK_ExplicitInstantiationDefinition:
165 // TSK_ExplicitSpecialization:
166 break;
167 }
168 }
169 }
170
171 bool RenameCXXMethodVisitor::TraverseClassTemplateDecl(ClassTemplateDecl *D)
172 {
173 CXXRecordDecl* TmplDecl = D->getTemplatedDecl();
174 if (TmplDecl)
175 TraverseDecl(TmplDecl);
176 if (TemplateParameterList *TmplList = D->getTemplateParameters()) {
177 for (TemplateParameterList::iterator I = TmplList->begin(),
178 E = TmplList->end(); I != E; ++I) {
179 TraverseDecl(*I);
180 }
181 }
182
183 if (D != D->getCanonicalDecl())
184 return true;
185
186 TraverseClassInstantiations(D);
187 return true;
188 }
189
190 bool RenameCXXMethodVisitor::VisitCXXMethodDecl(CXXMethodDecl *MD)
191 {
192 if (ConsumerInstance->isSpecialCXXMethod(MD) ||
193 ConsumerInstance->isInIncludedFile(MD))
194 return true;
195
196 const CXXMethodDecl *CanonicalMD = MD->getCanonicalDecl();
197 llvm::DenseMap<const CXXMethodDecl *, std::string>::iterator I =
198 ConsumerInstance->NewMethodNames.find(CanonicalMD);
199 if (I != ConsumerInstance->NewMethodNames.end()) {
200 ConsumerInstance->RewriteHelper->replaceFunctionDeclName(MD, (*I).second);
201 return true;
202 }
203
204 TemplateSpecializationKind K = MD->getTemplateSpecializationKind();
205 if (const FunctionDecl *MemberFD = MD->getInstantiatedFromMemberFunction()) {
206 if (K != TSK_ExplicitSpecialization)
207 return true;
208 const CXXMethodDecl *MemberMD = dyn_cast<CXXMethodDecl>(MemberFD);
209 TransAssert(MemberMD && "Invalid Member FD!");
210
211 if (ConsumerInstance->VisitedSpecializedMethods.count(
212 MD->getCanonicalDecl()))
213 return true;
214
215 ConsumerInstance->VisitedSpecializedMethods.insert(
216 MD->getCanonicalDecl());
217 CanonicalMD = MemberMD->getCanonicalDecl();
218 I = ConsumerInstance->NewMethodNames.find(CanonicalMD);
219 TransAssert((I != ConsumerInstance->NewMethodNames.end()) &&
220 "Cannot find member function!");
221 ConsumerInstance->RewriteHelper->replaceFunctionDeclName(MD, (*I).second);
222 return true;
223 }
224
225 // only need to rewrite explicit instantiations
226 if ((K == TSK_ExplicitInstantiationDeclaration) ||
227 (K == TSK_ExplicitInstantiationDefinition)) {
228 ConsumerInstance->rewriteFunctionTemplateExplicitInstantiation(MD);
229 }
230
231 return true;
232 }
233
234 bool RenameCXXMethodVisitor::VisitDeclRefExpr(DeclRefExpr *DRE)
235 {
236 const ValueDecl *VD = DRE->getDecl();
237 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD);
238 if (!MD)
239 return true;
240
241 if (!ConsumerInstance->isExplicit(MD))
242 return true;
243
244 std::string NewName = "";
245 if (!ConsumerInstance->getMethodNewName(MD, NewName))
246 return true;
247 TransAssert((NewName != "") && "Bad new name!");
248
249 if (DRE->hasQualifier()) {
250 NestedNameSpecifierLoc QualLoc = DRE->getQualifierLoc();
251 ConsumerInstance->RewriteHelper->replaceCXXMethodNameAfterQualifier(
252 &QualLoc, MD, NewName);
253 }
254 else {
255 ConsumerInstance->TheRewriter.ReplaceText(DRE->getBeginLoc(),
256 MD->getNameAsString().size(), NewName);
257 }
258
259 return true;
260 }
261
262 bool RenameCXXMethodVisitor::VisitMemberExpr(MemberExpr *ME)
263 {
264 const ValueDecl *VD = ME->getMemberDecl();
265 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD);
266 if (!MD)
267 return true;
268 if (!ConsumerInstance->isExplicit(MD)) {
269 return true;
270 }
271 std::string NewName = "";
272 if (!ConsumerInstance->getMethodNewName(MD, NewName))
273 return true;
274 TransAssert((NewName != "") && "Bad new name!");
275
276 if (ME->hasQualifier()) {
277 NestedNameSpecifierLoc QualLoc = ME->getQualifierLoc();
278 ConsumerInstance->RewriteHelper->replaceCXXMethodNameAfterQualifier(
279 &QualLoc, MD, NewName);
280 }
281 else {
282 ConsumerInstance->TheRewriter.ReplaceText(ME->getMemberLoc(),
283 MD->getNameAsString().size(), NewName);
284 }
285
286 return true;
287 }
288
289 bool RenameCXXMethodVisitor::VisitCallExpr(CallExpr *CE)
290 {
291 // handled by VisitMemberExpr
292 if (CE->getDirectCallee())
293 return true;
294
295 // deal with UnresolvedLookupExpr
296 const Expr *E = CE->getCallee();
297 ConsumerInstance->rewriteDependentExpr(E);
298 return true;
299 }
300
301 void RenameCXXMethod::Initialize(ASTContext &context)
302 {
303 Transformation::Initialize(context);
304 MethodCollectionVisitor = new RenameCXXMethodCollectionVisitor(this);
305 RenameVisitor = new RenameCXXMethodVisitor(this);
306 ValidInstanceNum = 1;
307 }
308
309 bool RenameCXXMethod::HandleTopLevelDecl(DeclGroupRef D)
310 {
311 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
312 MethodCollectionVisitor->TraverseDecl(*I);
313 }
314 return true;
315 }
316
317 void RenameCXXMethod::HandleTranslationUnit(ASTContext &Ctx)
318 {
319 if (QueryInstanceOnly) {
320 if (hasValidMethods())
321 ValidInstanceNum = 1;
322 else
323 ValidInstanceNum = 0;
324 return;
325 }
326
327 if (!hasValidMethods()) {
328 TransError = TransNoValidFunsError;
329 return;
330 }
331 else if (TransformationCounter > ValidInstanceNum) {
332 TransError = TransMaxInstanceError;
333 return;
334 }
335
336 TransAssert(RenameVisitor && "NULL RenameVisitor!");
337 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
338
339 RenameVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
340
341 if (Ctx.getDiagnostics().hasErrorOccurred() ||
342 Ctx.getDiagnostics().hasFatalErrorOccurred())
343 TransError = TransInternalError;
344 }
345
346 bool RenameCXXMethod::hasValidMethods()
347 {
348 return ((NewMethodNames.size() != 0) && DoRenaming);
349 }
350
351 // note that we don't handle the possible ambiguity here, e.g.
352 // class A {
353 // public:
354 // virtual void foo();
355 // };
356 // class B {
357 // public:
358 // virtual void foo();
359 // };
360 // class C : public A, B {
361 // virtual void foo();
362 // };
363 // In this example, getNumInheritedFunctions(C) will return
364 // 2, but it doesn't really matter --- the number 2 is only used
365 // for numbering non-virtual functions.
366 // We are fine unless we don't rename a non-virtual function to
367 // a possible virtual function, either defined in the same
368 // class or inherited from a base.
369 // Furthermore, we don't want to hide any function in
370 // the base class through renaming, for example:
371 // class A {
372 // void foo();
373 // };
374 // class B : public A {
375 // void bar();
376 // };
377 //
378 // the transformation below is bad:
379 // class A {
380 // void m_fn1();
381 // };
382 // class B : public A {
383 // void m_fn1();
384 // };
385 unsigned int RenameCXXMethod::getNumInheritedFunctions(
386 const CXXRecordDecl *RD)
387 {
388 TransAssert(RD->isThisDeclarationADefinition() && "Not a definition!");
389
390 unsigned int Num = 0;
391 for (CXXRecordDecl::base_class_const_iterator I =
392 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
393
394 const CXXBaseSpecifier *BS = I;
395 const Type *Ty = BS->getType().getTypePtr();
396 const CXXRecordDecl *Base = getBaseDeclFromType(Ty);
397 if (!Base)
398 continue;
399
400 const CXXRecordDecl *CanonicalBase = Base->getCanonicalDecl();
401 // e.g.,
402 // template<typename T> struct A;
403 // template<typename T> struct B : A<T> {
404 // void foo() {}
405 // };
406 if (!Base->hasDefinition() && Base->getDescribedClassTemplate())
407 continue;
408
409 CXXRecordDeclToNumMap::iterator NI =
410 NumMemberFunctions.find(CanonicalBase);
411 if (NI != NumMemberFunctions.end()) {
412 Num += NI->second;
413 continue;
414 }
415
416 if (!Base->hasDefinition())
417 continue;
418 const CXXRecordDecl *BaseDef = Base->getDefinition();
419 handleOneCXXRecordDecl(BaseDef);
420 Num += NumMemberFunctions[CanonicalBase];
421 }
422 return Num;
423 }
424
425 bool RenameCXXMethod::isValidName(const StringRef &Name)
426 {
427 size_t PrefixLen = MethodNamePrefix.length();
428 StringRef NamePrefix = Name.substr(0, PrefixLen);
•429 if (NamePrefix != MethodNamePrefix)
430 return false;
431 llvm::APInt Num;
432 return !Name.drop_front(PrefixLen).getAsInteger(10, Num);
433 }
434
435 void RenameCXXMethod::addOneMethodName(const CXXMethodDecl *MD,
436 unsigned int /*Num*/)
437 {
438 const CXXMethodDecl *CanonicalMD = MD->getCanonicalDecl();
439 TransAssert((NewMethodNames.find(CanonicalMD) == NewMethodNames.end()) &&
440 "Duplicate CXXMethodDecl!");
441 std::stringstream SS;
442 // SS << MethodNamePrefix << Num;
443 NumRenamedMethods++;
444 SS << MethodNamePrefix << NumRenamedMethods;
445 NewMethodNames[CanonicalMD] = SS.str();
446
447 // Now we check if the old name actually has a valid format, i.e. m_fn([0-9]+)
448 // if not, set DoRenaming to be false, then we will need to
449 // do renaming later.
450 if (!isValidName(CanonicalMD->getNameAsString()))
451 DoRenaming = true;
452 }
453
454 void RenameCXXMethod::addOneInheritedName(const CXXMethodDecl *MD,
455 const CXXMethodDecl *BaseMD)
456 {
457 const CXXMethodDecl *CanonicalMD = MD->getCanonicalDecl();
458 CXXMethodDeclToNameMap::iterator I = NewMethodNames.find(CanonicalMD);
459 (void)I;
460 TransAssert((I == NewMethodNames.end()) && "Duplicate CXXMethodDecl!");
461
462 const CXXMethodDecl *CanonicalBaseMD = BaseMD->getCanonicalDecl();
463 // MD may be inherited of a member function of a class template
464 if (const FunctionDecl *FD =
465 CanonicalBaseMD->getInstantiatedFromMemberFunction()) {
466 CanonicalBaseMD = dyn_cast<CXXMethodDecl>(FD);
467 TransAssert(CanonicalBaseMD && "bad conversion from FD to MD!");
468 }
469 CXXMethodDeclToNameMap::iterator BaseI = NewMethodNames.find(CanonicalBaseMD);
470 TransAssert((BaseI != NewMethodNames.end()) &&
471 "Cannot find base CXXMethodDecl!");
472 NewMethodNames[CanonicalMD] = BaseI->second;
473 }
474
475 void RenameCXXMethod::handleOneCXXRecordDecl(const CXXRecordDecl *RD)
476 {
477 TransAssert(RD->isThisDeclarationADefinition() &&
478 "Can only handle class definition!");
479 if (VisitedCXXRecordDecls.count(RD))
480 return;
481 VisitedCXXRecordDecls.insert(RD);
482
483 // We need to skip explicit instantiations
484 // Note that shouldVisitTemplateInstantiations is false here,
485 // so we don't need to worry about implicit instantiations
486 if (const ClassTemplateSpecializationDecl *Spec =
487 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
488 TemplateSpecializationKind K = Spec->getSpecializationKind();
489 if ((K == TSK_ExplicitInstantiationDefinition) ||
490 (K == TSK_ExplicitInstantiationDeclaration))
491 return;
492 }
493
494 unsigned int NumFuns = getNumInheritedFunctions(RD);
495 CXXMethodDeclSet NonVirtualFuns;
496 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
497 E = RD->method_end(); I != E; ++I) {
498 const CXXMethodDecl *MD = (*I);
499
500 if (isSpecialCXXMethod(MD))
501 continue;
502 if (!MD->isVirtual()) {
503 NonVirtualFuns.insert(MD);
504 continue;
505 }
506
507 CXXMethodDecl::method_iterator MI = MD->begin_overridden_methods();
508 if (MI == MD->end_overridden_methods()) {
509 // new virtual function
510 NumFuns++;
511 addOneMethodName(MD, NumFuns);
512 }
513 else {
514 // if MD is overidden from any base class,
515 // it has been counted, so we don't need to increase NumFuns.
516 addOneInheritedName(MD, *MI);
517 }
518 }
519 const CXXRecordDecl *CanonicalRD = RD->getCanonicalDecl();
520
521 for (CXXMethodDeclSet::iterator MI = NonVirtualFuns.begin(),
522 ME = NonVirtualFuns.end(); MI != ME; ++MI) {
523 NumFuns++;
524 const CXXMethodDecl *MD = (*MI);
525 addOneMethodName(MD, NumFuns);
526 }
527 NumMemberFunctions[CanonicalRD] = NumFuns;
528 }
529
530 bool RenameCXXMethod::isSpecialCXXMethod(const CXXMethodDecl *MD)
531 {
532 if (dyn_cast<CXXConstructorDecl>(MD) ||
533 dyn_cast<CXXDestructorDecl>(MD) ||
534 dyn_cast<CXXConversionDecl>(MD))
535 return true;
536
537 SmallVector<const FunctionDecl*, 4> PreventedBy;
538 if (MD->isUsualDeallocationFunction(PreventedBy) ||
539 MD->isCopyAssignmentOperator() ||
540 MD->isMoveAssignmentOperator() ||
541 MD->isLambdaStaticInvoker() ||
542 MD->isOverloadedOperator())
543 return true;
544
545 return false;
546 }
547
548 // Handle function tempates in a class, which are not iterated throught
549 // CXXRecordDecl::method_iterator.
550 // For example:
551 // class A { template<typename T> void foo(T p) {} };
552 void RenameCXXMethod::handleOneMemberTemplateFunction(
553 const CXXMethodDecl *MD)
554 {
555 // we could have template constructors
556 if (isSpecialCXXMethod(MD))
557 return;
558
559 const FunctionTemplateDecl *FTD =
560 MD->getDescribedFunctionTemplate();
561 if (!FTD)
562 return;
563 const CXXRecordDecl *CanonicalRD = MD->getParent()->getCanonicalDecl();
564
565 CXXRecordDeclToNumMap::iterator I = NumMemberFunctions.find(CanonicalRD);
566 TransAssert((I != NumMemberFunctions.end()) && "Cannot find class!");
567 unsigned int NumFuns = I->second;
568 NumFuns++;
569 addOneMethodName(MD, NumFuns);
570 NumMemberFunctions[CanonicalRD] = NumFuns;
571 }
572
573 // handle UnresolvedLookupExpr:
574 // class A {
575 // template <typename T> static int foo(T, int) {
576 // foo<T, 0>(0, 0);
577 // }
578 // };
579 // or UnresolvedMemberExpr:
580 // class A {
581 // template < typename T > void foo (T) { foo <T> (0); }
582 // };
583 void RenameCXXMethod::rewriteOverloadExpr(const OverloadExpr *OE)
584 {
585 const FunctionDecl *FD = getFunctionDeclFromOverloadExpr(OE);
586 if (!FD)
587 return;
588 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
589 TransAssert(MD && "Invalid CXXMethodDecl!");
590
591 std::string NewName = "";
592 if (!getMethodNewName(MD, NewName))
593 return;
594 TransAssert((NewName != "") && "Bad new name!");
595 if (OE->getQualifier()) {
596 NestedNameSpecifierLoc QualLoc = OE->getQualifierLoc();
597 RewriteHelper->replaceCXXMethodNameAfterQualifier(
598 &QualLoc, MD, NewName);
599 }
600 else {
601 TheRewriter.ReplaceText(OE->getNameLoc(),
602 MD->getNameAsString().size(), NewName);
603 }
604 }
605
606 const FunctionDecl* RenameCXXMethod::getFunctionDeclFromOverloadExpr(
607 const OverloadExpr *OE)
608 {
609 const CXXRecordDecl *RD = OE->getNamingClass();
610 if (!RD)
611 return NULL;
612 DeclarationName DName = OE->getName();
613 DeclarationName::NameKind K = DName.getNameKind();
614 if (K == DeclarationName::CXXOperatorName)
615 return NULL;
616 TransAssert((K == DeclarationName::Identifier) &&
617 "Not an indentifier!");
618 DeclContextSet VisitedCtxs;
619 return lookupFunctionDecl(DName, RD, VisitedCtxs);
620 }
621
622 const FunctionDecl* RenameCXXMethod::getFunctionDeclFromType(
623 const Type *Ty, DeclarationName &DName)
624 {
625 if (Ty->isPointerType() || Ty->isReferenceType())
626 Ty = getBasePointerElemType(Ty);
627 const FunctionDecl *FD = NULL;
628 if (const CXXRecordDecl *BaseRD = getBaseDeclFromType(Ty)) {
629 DeclContextSet VisitedCtxs;
630 FD = lookupFunctionDecl(DName, BaseRD, VisitedCtxs);
631 }
632 return FD;
633 }
634
635 const FunctionDecl* RenameCXXMethod::getFunctionDeclFromOverloadTemplate(
636 const CallExpr *CE, const OverloadExpr *OE, DeclarationName &DName)
637 {
638 const FunctionDecl *FD = getFunctionDeclFromOverloadExpr(OE);
639 // FD is not necessary a member function
640 if (!FD) {
641 TransAssert(CurrentFD && "Invalid CurrentFD!");
642 const DeclContext *Ctx = CurrentFD->getLookupParent();
643 TransAssert(Ctx && "Bad DeclContext!");
644 DeclarationName FunName = OE->getName();
645 DeclContextSet VisitedCtxs;
646 FD = lookupFunctionDecl(FunName, Ctx, VisitedCtxs);
647 if (!FD)
648 return NULL;
649 }
650
651 const Type *Ty = FD->getReturnType().getTypePtr();
652 return getFunctionDeclFromType(Ty, DName);
653 }
654
655 const FunctionDecl* RenameCXXMethod::getFunctionDeclFromReturnType(
656 const CallExpr *CE, DeclarationName &DName)
657 {
658 const Expr *CalleeExpr = CE->getCallee();
659 TransAssert(CalleeExpr && "NULL CalleeExpr!");
660
661 // template<typename T> class A {
662 // struct B{
663 // static B& bar() {}
664 // };
665 // B& foo() {}
666 // void baz() {
667 // foo().bar();
668 // }
669 // };
670 // get the return type of foo().
671 if (const MemberExpr *ME = dyn_cast<MemberExpr>(CalleeExpr)) {
672 const ValueDecl *VD = ME->getMemberDecl();
673 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD);
674 if (!MD)
675 return NULL;
676 const Type *Ty = MD->getReturnType().getTypePtr();
677 return getFunctionDeclFromType(Ty, DName);
678 }
679 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CalleeExpr)) {
680 const ValueDecl *VD = DRE->getDecl();
681 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD);
682 if (!MD)
683 return NULL;
684 const Type *Ty = MD->getReturnType().getTypePtr();
685 return getFunctionDeclFromType(Ty, DName);
686 }
687 else if (const OverloadExpr *OE = dyn_cast<OverloadExpr>(CalleeExpr)) {
688 return getFunctionDeclFromOverloadTemplate(CE, OE, DName);
689 }
690 else if (const CXXDependentScopeMemberExpr *DE =
691 dyn_cast<CXXDependentScopeMemberExpr>(CalleeExpr)) {
692 // template <typename T> class A {
693 // public:
694 // T foo();
695 // };
696 // template <typename T> class B {
697 // public:
698 // A<T> a;
699 // void bar();
700 // A<T> &return_a() { return a; }
701 // };
702 // template <typename T> void bar() {
703 // B<T> b;
704 // T xx = b.return_a().foo();
705 // }
706 // CallExpr could be invoked via CXXDependentScopeMemberExpr,
707 // then we get the called function (e.g., return_a) via looking up
708 // the base(e.g., b) of CXXDependentScopeMemberExpr
709 const FunctionDecl *FD = getFunctionDecl(DE);
710 if (!FD)
711 return NULL;
712 const Type *Ty = FD->getReturnType().getTypePtr();
713 // Note that it's not always true that we could get a
714 // non-null function here, e.g.:
715 // template <typename T> class A {
716 // public:
717 // T foo();
718 // };
719 // template <typename T> class B {
720 // public:
721 // T a;
722 // void bar();
723 // T &return_a() { return a; }
724 // };
725 // template <typename T> void bar() {
726 // B<T> b;
727 // T xx = b.return_a().foo();
728 // }
729 // here we cannot resolve return_a's return type
730 return getFunctionDeclFromType(Ty, DName);
731 }
732 return NULL;
733 }
734
735 // could return NULL
736 const FunctionDecl* RenameCXXMethod::getFunctionDecl(
737 const CXXDependentScopeMemberExpr *DE)
738 {
739 if (DE->isImplicitAccess())
740 return NULL;
741 DeclarationName DName = DE->getMember();
742 if (DName.getNameKind() == DeclarationName::CXXOperatorName)
743 return NULL;
744
745 TransAssert((DName.getNameKind() == DeclarationName::Identifier) &&
746 "Not an indentifier!");
747 const Expr *E = DE->getBase();
748 TransAssert(E && "NULL Base Expr!");
749 const Expr *BaseE = E->IgnoreParens();
750
751 const FunctionDecl *FD = NULL;
752 if (dyn_cast<CXXThisExpr>(BaseE)) {
753 TransAssert(CurrentFD && "NULL CurrentFD!");
754 const DeclContext *Ctx = CurrentFD->getLookupParent();
755 TransAssert(Ctx && "Bad DeclContext!");
756 DeclContextSet VisitedCtxs;
757 FD = lookupFunctionDecl(DName, Ctx, VisitedCtxs);
758 TransAssert(FD && "Cannot resolve DName!");
759 return FD;
760 }
761
762 // it's not always the case we can get a non-null FD, e.g.
763 // template<typename T>
764 // struct S
765 // {
766 // static int foo(T t) { return t.bar(); }
767 // };
768 // here we can't resolve bar()
769 // What should we do? assign a fresh name to this kind of function?
770 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseE)) {
771 FD = getFunctionDeclFromType(DRE->getType().getTypePtr(), DName);
772 return FD;
773 }
774
775 if (const CallExpr *CE = dyn_cast<CallExpr>(BaseE)) {
776 FD = getFunctionDeclFromReturnType(CE, DName);
777 // TransAssert(FD && "Cannot find FunctionDecl!");
778 return FD;
779 }
780
781 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseE)) {
782 const Expr *MEBase = ME->getBase();
783 return getFunctionDeclFromType(MEBase->getType().getTypePtr(), DName);
784 }
785
786 const Type *Ty = DE->getBaseType().getTypePtr();
787 if (Ty->isPointerType() || Ty->isReferenceType())
788 Ty = getBasePointerElemType(Ty);
789 if (const DeclContext *Ctx = getBaseDeclFromType(Ty)) {
790 DeclContextSet VisitedCtxs;
791 return lookupFunctionDecl(DName, Ctx, VisitedCtxs);
792 }
793 return NULL;
794 }
795
796 void RenameCXXMethod::rewriteCXXDependentScopeMemberExpr(
797 const CXXDependentScopeMemberExpr *DE)
798 {
799 const FunctionDecl *FD = getFunctionDecl(DE);
800
801 if (!FD)
802 return;
803 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
804 TransAssert(MD && "Invalid MD!");
805 std::string NewName = "";
806 if (!getMethodNewName(MD, NewName))
807 return;
808 TransAssert((NewName != "") && "Bad new name!");
809 if (DE->getQualifier()) {
810 NestedNameSpecifierLoc QualLoc = DE->getQualifierLoc();
811 RewriteHelper->replaceCXXMethodNameAfterQualifier(
812 &QualLoc, MD, NewName);
813 }
814 else {
815 TheRewriter.ReplaceText(DE->getMemberLoc(),
816 MD->getNameAsString().size(), NewName);
817 }
818 }
819
820 void RenameCXXMethod::rewriteDependentExpr(const Expr *E)
821 {
822 if (const OverloadExpr *OE = dyn_cast<OverloadExpr>(E)) {
823 rewriteOverloadExpr(OE);
824 return;
825 }
826 if (const CXXDependentScopeMemberExpr *DE =
827 dyn_cast<CXXDependentScopeMemberExpr>(E)) {
828 rewriteCXXDependentScopeMemberExpr(DE);
829 return;
830 }
831 }
832
833 const CXXMethodDecl* RenameCXXMethod::getCXXMethodFromMemberFunction(
834 const CXXMethodDecl *MD)
835 {
836 // coud happen, e.g.:
837 // template <typename T> struct A { int foo(); };
838 // void bar () {
839 // A<int> a;
840 // a.foo(); <-- here we find foo via getInstantiatedFromMemberFunction
841 // }
842 const FunctionDecl *FD = MD->getInstantiatedFromMemberFunction();
843 if (FD) {
844 MD = dyn_cast<CXXMethodDecl>(FD);
845 TransAssert(MD && "bad conversion from FD to MD!");
846 return MD;
847 }
848
849 // one more try
850 FD = MD->getTemplateInstantiationPattern();
851 if (FD) {
852 MD = dyn_cast<CXXMethodDecl>(FD);
853 TransAssert(MD && "bad conversion from FD to MD!");
854 return MD;
855 }
856 return NULL;
857 }
858
859 bool RenameCXXMethod::getMethodNewName(const CXXMethodDecl *MD,
860 std::string &NewName)
861 {
862 const CXXMethodDecl *CanonicalMD = MD->getCanonicalDecl();
863 llvm::DenseMap<const CXXMethodDecl *, std::string>::iterator I =
864 NewMethodNames.find(CanonicalMD);
865 if (I == NewMethodNames.end()) {
866 CanonicalMD = getCXXMethodFromMemberFunction(CanonicalMD);
867 I = NewMethodNames.find(CanonicalMD);
868 if (I == NewMethodNames.end())
869 return false;
870 }
871 NewName = I->second;
872 return true;
873 }
874
875 void RenameCXXMethod::rewriteFunctionTemplateExplicitInstantiation(
876 const FunctionDecl *FD)
877 {
878 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
879 TransAssert(MD && "Not a CXXMethodDecl!");
880
881 const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern();
882 TransAssert(Pattern && "Cannot find Template Pattern!");
883 const CXXMethodDecl *TmplMD = dyn_cast<CXXMethodDecl>(Pattern);
884 TransAssert(TmplMD && "Invalid CXXMethodDecl!");
885
886 CXXMethodDeclToNameMap::iterator I =
887 NewMethodNames.find(TmplMD->getCanonicalDecl());
888 TransAssert((I != NewMethodNames.end()) && "Cannot find CXXMethodDecl!");
889 std::string Name = I->second;
890 I = NewMethodNames.find(MD);
891 TransAssert((I == NewMethodNames.end()) && "Duplicate find CXXMethodDecl?");
892
893 SourceLocation Loc = MD->getPointOfInstantiation();
894 TheRewriter.ReplaceText(Loc, MD->getNameAsString().size(), Name);
895 }
896
897 // avoid rewriting the content of an implicit instantiated record decl, e.g.
898 // struct A {};
899 // template <typename T = A> class B {
900 // public:
901 // B() { foo(0); } <--- avoid writing the foo of the implicit instantiation
902 // void foo ( int );
903 // };
904 // struct C { B<> b; };
905 // void foo() { new C; }
906 // template <typename T> B<T>::B() { foo(0); }
907 bool RenameCXXMethod::isExplicit(const CXXMethodDecl *MD)
908 {
909 if (dyn_cast<CXXMethodDecl>(CurrentFD)) {
910 if (ClassInstantiation)
911 return false;
912 return (InstantiationQueue.size() == 0);
913 }
914 else {
915 if (FunctionInstantiation && MD->isStatic())
916 return true;
917 return !FunctionInstantiation;
918 }
919 }
920
921 void RenameCXXMethod::setClassInstantiationFlag(const RecordDecl *RD)
922 {
923 if (const ClassTemplateSpecializationDecl *Spec =
924 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
925 TemplateSpecializationKind K = Spec->getSpecializationKind();
926 if (K == TSK_ExplicitInstantiationDeclaration) {
927 ClassInstantiation = true;
928 return;
929 }
930 }
931 ClassInstantiation = false;
932 }
933
934 void RenameCXXMethod::setFunctionInstantiationFlag(const FunctionDecl *FD)
935 {
936 TemplateSpecializationKind K = FD->getTemplateSpecializationKind();
937 if ((K == TSK_ImplicitInstantiation) ||
938 (K == TSK_ExplicitInstantiationDeclaration) ||
939 (K == TSK_ExplicitInstantiationDefinition)) {
940 FunctionInstantiation = true;
941 }
942 else {
943 FunctionInstantiation = false;
944 }
945 }
946
947 RenameCXXMethod::~RenameCXXMethod(void)
948 {
949 delete MethodCollectionVisitor;
950 delete RenameVisitor;
951 }
952