Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Lex/MacroArgs.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- MacroArgs.cpp - Formal argument info for Macros ------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the MacroArgs interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Lex/MacroArgs.h"
14
#include "clang/Lex/LexDiagnostic.h"
15
#include "clang/Lex/MacroInfo.h"
16
#include "clang/Lex/Preprocessor.h"
17
#include "llvm/ADT/SmallString.h"
18
#include "llvm/Support/SaveAndRestore.h"
19
#include <algorithm>
20
21
using namespace clang;
22
23
/// MacroArgs ctor function - This destroys the vector passed in.
24
MacroArgs *MacroArgs::create(const MacroInfo *MI,
25
                             ArrayRef<Token> UnexpArgTokens,
26
4.47M
                             bool VarargsElided, Preprocessor &PP) {
27
4.47M
  assert(MI->isFunctionLike() &&
28
4.47M
         "Can't have args for an object-like macro!");
29
4.47M
  MacroArgs **ResultEnt = nullptr;
30
4.47M
  unsigned ClosestMatch = ~0U;
31
4.47M
32
4.47M
  // See if we have an entry with a big enough argument list to reuse on the
33
4.47M
  // free list.  If so, reuse it.
34
15.8M
  for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;
35
15.5M
       
Entry = &(*Entry)->ArgCache11.3M
) {
36
15.5M
    if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
37
15.5M
        
(*Entry)->NumUnexpArgTokens < ClosestMatch9.38M
) {
38
6.92M
      ResultEnt = Entry;
39
6.92M
40
6.92M
      // If we have an exact match, use it.
41
6.92M
      if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
42
4.15M
        break;
43
2.76M
      // Otherwise, use the best fit.
44
2.76M
      ClosestMatch = (*Entry)->NumUnexpArgTokens;
45
2.76M
    }
46
15.5M
  }
47
4.47M
  MacroArgs *Result;
48
4.47M
  if (!ResultEnt) {
49
114k
    // Allocate memory for a MacroArgs object with the lexer tokens at the end,
50
114k
    // and construct the MacroArgs object.
51
114k
    Result = new (
52
114k
        llvm::safe_malloc(totalSizeToAlloc<Token>(UnexpArgTokens.size())))
53
114k
        MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumParams());
54
4.36M
  } else {
55
4.36M
    Result = *ResultEnt;
56
4.36M
    // Unlink this node from the preprocessors singly linked list.
57
4.36M
    *ResultEnt = Result->ArgCache;
58
4.36M
    Result->NumUnexpArgTokens = UnexpArgTokens.size();
59
4.36M
    Result->VarargsElided = VarargsElided;
60
4.36M
    Result->NumMacroArgs = MI->getNumParams();
61
4.36M
  }
62
4.47M
63
4.47M
  // Copy the actual unexpanded tokens to immediately after the result ptr.
64
4.47M
  if (!UnexpArgTokens.empty()) {
65
4.43M
    static_assert(std::is_trivial<Token>::value,
66
4.43M
                  "assume trivial copyability if copying into the "
67
4.43M
                  "uninitialized array (as opposed to reusing a cached "
68
4.43M
                  "MacroArgs)");
69
4.43M
    std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),
70
4.43M
              Result->getTrailingObjects<Token>());
71
4.43M
  }
72
4.47M
73
4.47M
  return Result;
74
4.47M
}
75
76
/// destroy - Destroy and deallocate the memory for this object.
77
///
78
4.45M
void MacroArgs::destroy(Preprocessor &PP) {
79
4.45M
  StringifiedArgs.clear();
80
4.45M
81
4.45M
  // Don't clear PreExpArgTokens, just clear the entries.  Clearing the entries
82
4.45M
  // would deallocate the element vectors.
83
13.8M
  for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; 
++i9.35M
)
84
9.35M
    PreExpArgTokens[i].clear();
85
4.45M
86
4.45M
  // Add this to the preprocessor's free list.
87
4.45M
  ArgCache = PP.MacroArgCache;
88
4.45M
  PP.MacroArgCache = this;
89
4.45M
}
90
91
/// deallocate - This should only be called by the Preprocessor when managing
92
/// its freelist.
93
7.24k
MacroArgs *MacroArgs::deallocate() {
94
7.24k
  MacroArgs *Next = ArgCache;
95
7.24k
96
7.24k
  // Run the dtor to deallocate the vectors.
97
7.24k
  this->~MacroArgs();
98
7.24k
  // Release the memory for the object.
99
7.24k
  static_assert(std::is_trivially_destructible<Token>::value,
100
7.24k
                "assume trivially destructible and forego destructors");
101
7.24k
  free(this);
102
7.24k
103
7.24k
  return Next;
104
7.24k
}
105
106
107
/// getArgLength - Given a pointer to an expanded or unexpanded argument,
108
/// return the number of tokens, not counting the EOF, that make up the
109
/// argument.
110
7.36M
unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
111
7.36M
  unsigned NumArgTokens = 0;
112
26.9M
  for (; ArgPtr->isNot(tok::eof); 
++ArgPtr19.5M
)
113
19.5M
    ++NumArgTokens;
114
7.36M
  return NumArgTokens;
115
7.36M
}
116
117
118
/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
119
///
120
8.43M
const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
121
8.43M
122
8.43M
  assert(Arg < getNumMacroArguments() && "Invalid arg #");
123
8.43M
  // The unexpanded argument tokens start immediately after the MacroArgs object
124
8.43M
  // in memory.
125
8.43M
  const Token *Start = getTrailingObjects<Token>();
126
8.43M
  const Token *Result = Start;
127
8.43M
128
8.43M
  // Scan to find Arg.
129
26.0M
  for (; Arg; 
++Result17.5M
) {
130
17.5M
    assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
131
17.5M
    if (Result->is(tok::eof))
132
5.89M
      --Arg;
133
17.5M
  }
134
8.43M
  assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
135
8.43M
  return Result;
136
8.43M
}
137
138
bool MacroArgs::invokedWithVariadicArgument(const MacroInfo *const MI,
139
35
                                            Preprocessor &PP) {
140
35
  if (!MI->isVariadic())
141
0
    return false;
142
35
  const int VariadicArgIndex = getNumMacroArguments() - 1;
143
35
  return getPreExpArgument(VariadicArgIndex, PP).front().isNot(tok::eof);
144
35
}
145
146
/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
147
/// by pre-expansion, return false.  Otherwise, conservatively return true.
148
bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
149
5.88M
                                     Preprocessor &PP) const {
150
5.88M
  // If there are no identifiers in the argument list, or if the identifiers are
151
5.88M
  // known to not be macros, pre-expansion won't modify it.
152
18.7M
  for (; ArgTok->isNot(tok::eof); 
++ArgTok12.8M
)
153
13.5M
    if (IdentifierInfo *II = ArgTok->getIdentifierInfo())
154
5.53M
      if (II->hasMacroDefinition())
155
718k
        // Return true even though the macro could be a function-like macro
156
718k
        // without a following '(' token, or could be disabled, or not visible.
157
718k
        return true;
158
5.88M
  
return false5.16M
;
159
5.88M
}
160
161
/// getPreExpArgument - Return the pre-expanded form of the specified
162
/// argument.
163
const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg,
164
718k
                                                       Preprocessor &PP) {
165
718k
  assert(Arg < getNumMacroArguments() && "Invalid argument number!");
166
718k
167
718k
  // If we have already computed this, return it.
168
718k
  if (PreExpArgTokens.size() < getNumMacroArguments())
169
56.5k
    PreExpArgTokens.resize(getNumMacroArguments());
170
718k
171
718k
  std::vector<Token> &Result = PreExpArgTokens[Arg];
172
718k
  if (!Result.empty()) 
return Result38.6k
;
173
680k
174
680k
  SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
175
680k
176
680k
  const Token *AT = getUnexpArgument(Arg);
177
680k
  unsigned NumToks = getArgLength(AT)+1;  // Include the EOF.
178
680k
179
680k
  // Otherwise, we have to pre-expand this argument, populating Result.  To do
180
680k
  // this, we set up a fake TokenLexer to lex from the unexpanded argument
181
680k
  // list.  With this installed, we lex expanded tokens until we hit the EOF
182
680k
  // token at the end of the unexp list.
183
680k
  PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
184
680k
                      false /*owns tokens*/, false /*is reinject*/);
185
680k
186
680k
  // Lex all of the macro-expanded tokens into Result.
187
3.00M
  do {
188
3.00M
    Result.push_back(Token());
189
3.00M
    Token &Tok = Result.back();
190
3.00M
    PP.Lex(Tok);
191
3.00M
  } while (Result.back().isNot(tok::eof));
192
680k
193
680k
  // Pop the token stream off the top of the stack.  We know that the internal
194
680k
  // pointer inside of it is to the "end" of the token stream, but the stack
195
680k
  // will not otherwise be popped until the next token is lexed.  The problem is
196
680k
  // that the token may be lexed sometime after the vector of tokens itself is
197
680k
  // destroyed, which would be badness.
198
680k
  if (PP.InCachingLexMode())
199
0
    PP.ExitCachingLexMode();
200
680k
  PP.RemoveTopOfLexerStack();
201
680k
  return Result;
202
680k
}
203
204
205
/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
206
/// tokens into the literal string token that should be produced by the C #
207
/// preprocessor operator.  If Charify is true, then it should be turned into
208
/// a character literal for the Microsoft charize (#@) extension.
209
///
210
Token MacroArgs::StringifyArgument(const Token *ArgToks,
211
                                   Preprocessor &PP, bool Charify,
212
                                   SourceLocation ExpansionLocStart,
213
448k
                                   SourceLocation ExpansionLocEnd) {
214
448k
  Token Tok;
215
448k
  Tok.startToken();
216
448k
  Tok.setKind(Charify ? 
tok::char_constant1
:
tok::string_literal448k
);
217
448k
218
448k
  const Token *ArgTokStart = ArgToks;
219
448k
220
448k
  // Stringify all the tokens.
221
448k
  SmallString<128> Result;
222
448k
  Result += "\"";
223
448k
224
448k
  bool isFirst = true;
225
1.59M
  for (; ArgToks->isNot(tok::eof); 
++ArgToks1.14M
) {
226
1.14M
    const Token &Tok = *ArgToks;
227
1.14M
    if (!isFirst && 
(694k
Tok.hasLeadingSpace()694k
||
Tok.isAtStartOfLine()630k
))
228
64.6k
      Result += ' ';
229
1.14M
    isFirst = false;
230
1.14M
231
1.14M
    // If this is a string or character constant, escape the token as specified
232
1.14M
    // by 6.10.3.2p2.
233
1.14M
    if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
234
1.14M
        
Tok.is(tok::char_constant)1.14M
|| // 'x'
235
1.14M
        
Tok.is(tok::wide_char_constant)1.14M
|| // L'x'.
236
1.14M
        
Tok.is(tok::utf8_char_constant)1.14M
|| // u8'x'.
237
1.14M
        
Tok.is(tok::utf16_char_constant)1.14M
|| // u'x'.
238
1.14M
        
Tok.is(tok::utf32_char_constant)1.14M
) { // U'x'.
239
3.57k
      bool Invalid = false;
240
3.57k
      std::string TokStr = PP.getSpelling(Tok, &Invalid);
241
3.57k
      if (!Invalid) {
242
3.57k
        std::string Str = Lexer::Stringify(TokStr);
243
3.57k
        Result.append(Str.begin(), Str.end());
244
3.57k
      }
245
1.14M
    } else if (Tok.is(tok::code_completion)) {
246
2
      PP.CodeCompleteNaturalLanguage();
247
1.13M
    } else {
248
1.13M
      // Otherwise, just append the token.  Do some gymnastics to get the token
249
1.13M
      // in place and avoid copies where possible.
250
1.13M
      unsigned CurStrLen = Result.size();
251
1.13M
      Result.resize(CurStrLen+Tok.getLength());
252
1.13M
      const char *BufPtr = Result.data() + CurStrLen;
253
1.13M
      bool Invalid = false;
254
1.13M
      unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
255
1.13M
256
1.13M
      if (!Invalid) {
257
1.13M
        // If getSpelling returned a pointer to an already uniqued version of
258
1.13M
        // the string instead of filling in BufPtr, memcpy it onto our string.
259
1.13M
        if (ActualTokLen && 
BufPtr != &Result[CurStrLen]1.13M
)
260
1.13M
          memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
261
1.13M
262
1.13M
        // If the token was dirty, the spelling may be shorter than the token.
263
1.13M
        if (ActualTokLen != Tok.getLength())
264
0
          Result.resize(CurStrLen+ActualTokLen);
265
1.13M
      }
266
1.13M
    }
267
1.14M
  }
268
448k
269
448k
  // If the last character of the string is a \, and if it isn't escaped, this
270
448k
  // is an invalid string literal, diagnose it as specified in C99.
271
448k
  if (Result.back() == '\\') {
272
0
    // Count the number of consecutive \ characters.  If even, then they are
273
0
    // just escaped backslashes, otherwise it's an error.
274
0
    unsigned FirstNonSlash = Result.size()-2;
275
0
    // Guaranteed to find the starting " if nothing else.
276
0
    while (Result[FirstNonSlash] == '\\')
277
0
      --FirstNonSlash;
278
0
    if ((Result.size()-1-FirstNonSlash) & 1) {
279
0
      // Diagnose errors for things like: #define F(X) #X   /   F(\)
280
0
      PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
281
0
      Result.pop_back();  // remove one of the \'s.
282
0
    }
283
0
  }
284
448k
  Result += '"';
285
448k
286
448k
  // If this is the charify operation and the result is not a legal character
287
448k
  // constant, diagnose it.
288
448k
  if (Charify) {
289
1
    // First step, turn double quotes into single quotes:
290
1
    Result[0] = '\'';
291
1
    Result[Result.size()-1] = '\'';
292
1
293
1
    // Check for bogus character.
294
1
    bool isBad = false;
295
1
    if (Result.size() == 3)
296
1
      isBad = Result[1] == '\'';   // ''' is not legal. '\' already fixed above.
297
0
    else
298
0
      isBad = (Result.size() != 4 || Result[1] != '\\');  // Not '\x'
299
1
300
1
    if (isBad) {
301
0
      PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
302
0
      Result = "' '";  // Use something arbitrary, but legal.
303
0
    }
304
1
  }
305
448k
306
448k
  PP.CreateString(Result, Tok,
307
448k
                  ExpansionLocStart, ExpansionLocEnd);
308
448k
  return Tok;
309
448k
}
310
311
/// getStringifiedArgument - Compute, cache, and return the specified argument
312
/// that has been 'stringified' as required by the # operator.
313
const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
314
                                               Preprocessor &PP,
315
                                               SourceLocation ExpansionLocStart,
316
448k
                                               SourceLocation ExpansionLocEnd) {
317
448k
  assert(ArgNo < getNumMacroArguments() && "Invalid argument number!");
318
448k
  if (StringifiedArgs.empty())
319
225k
    StringifiedArgs.resize(getNumMacroArguments(), {});
320
448k
321
448k
  if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
322
448k
    StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
323
448k
                                               /*Charify=*/false,
324
448k
                                               ExpansionLocStart,
325
448k
                                               ExpansionLocEnd);
326
448k
  return StringifiedArgs[ArgNo];
327
448k
}