forked from vgvassilev/creduce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimplifyStruct.cpp
333 lines (274 loc) · 9.68 KB
/
SimplifyStruct.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
//===----------------------------------------------------------------------===//
//
// Copyright (c) 2012, 2013 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 "SimplifyStruct.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Lex/Lexer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/SourceManager.h"
#include "clang/AST/RecordLayout.h"
#include "TransformationManager.h"
using namespace clang;
using namespace llvm;
static const char *DescriptionMsg =
"This pass replaces a struct with its parent if it has only one \
field, and this field is a struct, e.g, \n\
struct S1 { \n\
int f1;\n\
int f2;\n\
}\n\
struct S2 { \n\
struct S1 f1;\n\
} \n\
In the above code, struct S2 will be replaced with struct S1, including\n\
all its referenced. \n";
static RegisterTransformation<SimplifyStruct>
Trans("simplify-struct", DescriptionMsg);
class SimplifyStructCollectionVisitor : public
RecursiveASTVisitor<SimplifyStructCollectionVisitor> {
public:
explicit SimplifyStructCollectionVisitor(SimplifyStruct *Instance)
: ConsumerInstance(Instance)
{ }
bool VisitRecordDecl(RecordDecl *RD);
private:
SimplifyStruct *ConsumerInstance;
};
class SimplifyStructRewriteVisitor : public
RecursiveASTVisitor<SimplifyStructRewriteVisitor> {
public:
explicit SimplifyStructRewriteVisitor(SimplifyStruct *Instance)
: ConsumerInstance(Instance)
{ }
bool VisitVarDecl(VarDecl *VD);
bool VisitRecordDecl(RecordDecl *RD);
bool VisitRecordTypeLoc(RecordTypeLoc RTLoc);
bool VisitMemberExpr(MemberExpr *ME);
private:
SimplifyStruct *ConsumerInstance;
};
bool SimplifyStructCollectionVisitor::VisitRecordDecl(RecordDecl *RD)
{
if (!RD->isThisDeclarationADefinition() || !RD->isStruct())
return true;
if (ConsumerInstance->isSpecialRecordDecl(RD))
return true;
if (RD->isInvalidDecl())
return true;
const ASTRecordLayout &Info = ConsumerInstance->Context->getASTRecordLayout(RD);
unsigned Count = Info.getFieldCount();
if (Count != 1)
return true;
const FieldDecl *FD = *(RD->field_begin());
TransAssert(FD && "Invalid FieldDecl!");
const Type *Ty = FD->getType().getTypePtr();
const RecordType *RT = Ty->getAs<RecordType>();
if (!RT)
return true;
const RecordDecl *NestedRD = RT->getDecl();
if (NestedRD->getNameAsString() == "")
return true;
ConsumerInstance->ValidInstanceNum++;
if (ConsumerInstance->TransformationCounter ==
ConsumerInstance->ValidInstanceNum) {
ConsumerInstance->TheRecordDecl =
dyn_cast<RecordDecl>(RD->getCanonicalDecl());
ConsumerInstance->ReplacingRecordDecl =
dyn_cast<RecordDecl>(NestedRD->getCanonicalDecl());
ConsumerInstance->setQualifierFlags(FD);
}
return true;
}
bool SimplifyStructRewriteVisitor::VisitVarDecl(VarDecl *VD)
{
if (!ConsumerInstance->ConstField && !ConsumerInstance->VolatileField)
return true;
QualType QT = VD->getType();
const Type *Ty = QT.getTypePtr();
const RecordType *RT = Ty->getAs<RecordType>();
if (!RT)
return true;
const RecordDecl *RD = RT->getDecl();
if (RD != ConsumerInstance->TheRecordDecl)
return true;
SourceLocation LocStart = VD->getLocStart();
void *LocPtr = LocStart.getPtrEncoding();
if (ConsumerInstance->VisitedVarDeclLocs.count(LocPtr))
return true;
ConsumerInstance->VisitedVarDeclLocs.insert(LocPtr);
std::string QualStr = "";
if (ConsumerInstance->ConstField && !QT.isConstQualified())
QualStr += "const ";
if (ConsumerInstance->VolatileField && !QT.isVolatileQualified())
QualStr += "volatile ";
ConsumerInstance->TheRewriter.InsertText(LocStart, QualStr);
return true;
}
bool SimplifyStructRewriteVisitor::VisitRecordDecl(RecordDecl *RD)
{
RecordDecl *CanonicalRD = dyn_cast<RecordDecl>(RD->getCanonicalDecl());
if (CanonicalRD != ConsumerInstance->TheRecordDecl)
return true;
SourceLocation LocStart = RD->getLocation();
void *LocPtr = LocStart.getPtrEncoding();
if (!ConsumerInstance->VisitedLocs.count(LocPtr)) {
ConsumerInstance->VisitedLocs.insert(LocPtr);
std::string RPName =
ConsumerInstance->ReplacingRecordDecl->getNameAsString();
if (RD->getNameAsString() != "") {
ConsumerInstance->RewriteHelper->replaceRecordDeclName(RD, RPName);
}
else {
ConsumerInstance->TheRewriter.ReplaceText(LocStart,
/*struct*/6, "struct " + RPName);
}
}
if (!RD->isThisDeclarationADefinition())
return true;
SourceLocation LBLoc =
ConsumerInstance->RewriteHelper->getLocationUntil(RD->getLocation(), '{');
SourceLocation RBLoc = RD->getRBraceLoc();
ConsumerInstance->TheRewriter.RemoveText(SourceRange(LBLoc, RBLoc));
return true;
}
bool SimplifyStructRewriteVisitor::VisitRecordTypeLoc(RecordTypeLoc RTLoc)
{
const Type *Ty = RTLoc.getTypePtr();
if (Ty->isUnionType())
return true;
RecordDecl *RD = RTLoc.getDecl();
RecordDecl *CanonicalRD = dyn_cast<RecordDecl>(RD->getCanonicalDecl());
if (CanonicalRD != ConsumerInstance->TheRecordDecl)
return true;
SourceLocation LocStart = RTLoc.getLocStart();
void *LocPtr = LocStart.getPtrEncoding();
if (ConsumerInstance->VisitedLocs.count(LocPtr))
return true;
ConsumerInstance->VisitedLocs.insert(LocPtr);
ConsumerInstance->RewriteHelper->replaceRecordType(RTLoc,
ConsumerInstance->ReplacingRecordDecl->getNameAsString());
return true;
}
bool SimplifyStructRewriteVisitor::VisitMemberExpr(MemberExpr *ME)
{
ValueDecl *OrigDecl = ME->getMemberDecl();
FieldDecl *FD = dyn_cast<FieldDecl>(OrigDecl);
if (!FD) {
// in C++, getMemberDecl returns a CXXMethodDecl.
if (TransformationManager::isCXXLangOpt())
return true;
TransAssert(0 && "Bad FD!\n");
}
RecordDecl *RD = FD->getParent();
if (!RD || (dyn_cast<RecordDecl>(RD->getCanonicalDecl()) !=
ConsumerInstance->TheRecordDecl))
return true;
const Type *T = FD->getType().getTypePtr();
const RecordType *RT = T->getAs<RecordType>();
TransAssert(RT && "Invalid record type!");
const RecordDecl *ReplacingRD =
dyn_cast<RecordDecl>(RT->getDecl()->getCanonicalDecl());
(void)ReplacingRD;
TransAssert((ReplacingRD == ConsumerInstance->ReplacingRecordDecl) &&
"Unmatched Replacing RD!");
SourceLocation LocEnd = ME->getLocEnd();
SourceLocation ArrowPos =
Lexer::findLocationAfterToken(LocEnd,
tok::arrow,
*(ConsumerInstance->SrcManager),
ConsumerInstance->Context->getLangOpts(),
/*SkipTrailingWhitespaceAndNewLine=*/true);
SourceLocation PeriodPos =
Lexer::findLocationAfterToken(LocEnd,
tok::period,
*(ConsumerInstance->SrcManager),
ConsumerInstance->Context->getLangOpts(),
/*SkipTrailingWhitespaceAndNewLine=*/true);
std::string ES;
ConsumerInstance->RewriteHelper->getExprString(ME, ES);
// no more MemberExpr upon this ME
if (ArrowPos.isInvalid() && PeriodPos.isInvalid()) {
SourceLocation StartLoc = ME->getLocStart();
size_t Pos;
if (ME->isArrow()) {
Pos = ES.find("->");
}
else {
Pos = ES.find(".");
}
TransAssert((Pos != std::string::npos) && "Cannot find arrow or dot!");
StartLoc = StartLoc.getLocWithOffset(Pos);
int Off = ES.length() - Pos;
ConsumerInstance->TheRewriter.RemoveText(StartLoc, Off);
return true;
}
SourceLocation StartLoc = ME->getMemberLoc();
const char *StartBuf =
ConsumerInstance->SrcManager->getCharacterData(StartLoc);
const char *EndBuf;
if (ArrowPos.isValid()) {
EndBuf = ConsumerInstance->SrcManager->getCharacterData(ArrowPos);
EndBuf++;
}
else {
TransAssert(PeriodPos.isValid() && "Bad dot position!");
EndBuf = ConsumerInstance->SrcManager->getCharacterData(PeriodPos);
}
int Off = EndBuf - StartBuf;
ConsumerInstance->TheRewriter.RemoveText(StartLoc, Off);
return true;
}
void SimplifyStruct::Initialize(ASTContext &context)
{
Transformation::Initialize(context);
CollectionVisitor = new SimplifyStructCollectionVisitor(this);
RewriteVisitor = new SimplifyStructRewriteVisitor(this);
}
void SimplifyStruct::HandleTranslationUnit(ASTContext &Ctx)
{
// ISSUE: not well tested on CXX code, so currently disable this pass for CXX
if (TransformationManager::isCXXLangOpt()) {
ValidInstanceNum = 0;
TransError = TransMaxInstanceError;
return;
}
TransAssert(CollectionVisitor && "NULL CollectionVisitor!");
CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
if (QueryInstanceOnly) {
return;
}
if (TransformationCounter > ValidInstanceNum) {
TransError = TransMaxInstanceError;
return;
}
Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
TransAssert(RewriteVisitor && "NULL RewriteVisitor!");
TransAssert(TheRecordDecl && "NULL TheRecordDecl!");
TransAssert(ReplacingRecordDecl && "NULL ReplacingRecordDecl!");
RewriteVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
if (Ctx.getDiagnostics().hasErrorOccurred() ||
Ctx.getDiagnostics().hasFatalErrorOccurred())
TransError = TransInternalError;
}
void SimplifyStruct::setQualifierFlags(const FieldDecl *FD)
{
QualType QT = FD->getType();
if (QT.isConstQualified())
ConstField = true;
if (QT.isVolatileQualified())
VolatileField = true;
}
SimplifyStruct::~SimplifyStruct(void)
{
delete CollectionVisitor;
delete RewriteVisitor;
}