36
36
"macro names that behave like NULL"),
37
37
llvm::cl::init(""));
39
bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc,
40
const SourceManager &SM) {
41
return SM.isFromSameFile(StartLoc, EndLoc) && SM.isFromMainFile(StartLoc);
39
44
/// \brief Replaces the provided range with the text "nullptr", but only if
40
45
/// the start and end location are both in main file.
41
46
/// Returns true if and only if a replacement was made.
42
bool ReplaceWithNullptr(tooling::Replacements &Replace, SourceManager &SM,
47
void ReplaceWithNullptr(tooling::Replacements &Replace, SourceManager &SM,
43
48
SourceLocation StartLoc, SourceLocation EndLoc) {
44
if (SM.isFromSameFile(StartLoc, EndLoc) && SM.isFromMainFile(StartLoc)) {
45
CharSourceRange Range(SourceRange(StartLoc, EndLoc), true);
46
// Add a space if nullptr follows an alphanumeric character. This happens
47
// whenever there is an c-style explicit cast to nullptr not surrounded by
48
// parentheses and right beside a return statement.
49
SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1);
50
if (isAlphanumeric(*FullSourceLoc(PreviousLocation, SM).getCharacterData()))
51
Replace.insert(tooling::Replacement(SM, Range, " nullptr"));
53
Replace.insert(tooling::Replacement(SM, Range, "nullptr"));
49
CharSourceRange Range(SourceRange(StartLoc, EndLoc), true);
50
// Add a space if nullptr follows an alphanumeric character. This happens
51
// whenever there is an c-style explicit cast to nullptr not surrounded by
52
// parentheses and right beside a return statement.
53
SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1);
54
if (isAlphanumeric(*FullSourceLoc(PreviousLocation, SM).getCharacterData()))
55
Replace.insert(tooling::Replacement(SM, Range, " nullptr"));
57
Replace.insert(tooling::Replacement(SM, Range, "nullptr"));
59
60
/// \brief Returns the name of the outermost macro.
76
77
return clang::Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO);
80
/// \brief RecursiveASTVisitor for ensuring all nodes rooted at a given AST
81
/// subtree that have file-level source locations corresponding to a macro
82
/// argument have implicit NullTo(Member)Pointer nodes as ancestors.
83
class MacroArgUsageVisitor : public RecursiveASTVisitor<MacroArgUsageVisitor> {
85
MacroArgUsageVisitor(SourceLocation CastLoc, const SourceManager &SM)
86
: CastLoc(CastLoc), SM(SM), Visited(false), CastFound(false),
88
assert(CastLoc.isFileID());
91
bool TraverseStmt(Stmt *S) {
92
bool VisitedPreviously = Visited;
94
if (!RecursiveASTVisitor<MacroArgUsageVisitor>::TraverseStmt(S))
97
// The point at which VisitedPreviously is false and Visited is true is the
98
// root of a subtree containing nodes whose locations match CastLoc. It's
99
// at this point we test that the Implicit NullTo(Member)Pointer cast was
101
if (!VisitedPreviously) {
102
if (Visited && !CastFound) {
103
// Found nodes with matching SourceLocations but didn't come across a
104
// cast. This is an invalid macro arg use. Can stop traversal
109
// Reset state as we unwind back up the tree.
116
bool VisitStmt(Stmt *S) {
117
if (SM.getFileLoc(S->getLocStart()) != CastLoc)
121
const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(S);
122
if (Cast && (Cast->getCastKind() == CK_NullToPointer ||
123
Cast->getCastKind() == CK_NullToMemberPointer))
129
bool foundInvalid() const { return InvalidFound; }
132
SourceLocation CastLoc;
133
const SourceManager &SM;
80
140
/// \brief Looks for implicit casts as well as sequences of 0 or more explicit
81
141
/// casts with an implicit null-to-pointer cast within.
114
183
SourceLocation StartLoc = FirstSubExpr->getLocStart();
115
184
SourceLocation EndLoc = FirstSubExpr->getLocEnd();
117
// If the start/end location is a macro argument expansion, get the
118
// expansion location. If its a macro body expansion, check to see if its
119
// coming from a macro called NULL.
186
// If the location comes from a macro arg expansion, *all* uses of that
187
// arg must be checked to result in NullTo(Member)Pointer casts.
189
// If the location comes from a macro body expansion, check to see if its
190
// coming from one of the allowed 'NULL' macros.
120
191
if (SM.isMacroArgExpansion(StartLoc) && SM.isMacroArgExpansion(EndLoc)) {
121
StartLoc = SM.getFileLoc(StartLoc);
122
EndLoc = SM.getFileLoc(EndLoc);
123
} else if (SM.isMacroBodyExpansion(StartLoc) &&
124
SM.isMacroBodyExpansion(EndLoc)) {
192
SourceLocation FileLocStart = SM.getFileLoc(StartLoc),
193
FileLocEnd = SM.getFileLoc(EndLoc);
194
if (isReplaceableRange(FileLocStart, FileLocEnd, SM) &&
195
allArgUsesValid(C)) {
196
ReplaceWithNullptr(Replace, SM, FileLocStart, FileLocEnd);
199
return skipSubTree();
202
if (SM.isMacroBodyExpansion(StartLoc) &&
203
SM.isMacroBodyExpansion(EndLoc)) {
125
204
llvm::StringRef OutermostMacroName =
126
GetOutermostMacroName(StartLoc, SM, LangOpts);
205
GetOutermostMacroName(StartLoc, SM, Context.getLangOpts());
128
207
// Check to see if the user wants to replace the macro being expanded.
129
bool ReplaceNullMacro =
130
std::find(UserNullMacros.begin(), UserNullMacros.end(),
131
OutermostMacroName) != UserNullMacros.end();
133
if (!ReplaceNullMacro)
208
if (std::find(UserNullMacros.begin(), UserNullMacros.end(),
209
OutermostMacroName) == UserNullMacros.end()) {
210
return skipSubTree();
136
213
StartLoc = SM.getFileLoc(StartLoc);
137
214
EndLoc = SM.getFileLoc(EndLoc);
141
ReplaceWithNullptr(Replace, SM, StartLoc, EndLoc) ? 1 : 0;
217
if (!isReplaceableRange(StartLoc, EndLoc, SM)) {
218
return skipSubTree();
220
ReplaceWithNullptr(Replace, SM, StartLoc, EndLoc);
223
return skipSubTree();
224
} // If NullTo(Member)Pointer cast.
150
void ResetFirstSubExpr() { FirstSubExpr = 0; }
230
bool skipSubTree() { PruneSubtree = true; return true; }
232
/// \brief Tests that all expansions of a macro arg, one of which expands to
233
/// result in \p CE, yield NullTo(Member)Pointer casts.
234
bool allArgUsesValid(const CastExpr *CE) {
235
SourceLocation CastLoc = CE->getLocStart();
237
// Step 1: Get location of macro arg and location of the macro the arg was
239
SourceLocation ArgLoc, MacroLoc;
240
if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc))
243
// Step 2: Find the first ancestor that doesn't expand from this macro.
244
ast_type_traits::DynTypedNode ContainingAncestor;
245
if (!findContainingAncestor(
246
ast_type_traits::DynTypedNode::create<Stmt>(*CE), MacroLoc,
251
// Visit children of this containing parent looking for the least-descended
252
// nodes of the containing parent which are macro arg expansions that expand
253
// from the given arg location.
254
// Visitor needs: arg loc
255
MacroArgUsageVisitor ArgUsageVisitor(SM.getFileLoc(CastLoc), SM);
256
if (const Decl *D = ContainingAncestor.get<Decl>())
257
ArgUsageVisitor.TraverseDecl(const_cast<Decl *>(D));
258
else if (const Stmt *S = ContainingAncestor.get<Stmt>())
259
ArgUsageVisitor.TraverseStmt(const_cast<Stmt *>(S));
261
llvm_unreachable("Unhandled ContainingAncestor node type");
263
if (ArgUsageVisitor.foundInvalid())
269
/// \brief Given the SourceLocation for a macro arg expansion, finds the
270
/// non-macro SourceLocation of the macro the arg was passed to and the
271
/// non-macro SourceLocation of the argument in the arg list to that macro.
272
/// These results are returned via \c MacroLoc and \c ArgLoc respectively.
273
/// These values are undefined if the return value is false.
275
/// \returns false if one of the returned SourceLocations would be a
276
/// SourceLocation pointing within the definition of another macro.
277
bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc,
278
SourceLocation &MacroLoc) {
279
assert(Loc.isMacroID() && "Only reasonble to call this on macros");
283
// Find the location of the immediate macro expansion.
285
std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ArgLoc);
286
const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
287
const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
289
SourceLocation OldArgLoc = ArgLoc;
290
ArgLoc = Expansion.getExpansionLocStart();
291
if (!Expansion.isMacroArgExpansion()) {
292
if (!MacroLoc.isFileID())
296
Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts());
297
return std::find(UserNullMacros.begin(), UserNullMacros.end(), Name) !=
298
UserNullMacros.end();
301
MacroLoc = SM.getImmediateExpansionRange(ArgLoc).first;
303
ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
304
if (ArgLoc.isFileID())
307
// If spelling location resides in the same FileID as macro expansion
308
// location, it means there is no inner macro.
309
FileID MacroFID = SM.getFileID(MacroLoc);
310
if (SM.isInFileID(ArgLoc, MacroFID))
311
// Don't transform this case. If the characters that caused the
312
// null-conversion come from within a macro, they can't be changed.
316
llvm_unreachable("getMacroAndArgLocations");
319
/// \brief Tests if TestMacroLoc is found while recursively unravelling
320
/// expansions starting at TestLoc. TestMacroLoc.isFileID() must be true.
321
/// Implementation is very similar to getMacroAndArgLocations() except in this
322
/// case, it's not assumed that TestLoc is expanded from a macro argument.
323
/// While unravelling expansions macro arguments are handled as with
324
/// getMacroAndArgLocations() but in this function macro body expansions are
327
/// False means either:
328
/// - TestLoc is not from a macro expansion
329
/// - TestLoc is from a different macro expansion
330
bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) {
331
if (TestLoc.isFileID()) {
335
SourceLocation Loc = TestLoc, MacroLoc;
338
std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
339
const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
340
const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
342
Loc = Expansion.getExpansionLocStart();
344
if (!Expansion.isMacroArgExpansion()) {
345
if (Loc.isFileID()) {
346
if (Loc == TestMacroLoc)
351
// Since Loc is still a macro ID and it's not an argument expansion, we
352
// don't need to do the work of handling an argument expansion. Simply
353
// keep recursively expanding until we hit a FileID or a macro arg
354
// expansion or a macro arg expansion.
358
MacroLoc = SM.getImmediateExpansionRange(Loc).first;
359
if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc)
363
Loc = Expansion.getSpellingLoc();
364
Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
366
// If we made it this far without finding a match, there is no match to
371
llvm_unreachable("expandsFrom");
374
/// \brief Given a starting point \c Start in the AST, find an ancestor that
375
/// doesn't expand from the macro called at file location \c MacroLoc.
377
/// \pre MacroLoc.isFileID()
378
/// \returns true if such an ancestor was found, false otherwise.
379
bool findContainingAncestor(ast_type_traits::DynTypedNode Start,
380
SourceLocation MacroLoc,
381
ast_type_traits::DynTypedNode &Result) {
382
// Below we're only following the first parent back up the AST. This should
383
// be fine since for the statements we care about there should only be one
384
// parent as far up as we care. If this assumption doesn't hold, need to
385
// revisit what to do here.
387
assert(MacroLoc.isFileID());
390
ASTContext::ParentVector Parents = Context.getParents(Start);
393
assert(Parents.size() == 1 &&
394
"Found an ancestor with more than one parent!");
396
ASTContext::ParentVector::const_iterator I = Parents.begin();
399
if (const Decl *D = I->get<Decl>())
400
Loc = D->getLocStart();
401
else if (const Stmt *S = I->get<Stmt>())
402
Loc = S->getLocStart();
404
llvm_unreachable("Expected to find Decl or Stmt containing ancestor");
406
if (!expandsFrom(Loc, MacroLoc)) {
413
llvm_unreachable("findContainingAncestor");
153
417
tooling::Replacements &Replace;
154
418
SourceManager &SM;
155
const LangOptions &LangOpts;
156
420
const UserMacroNames &UserNullMacros;
157
421
unsigned &AcceptedChanges;
158
422
Expr *FirstSubExpr;
161
427
NullptrFixer::NullptrFixer(clang::tooling::Replacements &Replace,
162
428
unsigned &AcceptedChanges, RiskLevel)