forked from vgvassilev/creduce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Transformation.cpp
1037 lines (911 loc) · 30.2 KB
/
Transformation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// Copyright (c) 2012, 2013, 2014 The University of Utah
// All rights reserved.
//
// This file is distributed under the University of Illinois Open Source
// License. See the file COPYING for details.
//
//===----------------------------------------------------------------------===//
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include "Transformation.h"
#include <sstream>
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Lexer.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/SmallString.h"
using namespace clang;
class TransNameQueryVisitor : public
RecursiveASTVisitor<TransNameQueryVisitor> {
public:
TransNameQueryVisitor(TransNameQueryWrap *Instance,
const std::string &Prefix)
: WrapInstance(Instance),
NamePrefix(Prefix)
{ }
bool VisitVarDecl(VarDecl *VD);
private:
TransNameQueryWrap *WrapInstance;
const std::string NamePrefix;
};
bool TransNameQueryVisitor::VisitVarDecl(VarDecl *VD)
{
std::string Name = VD->getNameAsString();
size_t Sz = NamePrefix.size();
if (Name.compare(0, Sz, NamePrefix))
return true;
std::string PostfixStr = Name.substr(Sz);
TransAssert((PostfixStr.size() > 0) && "Bad trans tmp name!");
std::stringstream TmpSS(PostfixStr);
unsigned int PostfixV;
if (!(TmpSS >> PostfixV))
TransAssert(0 && "Non-integer trans tmp name!");
if (PostfixV > WrapInstance->MaxPostfix)
WrapInstance->MaxPostfix = PostfixV;
return true;
}
TransNameQueryWrap::TransNameQueryWrap(const std::string &Prefix)
: NamePrefix(Prefix),
MaxPostfix(0)
{
NameQueryVisitor = new TransNameQueryVisitor(this, Prefix);
}
TransNameQueryWrap::~TransNameQueryWrap(void)
{
delete NameQueryVisitor;
}
bool TransNameQueryWrap::TraverseDecl(Decl *D)
{
return NameQueryVisitor->TraverseDecl(D);
}
void Transformation::Initialize(ASTContext &context)
{
Context = &context;
SrcManager = &Context->getSourceManager();
TheRewriter.setSourceMgr(Context->getSourceManager(),
Context->getLangOpts());
RewriteHelper = RewriteUtils::GetInstance(&TheRewriter);
}
void Transformation::outputTransformedSource(llvm::raw_ostream &OutStream)
{
FileID MainFileID = SrcManager->getMainFileID();
const RewriteBuffer *RWBuf = TheRewriter.getRewriteBufferFor(MainFileID);
// RWBuf is non-empty upon any rewrites
TransAssert(RWBuf && "Empty RewriteBuffer!");
OutStream << std::string(RWBuf->begin(), RWBuf->end());
OutStream.flush();
}
void Transformation::outputOriginalSource(llvm::raw_ostream &OutStream)
{
FileID MainFileID = SrcManager->getMainFileID();
const llvm::MemoryBuffer *MainBuf = SrcManager->getBuffer(MainFileID);
TransAssert(MainBuf && "Empty MainBuf!");
OutStream << MainBuf->getBufferStart();
OutStream.flush();
}
void Transformation::getTransErrorMsg(std::string &ErrorMsg)
{
if (TransError == TransSuccess) {
ErrorMsg = "";
}
else if (TransError == TransInternalError) {
ErrorMsg = "Internal transformation error!";
}
else if (TransError == TransMaxInstanceError) {
ErrorMsg =
"The counter value exceeded the number of transformation instances!";
}
else if (TransError == TransMaxVarsError) {
ErrorMsg = "Too many variables!";
}
else if (TransError == TransMaxClassesError) {
ErrorMsg = "Too many classes!";
}
else if (TransError == TransNoValidVarsError) {
ErrorMsg = "No variables need to be renamed!";
}
else if (TransError == TransNoValidFunsError) {
ErrorMsg = "No valid function declarations exist!";
}
else if (TransError == TransNoValidParamsError) {
ErrorMsg = "No valid parameters declarations exist!";
}
else if (TransError == TransNoTextModificationError) {
ErrorMsg = "No modification to the transformed program!";
}
else if (TransError == TransToCounterTooBigError) {
ErrorMsg =
"The to-counter value exceeded the number of transformation instances!";
}
else {
TransAssert(0 && "Unknown transformation error!");
}
}
const Expr *
Transformation::ignoreSubscriptExprParenCasts(const Expr *E)
{
const Expr *NewE = E->IgnoreParenCasts();
const ArraySubscriptExpr *ASE;
while (true) {
ASE = dyn_cast<ArraySubscriptExpr>(NewE);
if (!ASE)
break;
NewE = ASE->getBase()->IgnoreParenCasts();
}
TransAssert(NewE && "NULL NewE!");
return NewE;
}
const Expr *Transformation::getInitExprByIndex(IndexVector &Idxs,
const InitListExpr *ILE)
{
const InitListExpr *SubILE = ILE;
const Expr *Exp = NULL;
unsigned int Count = 0;
for (IndexVector::const_reverse_iterator I = Idxs.rbegin(),
E = Idxs.rend(); I != E; ++I) {
Count++;
unsigned int Idx;
const Type *T = SubILE->getType().getTypePtr();
if (T->isUnionType())
Idx = 0;
else
Idx = (*I);
// Incomplete initialization list
if (Idx >= SubILE->getNumInits())
return NULL;
Exp = SubILE->getInit(Idx);
TransAssert(Exp && "NULL Exp!");
SubILE = dyn_cast<InitListExpr>(Exp);
if (!SubILE)
break;
}
TransAssert(Exp && "Exp cannot be NULL");
TransAssert(Count == Idxs.size());
return Exp;
}
const Expr *Transformation::getArrayBaseExprAndIdxs(
const ArraySubscriptExpr *ASE, IndexVector &Idxs)
{
const Expr *BaseE = NULL;
while (ASE) {
const Expr *IdxE = ASE->getIdx();
unsigned int Idx = 0;
llvm::APSInt Result;
if (IdxE && IdxE->EvaluateAsInt(Result, *Context)) {
// this will truncate a possible uint64 value to uint32 value
Idx = (unsigned int)(*Result.getRawData());
}
BaseE = ASE->getBase()->IgnoreParenCasts();
ASE = dyn_cast<ArraySubscriptExpr>(BaseE);
Idxs.push_back(Idx);
}
return BaseE;
}
const Expr *Transformation::getInitExprFromBase(const Expr *BaseE,
IndexVector &Idxs)
{
TransAssert(BaseE && "Bad Array Base Expression!");
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseE);
if (!DRE)
return NULL;
const ValueDecl *OrigDecl = DRE->getDecl();
const VarDecl *VD = dyn_cast<VarDecl>(OrigDecl);
TransAssert(VD && "Bad VarDecl!");
const Type * Ty = VD->getType().getTypePtr();
if (Ty->isPointerType())
return NULL;
const Expr *InitE = VD->getAnyInitializer();
if (!InitE)
return NULL;
// We don't have routine for CXXConstructExpr
if (dyn_cast<CXXConstructExpr>(InitE))
return NULL;
const InitListExpr *ILE = dyn_cast<InitListExpr>(InitE);
// not always the case we will have an InitListExpr, e.g.,
// RHS is a struct, or dereferencing a struct pointer, etc
if (!ILE)
return NULL;
return getInitExprByIndex(Idxs, ILE);
}
const Expr *Transformation::getArraySubscriptElem(
const ArraySubscriptExpr *ASE)
{
IndexVector ArrayDims;
const Expr *BaseE = getArrayBaseExprAndIdxs(ASE, ArrayDims);
return getInitExprFromBase(BaseE, ArrayDims);
}
const Expr *Transformation::getMemberExprBaseExprAndIdxs(
const MemberExpr *ME, IndexVector &Idxs)
{
const Expr *BaseE = NULL;
while (ME) {
ValueDecl *VD = ME->getMemberDecl();
FieldDecl *FD = dyn_cast<FieldDecl>(VD);
TransAssert(FD && "Bad FD!\n");
unsigned int Idx = FD->getFieldIndex();
Idxs.push_back(Idx);
BaseE = ME->getBase()->IgnoreParenCasts();
const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(BaseE);
if (ASE) {
BaseE = getArrayBaseExprAndIdxs(ASE, Idxs);
if (!BaseE)
return NULL;
}
ME = dyn_cast<MemberExpr>(BaseE);
}
return BaseE;
}
bool Transformation::isCXXMemberExpr(const MemberExpr *ME)
{
const ValueDecl *VD = ME->getMemberDecl();
if (dyn_cast<CXXMethodDecl>(VD))
return true;
const FieldDecl *FD = dyn_cast<FieldDecl>(VD);
TransAssert(FD && "Bad FieldDecl!");
const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(FD->getParent());
if (!CXXRD)
return false;
return !(CXXRD->isCLike());
}
const Expr *Transformation::getMemberExprElem(const MemberExpr *ME)
{
if (isCXXMemberExpr(ME))
return NULL;
IndexVector Idxs;
const Expr *BaseE = getMemberExprBaseExprAndIdxs(ME, Idxs);
return getInitExprFromBase(BaseE, Idxs);
}
unsigned int Transformation::getArrayDimension(const ArrayType *ArrayTy)
{
unsigned int Dim = 1;
const Type *ArrayElemTy = ArrayTy->getElementType().getTypePtr();
while (ArrayElemTy->isArrayType()) {
const ArrayType *AT = dyn_cast<ArrayType>(ArrayElemTy);
ArrayElemTy = AT->getElementType().getTypePtr();
Dim++;
}
return Dim;
}
unsigned int Transformation::getArrayDimensionAndTypes(
const ArrayType *ArrayTy,
ArraySubTypeVector &TyVec)
{
unsigned int Dim = 1;
const Type *ArrayElemTy = ArrayTy->getElementType().getTypePtr();
TyVec.push_back(ArrayTy);
while (ArrayElemTy->isArrayType()) {
const ArrayType *AT = dyn_cast<ArrayType>(ArrayElemTy);
TyVec.push_back(AT);
ArrayElemTy = AT->getElementType().getTypePtr();
Dim++;
}
return Dim;
}
const Type *Transformation::getArrayBaseElemType(const ArrayType *ArrayTy)
{
const Type *ArrayElemTy = ArrayTy->getElementType().getTypePtr();
while (ArrayElemTy->isArrayType()) {
const ArrayType *AT = dyn_cast<ArrayType>(ArrayElemTy);
ArrayElemTy = AT->getElementType().getTypePtr();
}
TransAssert(ArrayElemTy && "Bad Array Element Type!");
return ArrayElemTy;
}
unsigned int Transformation::getConstArraySize(
const ConstantArrayType *CstArrayTy)
{
unsigned int Sz;
llvm::APInt Result = CstArrayTy->getSize();
llvm::SmallString<8> IntStr;
Result.toStringUnsigned(IntStr);
std::stringstream TmpSS(IntStr.str());
if (!(TmpSS >> Sz)) {
TransAssert(0 && "Non-integer value!");
}
return Sz;
}
// This is a more complete implementation to deal with mixed
// array and structs/unions
const Expr *Transformation::getBaseExprAndIdxs(const Expr *E,
IndexVector &Idxs)
{
const Expr *BaseE = NULL;
while (E) {
E = E->IgnoreParenCasts();
BaseE = E;
Expr::StmtClass SC = E->getStmtClass();
if (SC == Expr::MemberExprClass) {
const MemberExpr *ME = dyn_cast<MemberExpr>(E);
ValueDecl *VD = ME->getMemberDecl();
FieldDecl *FD = dyn_cast<FieldDecl>(VD);
TransAssert(FD && "Bad FD!\n");
unsigned int Idx = FD->getFieldIndex();
Idxs.push_back(Idx);
E = ME->getBase();
}
else if (SC == Expr::ArraySubscriptExprClass) {
const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E);
const Expr *IdxE = ASE->getIdx();
unsigned int Idx = 0;
llvm::APSInt Result;
// If we cannot have an integeral index, use 0.
if (IdxE && IdxE->EvaluateAsInt(Result, *Context)) {
std::string IntStr = Result.toString(10);
std::stringstream TmpSS(IntStr);
if (!(TmpSS >> Idx))
TransAssert(0 && "Non-integer value!");
}
Idxs.push_back(Idx);
E = ASE->getBase();
}
else {
break;
}
}
return BaseE;
}
const Expr *Transformation::getBaseExprAndIdxExprs(
const ArraySubscriptExpr *ASE, ExprVector &IdxExprs)
{
const Expr *BaseE = NULL;
while (ASE) {
const Expr *IdxE = ASE->getIdx();
IdxExprs.push_back(IdxE);
BaseE = ASE->getBase()->IgnoreParenCasts();
ASE = dyn_cast<ArraySubscriptExpr>(BaseE);
}
return BaseE;
}
const Type *Transformation::getBasePointerElemType(const Type *Ty)
{
QualType QT = Ty->getPointeeType();;
while (!QT.isNull()) {
Ty = QT.getTypePtr();
QT = Ty->getPointeeType();
}
TransAssert(Ty && "NULL Type Ptr!");
return Ty;
}
int Transformation::getIndexAsInteger(const Expr *E)
{
llvm::APSInt Result;
int Idx;
if (!E->EvaluateAsInt(Result, *Context))
TransAssert(0 && "Failed to Evaluate index!");
Idx = (int)(*Result.getRawData());
return Idx;
}
const Type* Transformation::getBaseType(const Type *T)
{
if (T->isPointerType() || T->isReferenceType())
return getBaseType(T->getPointeeType().getTypePtr());
else if (T->isRecordType())
T = T->getAs<RecordType>();
else if (T->isEnumeralType())
T = T->getAs<EnumType>();
else if (T->getTypeClass() == Type::Typedef)
T = T->getAs<TypedefType>();
else if (T->isArrayType())
return getBaseType(T->castAsArrayTypeUnsafe()->
getElementType().getTypePtr());
return T;
}
// Lookup a function decl from a top-level DeclContext
// It's slow...
const FunctionDecl *Transformation::lookupFunctionDeclInGlobal(
DeclarationName &DName, const DeclContext *Ctx)
{
DeclContext::lookup_const_result Result = Ctx->lookup(DName);
for (DeclContext::lookup_const_iterator I = Result.begin(), E = Result.end();
I != E; ++I) {
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
return FD;
}
const FunctionTemplateDecl *TD = NULL;
if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(*I)) {
TD = dyn_cast<FunctionTemplateDecl>(USD->getTargetDecl());
}
else {
TD = dyn_cast<FunctionTemplateDecl>(*I);
}
if (TD)
return TD->getTemplatedDecl();
}
for (DeclContext::decl_iterator I = Ctx->decls_begin(),
E = Ctx->decls_end(); I != E; ++I) {
if (const ClassTemplateDecl *ClassTemplate =
dyn_cast<ClassTemplateDecl>(*I)) {
const CXXRecordDecl *CXXRD = ClassTemplate->getTemplatedDecl();
if (const FunctionDecl *FD = lookupFunctionDeclInGlobal(DName, CXXRD)) {
return FD;
}
}
const DeclContext *SubCtx = dyn_cast<DeclContext>(*I);
if (!SubCtx || dyn_cast<LinkageSpecDecl>(SubCtx))
continue;
if (const FunctionDecl *FD = lookupFunctionDeclInGlobal(DName, SubCtx)) {
return FD;
}
}
return NULL;
}
const FunctionDecl *Transformation::lookupFunctionDeclFromBases(
DeclarationName &DName,
const CXXRecordDecl *CXXRD,
DeclContextSet &VisitedCtxs)
{
for (CXXRecordDecl::base_class_const_iterator I =
CXXRD->bases_begin(), E = CXXRD->bases_end(); I != E; ++I) {
const CXXBaseSpecifier *BS = I;
const Type *Ty = BS->getType().getTypePtr();
const CXXRecordDecl *Base = getBaseDeclFromType(Ty);
// it's not always the case we could resolve a base specifier, e.g.
// Ty is of DependentName
if (!Base)
continue;
const CXXRecordDecl *BaseDef = Base->getDefinition();
if (!BaseDef)
continue;
if (const FunctionDecl *FD =
lookupFunctionDecl(DName, BaseDef, VisitedCtxs))
return FD;
}
return NULL;
}
const FunctionDecl *Transformation::lookupFunctionDeclFromCtx(
DeclarationName &DName,
const DeclContext *Ctx,
DeclContextSet &VisitedCtxs)
{
if (dyn_cast<LinkageSpecDecl>(Ctx))
return NULL;
DeclContext::lookup_const_result Result = Ctx->lookup(DName);
for (DeclContext::lookup_const_iterator I = Result.begin(), E = Result.end();
I != E; ++I) {
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
return FD;
}
const FunctionTemplateDecl *TD = NULL;
if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(*I)) {
TD = dyn_cast<FunctionTemplateDecl>(USD->getTargetDecl());
}
else {
TD = dyn_cast<FunctionTemplateDecl>(*I);
}
if (TD)
return TD->getTemplatedDecl();
if (const UnresolvedUsingValueDecl *UUD =
dyn_cast<UnresolvedUsingValueDecl>(*I)) {
const NestedNameSpecifier *NNS = UUD->getQualifier();
const DeclContext *Ctx = getDeclContextFromSpecifier(NNS);
if (!Ctx)
continue;
if (const FunctionDecl *FD =
lookupFunctionDecl(DName, Ctx, VisitedCtxs))
return FD;
}
}
return NULL;
}
const FunctionDecl *Transformation::lookupFunctionDecl(
DeclarationName &DName,
const DeclContext *Ctx,
DeclContextSet &VisitedCtxs)
{
if (dyn_cast<LinkageSpecDecl>(Ctx))
return NULL;
if (VisitedCtxs.count(Ctx))
return NULL;
VisitedCtxs.insert(Ctx);
if (const FunctionDecl *FD =
lookupFunctionDeclFromCtx(DName, Ctx, VisitedCtxs))
return FD;
// lookup base classes:
// this would be slow and may re-visit some Ctx.
// Probably we should cache those Ctx(s) which have been visited
// to speedup lookup
if (Ctx->isRecord()) {
const RecordDecl *RD = dyn_cast<RecordDecl>(Ctx);
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
if (const FunctionDecl *FD =
lookupFunctionDeclFromBases(DName, CXXRD, VisitedCtxs))
return FD;
}
}
for (DeclContext::udir_iterator I = Ctx->using_directives_begin(),
E = Ctx->using_directives_end(); I != E; ++I) {
const NamespaceDecl *ND = (*I)->getNominatedNamespace();
// avoid infinite recursion
if (ND->getLookupParent() == Ctx)
return NULL;
if (const FunctionDecl *FD = lookupFunctionDecl(DName, ND, VisitedCtxs))
return FD;
}
const DeclContext *ParentCtx = Ctx->getLookupParent();
if (!ParentCtx || dyn_cast<LinkageSpecDecl>(ParentCtx))
return NULL;
return lookupFunctionDecl(DName, ParentCtx, VisitedCtxs);
}
const DeclContext *Transformation::getDeclContextFromSpecifier(
const NestedNameSpecifier *NNS)
{
for (; NNS; NNS = NNS->getPrefix()) {
NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
switch (Kind) {
case NestedNameSpecifier::Namespace: {
return NNS->getAsNamespace()->getCanonicalDecl();
}
case NestedNameSpecifier::NamespaceAlias: {
const NamespaceAliasDecl *NAD = NNS->getAsNamespaceAlias();
return NAD->getNamespace()->getCanonicalDecl();
}
case NestedNameSpecifier::TypeSpec: // Fall-through
case NestedNameSpecifier::TypeSpecWithTemplate: {
const Type *Ty = NNS->getAsType();
if (const RecordType *RT = Ty->getAs<RecordType>())
return RT->getDecl();
if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
const TypedefNameDecl *TypeDecl = TT->getDecl();
const Type *UnderlyingTy = TypeDecl->getUnderlyingType().getTypePtr();
if (const RecordType *RT = UnderlyingTy->getAs<RecordType>())
return RT->getDecl();
if (const TemplateSpecializationType *TST =
UnderlyingTy->getAs<TemplateSpecializationType>()) {
return getBaseDeclFromTemplateSpecializationType(TST);
}
}
break;
}
default:
break;
}
}
return NULL;
}
bool Transformation::isSpecialRecordDecl(const RecordDecl *RD)
{
std::string Name = RD->getNameAsString();
return (Name == "__va_list_tag");
}
const CXXRecordDecl *Transformation::getBaseDeclFromTemplateSpecializationType(
const TemplateSpecializationType *TSTy)
{
TemplateName TplName = TSTy->getTemplateName();
TemplateDecl *TplD = TplName.getAsTemplateDecl();
TransAssert(TplD && "Invalid TemplateDecl!");
NamedDecl *ND = TplD->getTemplatedDecl();
TransAssert(ND && "Invalid NamedDecl!");
if (TypedefNameDecl *TdefD = dyn_cast<TypedefNameDecl>(ND)) {
const Type *UnderlyingTy = TdefD->getUnderlyingType().getTypePtr();
const CXXRecordDecl *CXXRD = getBaseDeclFromType(UnderlyingTy);
TransAssert(CXXRD && "Invalid CXXRD from TypedefNameDecl!");
return CXXRD;
}
const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ND);
TransAssert(CXXRD && "Invalid CXXRD!");
if (CXXRD->hasDefinition())
return CXXRD->getDefinition();
else
return CXXRD;
}
// This function could return NULL
const CXXRecordDecl *Transformation::getBaseDeclFromType(const Type *Ty)
{
const CXXRecordDecl *Base = NULL;
Type::TypeClass TyClass = Ty->getTypeClass();
switch (TyClass) {
case Type::TemplateSpecialization: {
const TemplateSpecializationType *TSTy =
dyn_cast<TemplateSpecializationType>(Ty);
Base = getBaseDeclFromTemplateSpecializationType(TSTy);
TransAssert(Base && "Bad base class type!");
return Base;
}
case Type::DependentTemplateSpecialization: {
return NULL;
}
case Type::Elaborated: {
const ElaboratedType *ETy = dyn_cast<ElaboratedType>(Ty);
const Type *NamedT = ETy->getNamedType().getTypePtr();
return getBaseDeclFromType(NamedT);
}
case Type::Paren: {
const ParenType *PT = dyn_cast<ParenType>(Ty);
const Type *InnerTy = PT->getInnerType().getTypePtr();
return getBaseDeclFromType(InnerTy);
}
case Type::Typedef: {
const TypedefType *TdefTy = dyn_cast<TypedefType>(Ty);
const TypedefNameDecl *TdefD = TdefTy->getDecl();
const Type *UnderlyingTy = TdefD->getUnderlyingType().getTypePtr();
return getBaseDeclFromType(UnderlyingTy);
}
case Type::Decltype: {
const DecltypeType *DT = dyn_cast<DecltypeType>(Ty);
const Type *UnderlyingTy = DT->getUnderlyingType().getTypePtr();
return getBaseDeclFromType(UnderlyingTy);
}
case Type::ConstantArray:
case Type::DependentSizedArray:
case Type::IncompleteArray:
case Type::VariableArray: { // fall-through
const ArrayType *AT = dyn_cast<ArrayType>(Ty);
const Type *ElemTy = AT->getElementType().getTypePtr();
return getBaseDeclFromType(ElemTy);
}
case Type::MemberPointer: {
const MemberPointerType *MPT = dyn_cast<MemberPointerType>(Ty);
const Type *PT = MPT->getPointeeType().getTypePtr();
return getBaseDeclFromType(PT);
}
case Type::SubstTemplateTypeParm: {
const SubstTemplateTypeParmType *TP =
dyn_cast<SubstTemplateTypeParmType>(Ty);
const Type *ST = TP->getReplacementType().getTypePtr();
return getBaseDeclFromType(ST);
}
case Type::DependentName: {
// It's not always the case that we could resolve a dependent name type.
// For example,
// template<typename T1, typename T2>
// struct AAA { typedef T2 new_type; };
// template<typename T3>
// struct BBB : public AAA<int, T3>::new_type { };
// In the above code, we can't figure out what new_type refers to
// until BBB is instantiated
// Due to this reason, simply return NULL from here.
return NULL;
}
case Type::TemplateTypeParm: {
// Yet another case we might not know the base class, e.g.,
// template<typename T1>
// class AAA {
// struct BBB : T1 {};
// };
return NULL;
}
case Type::Enum:
case Type::FunctionProto:
case Type::FunctionNoProto:
case Type::SubstTemplateTypeParmPack:
case Type::Builtin: // fall-through
return NULL;
default:
Base = Ty->getAsCXXRecordDecl();
TransAssert(Base && "Bad base class type!");
// getAsCXXRecordDecl could return a ClassTemplateSpecializationDecl.
// For example:
// template <class T> class AAA { };
// typedef AAA<int> BBB;
// class CCC : BBB { };
// In the above code, BBB is of type ClassTemplateSpecializationDecl
if (const ClassTemplateSpecializationDecl *CTSDecl =
dyn_cast<ClassTemplateSpecializationDecl>(Base)) {
Base = CTSDecl->getSpecializedTemplate()->getTemplatedDecl();
TransAssert(Base &&
"Bad base decl from ClassTemplateSpecializationDecl!");
}
}
return Base;
}
bool Transformation::isParameterPack(const NamedDecl *ND)
{
if (const NonTypeTemplateParmDecl *NonTypeD =
dyn_cast<NonTypeTemplateParmDecl>(ND)) {
return NonTypeD->isParameterPack();
}
else if (const TemplateTypeParmDecl *TypeD =
dyn_cast<TemplateTypeParmDecl>(ND)) {
return TypeD->isParameterPack();
}
else if (const TemplateTemplateParmDecl *TmplD =
dyn_cast<TemplateTemplateParmDecl>(ND)) {
return TmplD->isParameterPack();
}
else {
TransAssert(0 && "Unknown template parameter type!");
return false;
}
}
unsigned Transformation::getNumCtorWrittenInitializers(
const CXXConstructorDecl &Ctor)
{
unsigned Num = 0;
for (CXXConstructorDecl::init_const_iterator I = Ctor.init_begin(),
E = Ctor.init_end(); I != E; ++I) {
if ((*I)->isWritten())
Num++;
}
return Num;
}
bool Transformation::isBeforeColonColon(TypeLoc &Loc)
{
SourceLocation EndLoc = Loc.getEndLoc();
SourceLocation ColonColonLoc =
Lexer::findLocationAfterToken(EndLoc,
tok::coloncolon,
*SrcManager,
Context->getLangOpts(),
/*SkipTrailingWhitespaceAndNewLine=*/true);
return ColonColonLoc.isValid();
}
bool Transformation::replaceDependentNameString(const Type *Ty,
const TemplateArgument *Args,
unsigned NumArgs,
std::string &Str,
bool &Typename)
{
TransAssert((Ty->getTypeClass() == Type::DependentName) &&
"Not DependentNameType!");
const DependentNameType *DNT = dyn_cast<DependentNameType>(Ty);
const IdentifierInfo *IdInfo = DNT->getIdentifier();
if (!IdInfo)
return false;
const NestedNameSpecifier *Specifier = DNT->getQualifier();
if (!Specifier)
return false;
const Type *DependentTy = Specifier->getAsType();
if (!DependentTy)
return false;
const TemplateTypeParmType *ParmTy =
DependentTy->getAs<TemplateTypeParmType>();
if (!ParmTy)
return false;
unsigned Idx = ParmTy->getIndex();
TransAssert((Idx < NumArgs) && "Bad Parm Index!");
const TemplateArgument Arg = Args[Idx];
if (Arg.getKind() != TemplateArgument::Type)
return false;
QualType ArgQT = Arg.getAsType();
ArgQT.getAsStringInternal(Str, Context->getPrintingPolicy());
Str += "::";
Str += IdInfo->getName();
Typename = true;
return true;
}
bool Transformation::getTemplateTypeParmString(
const TemplateTypeParmType *ParmTy,
const TemplateArgument *Args,
unsigned NumArgs,
std::string &Str)
{
unsigned Idx = ParmTy->getIndex();
// we could have default template args, skip this case for now
if (Idx >= NumArgs)
return false;
const TemplateArgument Arg = Args[Idx];
if (Arg.getKind() != TemplateArgument::Type)
return false;
QualType ArgQT = Arg.getAsType();
ArgQT.getAsStringInternal(Str, Context->getPrintingPolicy());
return true;
}
bool Transformation::getTypedefString(const StringRef &Name,
const CXXRecordDecl *CXXRD,
const TemplateArgument *Args,
unsigned NumArgs,
std::string &Str,
bool &Typename)
{
Str = "";
for (DeclContext::decl_iterator I = CXXRD->decls_begin(),
E = CXXRD->decls_end(); I != E; ++I) {
const TypedefDecl *D = dyn_cast<TypedefDecl>(*I);
if (!D || (D->getNameAsString() != Name))
continue;
const Type *UnderlyingTy = D->getUnderlyingType().getTypePtr();
Type::TypeClass TC = UnderlyingTy->getTypeClass();
if (TC == Type::DependentName) {
if (replaceDependentNameString(UnderlyingTy, Args,
NumArgs, Str, Typename))
return true;
}
else if (const TemplateTypeParmType *ParmTy =
UnderlyingTy->getAs<TemplateTypeParmType>()) {
if (getTemplateTypeParmString(ParmTy, Args, NumArgs, Str))
return true;
}
}
// check base class
for (CXXRecordDecl::base_class_const_iterator I =
CXXRD->bases_begin(), E = CXXRD->bases_end(); I != E; ++I) {
const CXXBaseSpecifier *BS = I;
const Type *Ty = BS->getType().getTypePtr();
const CXXRecordDecl *Base = getBaseDeclFromType(Ty);
// it could happen if we have a dependent base specifier
if (!Base)
continue;
const CXXRecordDecl *BaseDef = Base->getDefinition();
if (!BaseDef)
continue;
if (getTypedefString(Name, BaseDef, Args, NumArgs, Str, Typename))
return true;
}
// TODO: really simplified lookup process, maybe need
// to check other decl context?
return false;
}
bool Transformation::getDependentNameTypeString(
const DependentNameType *DNT, std::string &Str, bool &Typename)
{
const IdentifierInfo *IdInfo = DNT->getIdentifier();
if (!IdInfo)
return false;
const NestedNameSpecifier *Specifier = DNT->getQualifier();
if (!Specifier)
return false;
const Type *Ty = Specifier->getAsType();
if (!Ty)
return false;
const CXXRecordDecl *Base = getBaseDeclFromType(Ty);
if (!Base)
return false;
const CXXRecordDecl *BaseDef = Base->getDefinition();
if (!BaseDef)
return false;
unsigned NumArgs = 0;
const TemplateArgument *Args = NULL;
if (const TemplateSpecializationType *TST =
Ty->getAs<TemplateSpecializationType>()) {
NumArgs = TST->getNumArgs();
Args = TST->getArgs();
}
return getTypedefString(IdInfo->getName(),
BaseDef, Args, NumArgs, Str, Typename);
}
bool Transformation::getTypeString(const QualType &QT,
std::string &Str,
bool &Typename)
{
const Type *Ty = QT.getTypePtr();
Type::TypeClass TC = Ty->getTypeClass();
switch (TC) {
case Type::SubstTemplateTypeParm: {
const SubstTemplateTypeParmType *TP =
dyn_cast<SubstTemplateTypeParmType>(Ty);
return getTypeString(TP->getReplacementType(), Str, Typename);
}
case Type::Elaborated: {
const ElaboratedType *ETy = dyn_cast<ElaboratedType>(Ty);
return getTypeString(ETy->getNamedType(), Str, Typename);
}
case Type::Typedef: {
const TypedefType *TdefTy = dyn_cast<TypedefType>(Ty);
const TypedefNameDecl *TdefD = TdefTy->getDecl();
return getTypeString(TdefD->getUnderlyingType(), Str, Typename);
}
case Type::DependentName: {