forked from vgvassilev/creduce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EmptyStructToInt.cpp
357 lines (310 loc) · 10.6 KB
/
EmptyStructToInt.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
//===----------------------------------------------------------------------===//
//
// 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 "EmptyStructToInt.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/ASTContext.h"
#include "TransformationManager.h"
using namespace clang;
using namespace llvm;
static const char *DescriptionMsg =
"Replace an empty struct with type of int. A struct is defined to be empty if \
it: \
* does not have any field; \n\
* does not have any base class; \n\
* is not a base class of another class; \n\
* is not described by any template; \n\
* has only one unreferenced field; \n\
* doesn't have self pointer reference\n";
static RegisterTransformation<EmptyStructToInt>
Trans("empty-struct-to-int", DescriptionMsg);
class EmptyStructToIntASTVisitor : public
RecursiveASTVisitor<EmptyStructToIntASTVisitor> {
public:
explicit EmptyStructToIntASTVisitor(EmptyStructToInt *Instance)
: ConsumerInstance(Instance)
{ }
bool VisitRecordDecl(RecordDecl *RD);
bool VisitCXXRecordDecl(CXXRecordDecl *CXXRD);
private:
EmptyStructToInt *ConsumerInstance;
};
class EmptyStructToIntRewriteVisitor : public
RecursiveASTVisitor<EmptyStructToIntRewriteVisitor> {
public:
explicit EmptyStructToIntRewriteVisitor(EmptyStructToInt *Instance)
: ConsumerInstance(Instance)
{ }
bool VisitRecordTypeLoc(RecordTypeLoc RTLoc);
bool VisitElaboratedTypeLoc(ElaboratedTypeLoc Loc);
private:
EmptyStructToInt *ConsumerInstance;
};
bool EmptyStructToIntASTVisitor::VisitRecordDecl(RecordDecl *RD)
{
if (!ConsumerInstance->isValidRecordDecl(RD))
return true;
const RecordDecl *CanonicalRD = dyn_cast<RecordDecl>(RD->getCanonicalDecl());
if (ConsumerInstance->VisitedRecordDecls.count(CanonicalRD))
return true;
ConsumerInstance->VisitedRecordDecls.insert(CanonicalRD);
return true;
}
bool EmptyStructToIntASTVisitor::VisitCXXRecordDecl(CXXRecordDecl *CXXRD)
{
const CXXRecordDecl *CanonicalRD = CXXRD->getCanonicalDecl();
if (ConsumerInstance->VisitedRecordDecls.count(CanonicalRD))
return true;
if (!CanonicalRD->hasDefinition())
return true;
for (CXXRecordDecl::base_class_const_iterator I =
CanonicalRD->bases_begin(), E = CanonicalRD->bases_end(); I != E; ++I) {
const CXXBaseSpecifier *BS = I;
const Type *Ty = BS->getType().getTypePtr();
const CXXRecordDecl *Base = ConsumerInstance->getBaseDeclFromType(Ty);
if (Base)
ConsumerInstance->BaseClassDecls.insert(Base->getCanonicalDecl());
}
return true;
}
bool EmptyStructToIntRewriteVisitor::VisitRecordTypeLoc(RecordTypeLoc RTLoc)
{
const RecordDecl *RD = RTLoc.getDecl();
if (RD->getCanonicalDecl() == ConsumerInstance->TheRecordDecl) {
SourceLocation LocStart = RTLoc.getLocStart();
void *LocPtr = LocStart.getPtrEncoding();
if (ConsumerInstance->VisitedLocs.count(LocPtr))
return true;
ConsumerInstance->VisitedLocs.insert(LocPtr);
// handle a special case -
// struct S1 {
// struct { } S;
// };
const IdentifierInfo *TypeId = RTLoc.getType().getBaseTypeIdentifier();
if (!TypeId)
return true;
ConsumerInstance->RewriteHelper->replaceRecordType(RTLoc, "int");
ConsumerInstance->Rewritten = true;
}
return true;
}
bool EmptyStructToIntRewriteVisitor::VisitElaboratedTypeLoc(
ElaboratedTypeLoc Loc)
{
const ElaboratedType *ETy = dyn_cast<ElaboratedType>(Loc.getTypePtr());
const Type *NamedTy = ETy->getNamedType().getTypePtr();
const RecordType *RDTy = NamedTy->getAs<RecordType>();
if (!RDTy)
return true;
const RecordDecl *RD = RDTy->getDecl();
TransAssert(RD && "NULL RecordDecl!");
if (RD->getCanonicalDecl() != ConsumerInstance->TheRecordDecl) {
return true;
}
SourceLocation StartLoc = Loc.getLocStart();
if (StartLoc.isInvalid())
return true;
TypeLoc TyLoc = Loc.getNamedTypeLoc();
SourceLocation EndLoc = TyLoc.getLocStart();
if (EndLoc.isInvalid())
return true;
EndLoc = EndLoc.getLocWithOffset(-1);
const char *StartBuf =
ConsumerInstance->SrcManager->getCharacterData(StartLoc);
const char *EndBuf = ConsumerInstance->SrcManager->getCharacterData(EndLoc);
ConsumerInstance->Rewritten = true;
// It's possible, e.g.,
// struct S1 {
// struct { } S;
// };
// Clang will translate struct { } S to
// struct {
// };
// struct <anonymous struct ...> S;
// the last declaration is injected by clang.
// We need to omit it.
if (StartBuf > EndBuf) {
SourceLocation KeywordLoc = Loc.getElaboratedKeywordLoc();
const char *Keyword = TypeWithKeyword::getKeywordName(ETy->getKeyword());
ConsumerInstance->TheRewriter.ReplaceText(KeywordLoc,
strlen(Keyword), "int");
return true;
}
ConsumerInstance->TheRewriter.RemoveText(SourceRange(StartLoc, EndLoc));
return true;
}
void EmptyStructToInt::Initialize(ASTContext &context)
{
Transformation::Initialize(context);
CollectionVisitor = new EmptyStructToIntASTVisitor(this);
RewriteVisitor = new EmptyStructToIntRewriteVisitor(this);
}
void EmptyStructToInt::HandleTranslationUnit(ASTContext &Ctx)
{
CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
doAnalysis();
if (QueryInstanceOnly)
return;
if (TransformationCounter > ValidInstanceNum) {
TransError = TransMaxInstanceError;
return;
}
Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
removeRecordDecls();
RewriteVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
// sanity check that we actually
// have done some text modifications.
// It could be false due to invalid code being transformed.
if (!Rewritten) {
TransError = TransNoTextModificationError;
return;
}
if (Ctx.getDiagnostics().hasErrorOccurred() ||
Ctx.getDiagnostics().hasFatalErrorOccurred())
TransError = TransInternalError;
}
void EmptyStructToInt::doAnalysis(void)
{
for (RecordDeclSet::const_iterator I = VisitedRecordDecls.begin(),
E = VisitedRecordDecls.end(); I != E; ++I) {
const RecordDecl *RD = (*I);
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
if (BaseClassDecls.count(CXXRD->getCanonicalDecl()))
continue;
}
ValidInstanceNum++;
if (ValidInstanceNum == TransformationCounter)
TheRecordDecl = RD;
}
}
// ISSUE: we will have bad transformation for the case below:
// typedef struct S;
// S *s;
// ==>
// typedef
// int *s;
// This is bad because we don't catch the implicit declaration of struct S.
// But hopefully peephole pass will remove the keyword typedef,
// then we will be fine.
void EmptyStructToInt::removeRecordDecls(void)
{
for (RecordDecl::redecl_iterator I = TheRecordDecl->redecls_begin(),
E = TheRecordDecl->redecls_end(); I != E; ++I) {
const RecordDecl *RD = dyn_cast<RecordDecl>(*I);
SourceRange Range = RD->getSourceRange();
SourceLocation LocEnd = Range.getEnd();
SourceLocation SemiLoc =
Lexer::findLocationAfterToken(LocEnd,
tok::semi,
*SrcManager,
Context->getLangOpts(),
/*SkipTrailingWhitespaceAndNewLine=*/true);
// handle cases such as
// struct S {} s;
if (SemiLoc.isInvalid()) {
if (!RD->isThisDeclarationADefinition())
return;
SourceLocation RBLoc = RD->getRBraceLoc();
if (RBLoc.isInvalid())
return;
RewriteHelper->removeTextFromLeftAt(SourceRange(RBLoc, RBLoc),
'{', RBLoc);
Rewritten = true;
}
else {
LocEnd = RewriteHelper->getEndLocationUntil(Range, ';');
TheRewriter.RemoveText(SourceRange(Range.getBegin(), LocEnd));
Rewritten = true;
}
}
}
bool EmptyStructToInt::pointToSelf(const FieldDecl *FD)
{
const Type *Ty = FD->getType().getTypePtr();
if (!Ty->isPointerType())
return false;
const Type *PointeeTy = getBasePointerElemType(Ty);
if (TransformationManager::isCXXLangOpt()) {
const CXXRecordDecl *Base = getBaseDeclFromType(Ty);
if (!Base)
return false;
const CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(FD->getParent());
TransAssert(Parent && "Invalid Parent!");
return (Parent->getCanonicalDecl() == Base->getCanonicalDecl());
}
const RecordType *RT = PointeeTy->getAs<RecordType>();
if (!RT)
return false;
const RecordDecl *RD = RT->getDecl();
const RecordDecl *Parent = FD->getParent();
return (Parent->getCanonicalDecl() == RD->getCanonicalDecl());
}
bool EmptyStructToInt::isValidRecordDecl(const RecordDecl *RD)
{
const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
if (!CXXRD) {
const RecordDecl *Def = RD->getDefinition();
if (!Def) {
return true;
}
else if (Def->field_empty()) {
return true;
}
else {
// skip invalid decl, which causes clang assertion errors
if (Def->isInvalidDecl())
return false;
// handle another special case where a struct has an unreferenced
// field. In some cases, we cannot simply remove this field
// because an empty struct would make a bug disappear.
const ASTRecordLayout &Info = Context->getASTRecordLayout(Def);
unsigned Count = Info.getFieldCount();
if (Count != 1)
return false;
const FieldDecl *FD = *(Def->field_begin());
TransAssert(FD && "Invalid FieldDecl");
// skip case such as
// struct S { struct S *p; };
if (pointToSelf(FD))
return false;
return !FD->isReferenced();
}
}
if (dyn_cast<ClassTemplateSpecializationDecl>(CXXRD) ||
CXXRD->getDescribedClassTemplate() ||
CXXRD->getInstantiatedFromMemberClass())
return false;
// It's possible that the described template does not
// have definition, so we test hasDefinition after the
// above `if' guard
const CXXRecordDecl *CXXDef = CXXRD->getDefinition();
if (!CXXDef)
return true;
if(CXXDef->getNumBases())
return false;
const DeclContext *Ctx = dyn_cast<DeclContext>(CXXDef);
TransAssert(Ctx && "Invalid DeclContext!");
for (DeclContext::decl_iterator I = Ctx->decls_begin(),
E = Ctx->decls_end(); I != E; ++I) {
if (!(*I)->isImplicit())
return false;
}
return true;
}
EmptyStructToInt::~EmptyStructToInt(void)
{
delete CollectionVisitor;
delete RewriteVisitor;
}