Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
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 code simply runs the preprocessor on the input file and prints out the
10
// result.  This is the traditional behavior of the -E option.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Frontend/Utils.h"
15
#include "clang/Basic/CharInfo.h"
16
#include "clang/Basic/Diagnostic.h"
17
#include "clang/Basic/SourceManager.h"
18
#include "clang/Frontend/PreprocessorOutputOptions.h"
19
#include "clang/Lex/MacroInfo.h"
20
#include "clang/Lex/PPCallbacks.h"
21
#include "clang/Lex/Pragma.h"
22
#include "clang/Lex/Preprocessor.h"
23
#include "clang/Lex/TokenConcatenation.h"
24
#include "llvm/ADT/STLExtras.h"
25
#include "llvm/ADT/SmallString.h"
26
#include "llvm/ADT/StringRef.h"
27
#include "llvm/Support/ErrorHandling.h"
28
#include "llvm/Support/raw_ostream.h"
29
#include <cstdio>
30
using namespace clang;
31
32
/// PrintMacroDefinition - Print a macro definition in a form that will be
33
/// properly accepted back as a definition.
34
static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
35
427k
                                 Preprocessor &PP, raw_ostream &OS) {
36
427k
  OS << "#define " << II.getName();
37
427k
38
427k
  if (MI.isFunctionLike()) {
39
34
    OS << '(';
40
34
    if (!MI.param_empty()) {
41
33
      MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_end();
42
36
      for (; AI+1 != E; 
++AI3
) {
43
3
        OS << (*AI)->getName();
44
3
        OS << ',';
45
3
      }
46
33
47
33
      // Last argument.
48
33
      if ((*AI)->getName() == "__VA_ARGS__")
49
2
        OS << "...";
50
31
      else
51
31
        OS << (*AI)->getName();
52
33
    }
53
34
54
34
    if (MI.isGNUVarargs())
55
1
      OS << "...";  // #define foo(x...)
56
34
57
34
    OS << ')';
58
34
  }
59
427k
60
427k
  // GCC always emits a space, even if the macro body is empty.  However, do not
61
427k
  // want to emit two spaces if the first token has a leading space.
62
427k
  if (MI.tokens_empty() || 
!MI.tokens_begin()->hasLeadingSpace()418k
)
63
427k
    OS << ' ';
64
427k
65
427k
  SmallString<128> SpellingBuffer;
66
499k
  for (const auto &T : MI.tokens()) {
67
499k
    if (T.hasLeadingSpace())
68
45.4k
      OS << ' ';
69
499k
70
499k
    OS << PP.getSpelling(T, SpellingBuffer);
71
499k
  }
72
427k
}
73
74
//===----------------------------------------------------------------------===//
75
// Preprocessed token printer
76
//===----------------------------------------------------------------------===//
77
78
namespace {
79
class PrintPPOutputPPCallbacks : public PPCallbacks {
80
  Preprocessor &PP;
81
  SourceManager &SM;
82
  TokenConcatenation ConcatInfo;
83
public:
84
  raw_ostream &OS;
85
private:
86
  unsigned CurLine;
87
88
  bool EmittedTokensOnThisLine;
89
  bool EmittedDirectiveOnThisLine;
90
  SrcMgr::CharacteristicKind FileType;
91
  SmallString<512> CurFilename;
92
  bool Initialized;
93
  bool DisableLineMarkers;
94
  bool DumpDefines;
95
  bool DumpIncludeDirectives;
96
  bool UseLineDirectives;
97
  bool IsFirstFileEntered;
98
public:
99
  PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
100
                           bool defines, bool DumpIncludeDirectives,
101
                           bool UseLineDirectives)
102
      : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
103
        DisableLineMarkers(lineMarkers), DumpDefines(defines),
104
        DumpIncludeDirectives(DumpIncludeDirectives),
105
1.17k
        UseLineDirectives(UseLineDirectives) {
106
1.17k
    CurLine = 0;
107
1.17k
    CurFilename += "<uninit>";
108
1.17k
    EmittedTokensOnThisLine = false;
109
1.17k
    EmittedDirectiveOnThisLine = false;
110
1.17k
    FileType = SrcMgr::C_User;
111
1.17k
    Initialized = false;
112
1.17k
    IsFirstFileEntered = false;
113
1.17k
  }
114
115
718k
  void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
116
350k
  bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
117
118
1.28k
  void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
119
719k
  bool hasEmittedDirectiveOnThisLine() const {
120
719k
    return EmittedDirectiveOnThisLine;
121
719k
  }
122
123
  bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
124
125
  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
126
                   SrcMgr::CharacteristicKind FileType,
127
                   FileID PrevFID) override;
128
  void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
129
                          StringRef FileName, bool IsAngled,
130
                          CharSourceRange FilenameRange, const FileEntry *File,
131
                          StringRef SearchPath, StringRef RelativePath,
132
                          const Module *Imported,
133
                          SrcMgr::CharacteristicKind FileType) override;
134
  void Ident(SourceLocation Loc, StringRef str) override;
135
  void PragmaMessage(SourceLocation Loc, StringRef Namespace,
136
                     PragmaMessageKind Kind, StringRef Str) override;
137
  void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
138
  void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
139
  void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
140
  void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
141
                        diag::Severity Map, StringRef Str) override;
142
  void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
143
                     ArrayRef<int> Ids) override;
144
  void PragmaWarningPush(SourceLocation Loc, int Level) override;
145
  void PragmaWarningPop(SourceLocation Loc) override;
146
  void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;
147
  void PragmaExecCharsetPop(SourceLocation Loc) override;
148
  void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
149
  void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
150
151
  bool HandleFirstTokOnLine(Token &Tok);
152
153
  /// Move to the line of the provided source location. This will
154
  /// return true if the output stream required adjustment or if
155
  /// the requested location is on the first line.
156
17.5k
  bool MoveToLine(SourceLocation Loc) {
157
17.5k
    PresumedLoc PLoc = SM.getPresumedLoc(Loc);
158
17.5k
    if (PLoc.isInvalid())
159
1
      return false;
160
17.5k
    return MoveToLine(PLoc.getLine()) || 
(PLoc.getLine() == 1)475
;
161
17.5k
  }
162
  bool MoveToLine(unsigned LineNo);
163
164
  bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
165
349k
                   const Token &Tok) {
166
349k
    return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
167
349k
  }
168
  void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
169
                     unsigned ExtraLen=0);
170
0
  bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
171
  void HandleNewlinesInToken(const char *TokStr, unsigned Len);
172
173
  /// MacroDefined - This hook is called whenever a macro definition is seen.
174
  void MacroDefined(const Token &MacroNameTok,
175
                    const MacroDirective *MD) override;
176
177
  /// MacroUndefined - This hook is called whenever a macro #undef is seen.
178
  void MacroUndefined(const Token &MacroNameTok,
179
                      const MacroDefinition &MD,
180
                      const MacroDirective *Undef) override;
181
182
  void BeginModule(const Module *M);
183
  void EndModule(const Module *M);
184
};
185
}  // end anonymous namespace
186
187
void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
188
                                             const char *Extra,
189
9.66k
                                             unsigned ExtraLen) {
190
9.66k
  startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
191
9.66k
192
9.66k
  // Emit #line directives or GNU line markers depending on what mode we're in.
193
9.66k
  if (UseLineDirectives) {
194
21
    OS << "#line" << ' ' << LineNo << ' ' << '"';
195
21
    OS.write_escaped(CurFilename);
196
21
    OS << '"';
197
9.63k
  } else {
198
9.63k
    OS << '#' << ' ' << LineNo << ' ' << '"';
199
9.63k
    OS.write_escaped(CurFilename);
200
9.63k
    OS << '"';
201
9.63k
202
9.63k
    if (ExtraLen)
203
5.81k
      OS.write(Extra, ExtraLen);
204
9.63k
205
9.63k
    if (FileType == SrcMgr::C_System)
206
1.04k
      OS.write(" 3", 2);
207
8.59k
    else if (FileType == SrcMgr::C_ExternCSystem)
208
6
      OS.write(" 3 4", 4);
209
9.63k
  }
210
9.66k
  OS << '\n';
211
9.66k
}
212
213
/// MoveToLine - Move the output to the source line specified by the location
214
/// object.  We can do this by emitting some number of \n's, or be emitting a
215
/// #line directive.  This returns false if already at the specified line, true
216
/// if some newlines were emitted.
217
17.5k
bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
218
17.5k
  // If this line is "close enough" to the original line, just print newlines,
219
17.5k
  // otherwise print a #line directive.
220
17.5k
  if (LineNo-CurLine <= 8) {
221
15.3k
    if (LineNo-CurLine == 1)
222
10.5k
      OS << '\n';
223
4.81k
    else if (LineNo == CurLine)
224
475
      return false;    // Spelling line moved, but expansion line didn't.
225
4.33k
    else {
226
4.33k
      const char *NewLines = "\n\n\n\n\n\n\n\n";
227
4.33k
      OS.write(NewLines, LineNo-CurLine);
228
4.33k
    }
229
15.3k
  } else 
if (2.19k
!DisableLineMarkers2.19k
) {
230
2.17k
    // Emit a #line or line marker.
231
2.17k
    WriteLineInfo(LineNo, nullptr, 0);
232
2.17k
  } else {
233
20
    // Okay, we're in -P mode, which turns off line markers.  However, we still
234
20
    // need to emit a newline between tokens on different lines.
235
20
    startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
236
20
  }
237
17.5k
238
17.5k
  CurLine = LineNo;
239
17.0k
  return true;
240
17.5k
}
241
242
bool
243
10.1k
PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
244
10.1k
  if (EmittedTokensOnThisLine || 
EmittedDirectiveOnThisLine9.31k
) {
245
1.11k
    OS << '\n';
246
1.11k
    EmittedTokensOnThisLine = false;
247
1.11k
    EmittedDirectiveOnThisLine = false;
248
1.11k
    if (ShouldUpdateCurrentLine)
249
289
      ++CurLine;
250
1.11k
    return true;
251
1.11k
  }
252
9.06k
253
9.06k
  return false;
254
9.06k
}
255
256
/// FileChanged - Whenever the preprocessor enters or exits a #include file
257
/// it invokes this handler.  Update our conception of the current source
258
/// position.
259
void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
260
                                           FileChangeReason Reason,
261
                                       SrcMgr::CharacteristicKind NewFileType,
262
7.56k
                                       FileID PrevFID) {
263
7.56k
  // Unless we are exiting a #include, make sure to skip ahead to the line the
264
7.56k
  // #include directive was at.
265
7.56k
  SourceManager &SourceMgr = SM;
266
7.56k
267
7.56k
  PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
268
7.56k
  if (UserLoc.isInvalid())
269
0
    return;
270
7.56k
271
7.56k
  unsigned NewLine = UserLoc.getLine();
272
7.56k
273
7.56k
  if (Reason == PPCallbacks::EnterFile) {
274
4.11k
    SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
275
4.11k
    if (IncludeLoc.isValid())
276
1.75k
      MoveToLine(IncludeLoc);
277
4.11k
  } else 
if (3.45k
Reason == PPCallbacks::SystemHeaderPragma3.45k
) {
278
3
    // GCC emits the # directive for this directive on the line AFTER the
279
3
    // directive and emits a bunch of spaces that aren't needed. This is because
280
3
    // otherwise we will emit a line marker for THIS line, which requires an
281
3
    // extra blank line after the directive to avoid making all following lines
282
3
    // off by one. We can do better by simply incrementing NewLine here.
283
3
    NewLine += 1;
284
3
  }
285
7.56k
286
7.56k
  CurLine = NewLine;
287
7.56k
288
7.56k
  CurFilename.clear();
289
7.56k
  CurFilename += UserLoc.getFilename();
290
7.56k
  FileType = NewFileType;
291
7.56k
292
7.56k
  if (DisableLineMarkers) {
293
85
    startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
294
85
    return;
295
85
  }
296
7.48k
297
7.48k
  if (!Initialized) {
298
1.16k
    WriteLineInfo(CurLine);
299
1.16k
    Initialized = true;
300
1.16k
  }
301
7.48k
302
7.48k
  // Do not emit an enter marker for the main file (which we expect is the first
303
7.48k
  // entered file). This matches gcc, and improves compatibility with some tools
304
7.48k
  // which track the # line markers as a way to determine when the preprocessed
305
7.48k
  // output is in the context of the main file.
306
7.48k
  if (Reason == PPCallbacks::EnterFile && 
!IsFirstFileEntered4.07k
) {
307
1.16k
    IsFirstFileEntered = true;
308
1.16k
    return;
309
1.16k
  }
310
6.31k
311
6.31k
  switch (Reason) {
312
6.31k
  case PPCallbacks::EnterFile:
313
2.90k
    WriteLineInfo(CurLine, " 1", 2);
314
2.90k
    break;
315
6.31k
  case PPCallbacks::ExitFile:
316
2.90k
    WriteLineInfo(CurLine, " 2", 2);
317
2.90k
    break;
318
6.31k
  case PPCallbacks::SystemHeaderPragma:
319
499
  case PPCallbacks::RenameFile:
320
499
    WriteLineInfo(CurLine);
321
499
    break;
322
6.31k
  }
323
6.31k
}
324
325
void PrintPPOutputPPCallbacks::InclusionDirective(
326
    SourceLocation HashLoc,
327
    const Token &IncludeTok,
328
    StringRef FileName,
329
    bool IsAngled,
330
    CharSourceRange FilenameRange,
331
    const FileEntry *File,
332
    StringRef SearchPath,
333
    StringRef RelativePath,
334
    const Module *Imported,
335
1.45k
    SrcMgr::CharacteristicKind FileType) {
336
1.45k
  // In -dI mode, dump #include directives prior to dumping their content or
337
1.45k
  // interpretation.
338
1.45k
  if (DumpIncludeDirectives) {
339
5
    startNewLineIfNeeded();
340
5
    MoveToLine(HashLoc);
341
5
    const std::string TokenText = PP.getSpelling(IncludeTok);
342
5
    assert(!TokenText.empty());
343
5
    OS << "#" << TokenText << " "
344
5
       << (IsAngled ? 
'<'1
:
'"'4
) << FileName << (IsAngled ?
'>'1
:
'"'4
)
345
5
       << " /* clang -E -dI */";
346
5
    setEmittedDirectiveOnThisLine();
347
5
    startNewLineIfNeeded();
348
5
  }
349
1.45k
350
1.45k
  // When preprocessing, turn implicit imports into module import pragmas.
351
1.45k
  if (Imported) {
352
39
    switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
353
39
    case tok::pp_include:
354
39
    case tok::pp_import:
355
39
    case tok::pp_include_next:
356
39
      startNewLineIfNeeded();
357
39
      MoveToLine(HashLoc);
358
39
      OS << "#pragma clang module import " << Imported->getFullModuleName(true)
359
39
         << " /* clang -E: implicit import for "
360
39
         << "#" << PP.getSpelling(IncludeTok) << " "
361
39
         << (IsAngled ? 
'<'8
:
'"'31
) << FileName << (IsAngled ?
'>'8
:
'"'31
)
362
39
         << " */";
363
39
      // Since we want a newline after the pragma, but not a #<line>, start a
364
39
      // new line immediately.
365
39
      EmittedTokensOnThisLine = true;
366
39
      startNewLineIfNeeded();
367
39
      break;
368
39
369
39
    case tok::pp___include_macros:
370
0
      // #__include_macros has no effect on a user of a preprocessed source
371
0
      // file; the only effect is on preprocessing.
372
0
      //
373
0
      // FIXME: That's not *quite* true: it causes the module in question to
374
0
      // be loaded, which can affect downstream diagnostics.
375
0
      break;
376
39
377
39
    default:
378
0
      llvm_unreachable("unknown include directive kind");
379
39
      
break0
;
380
39
    }
381
39
  }
382
1.45k
}
383
384
/// Handle entering the scope of a module during a module compilation.
385
37
void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
386
37
  startNewLineIfNeeded();
387
37
  OS << "#pragma clang module begin " << M->getFullModuleName(true);
388
37
  setEmittedDirectiveOnThisLine();
389
37
}
390
391
/// Handle leaving the scope of a module during a module compilation.
392
37
void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
393
37
  startNewLineIfNeeded();
394
37
  OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
395
37
  setEmittedDirectiveOnThisLine();
396
37
}
397
398
/// Ident - Handle #ident directives when read by the preprocessor.
399
///
400
0
void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
401
0
  MoveToLine(Loc);
402
0
403
0
  OS.write("#ident ", strlen("#ident "));
404
0
  OS.write(S.begin(), S.size());
405
0
  EmittedTokensOnThisLine = true;
406
0
}
407
408
/// MacroDefined - This hook is called whenever a macro definition is seen.
409
void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
410
758k
                                            const MacroDirective *MD) {
411
758k
  const MacroInfo *MI = MD->getMacroInfo();
412
758k
  // Only print out macro definitions in -dD mode.
413
758k
  if (!DumpDefines ||
414
758k
      // Ignore __FILE__ etc.
415
758k
      
MI->isBuiltinMacro()1.03k
)
return757k
;
416
1.03k
417
1.03k
  MoveToLine(MI->getDefinitionLoc());
418
1.03k
  PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
419
1.03k
  setEmittedDirectiveOnThisLine();
420
1.03k
}
421
422
void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
423
                                              const MacroDefinition &MD,
424
92
                                              const MacroDirective *Undef) {
425
92
  // Only print out macro definitions in -dD mode.
426
92
  if (!DumpDefines) 
return91
;
427
1
428
1
  MoveToLine(MacroNameTok.getLocation());
429
1
  OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
430
1
  setEmittedDirectiveOnThisLine();
431
1
}
432
433
7
static void outputPrintable(raw_ostream &OS, StringRef Str) {
434
43
  for (unsigned char Char : Str) {
435
43
    if (isPrintable(Char) && 
Char != '\\'41
&&
Char != '"'39
)
436
33
      OS << (char)Char;
437
10
    else // Output anything hard as an octal escape.
438
10
      OS << '\\'
439
10
         << (char)('0' + ((Char >> 6) & 7))
440
10
         << (char)('0' + ((Char >> 3) & 7))
441
10
         << (char)('0' + ((Char >> 0) & 7));
442
43
  }
443
7
}
444
445
void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
446
                                             StringRef Namespace,
447
                                             PragmaMessageKind Kind,
448
7
                                             StringRef Str) {
449
7
  startNewLineIfNeeded();
450
7
  MoveToLine(Loc);
451
7
  OS << "#pragma ";
452
7
  if (!Namespace.empty())
453
4
    OS << Namespace << ' ';
454
7
  switch (Kind) {
455
7
    case PMK_Message:
456
3
      OS << "message(\"";
457
3
      break;
458
7
    case PMK_Warning:
459
2
      OS << "warning \"";
460
2
      break;
461
7
    case PMK_Error:
462
2
      OS << "error \"";
463
2
      break;
464
7
  }
465
7
466
7
  outputPrintable(OS, Str);
467
7
  OS << '"';
468
7
  if (Kind == PMK_Message)
469
3
    OS << ')';
470
7
  setEmittedDirectiveOnThisLine();
471
7
}
472
473
void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
474
5
                                           StringRef DebugType) {
475
5
  startNewLineIfNeeded();
476
5
  MoveToLine(Loc);
477
5
478
5
  OS << "#pragma clang __debug ";
479
5
  OS << DebugType;
480
5
481
5
  setEmittedDirectiveOnThisLine();
482
5
}
483
484
void PrintPPOutputPPCallbacks::
485
9
PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
486
9
  startNewLineIfNeeded();
487
9
  MoveToLine(Loc);
488
9
  OS << "#pragma " << Namespace << " diagnostic push";
489
9
  setEmittedDirectiveOnThisLine();
490
9
}
491
492
void PrintPPOutputPPCallbacks::
493
9
PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
494
9
  startNewLineIfNeeded();
495
9
  MoveToLine(Loc);
496
9
  OS << "#pragma " << Namespace << " diagnostic pop";
497
9
  setEmittedDirectiveOnThisLine();
498
9
}
499
500
void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
501
                                                StringRef Namespace,
502
                                                diag::Severity Map,
503
17
                                                StringRef Str) {
504
17
  startNewLineIfNeeded();
505
17
  MoveToLine(Loc);
506
17
  OS << "#pragma " << Namespace << " diagnostic ";
507
17
  switch (Map) {
508
17
  case diag::Severity::Remark:
509
0
    OS << "remark";
510
0
    break;
511
17
  case diag::Severity::Warning:
512
2
    OS << "warning";
513
2
    break;
514
17
  case diag::Severity::Error:
515
3
    OS << "error";
516
3
    break;
517
17
  case diag::Severity::Ignored:
518
10
    OS << "ignored";
519
10
    break;
520
17
  case diag::Severity::Fatal:
521
2
    OS << "fatal";
522
2
    break;
523
17
  }
524
17
  OS << " \"" << Str << '"';
525
17
  setEmittedDirectiveOnThisLine();
526
17
}
527
528
void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
529
                                             StringRef WarningSpec,
530
14
                                             ArrayRef<int> Ids) {
531
14
  startNewLineIfNeeded();
532
14
  MoveToLine(Loc);
533
14
  OS << "#pragma warning(" << WarningSpec << ':';
534
37
  for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; 
++I23
)
535
23
    OS << ' ' << *I;
536
14
  OS << ')';
537
14
  setEmittedDirectiveOnThisLine();
538
14
}
539
540
void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
541
16
                                                 int Level) {
542
16
  startNewLineIfNeeded();
543
16
  MoveToLine(Loc);
544
16
  OS << "#pragma warning(push";
545
16
  if (Level >= 0)
546
9
    OS << ", " << Level;
547
16
  OS << ')';
548
16
  setEmittedDirectiveOnThisLine();
549
16
}
550
551
5
void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
552
5
  startNewLineIfNeeded();
553
5
  MoveToLine(Loc);
554
5
  OS << "#pragma warning(pop)";
555
5
  setEmittedDirectiveOnThisLine();
556
5
}
557
558
void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
559
4
                                                     StringRef Str) {
560
4
  startNewLineIfNeeded();
561
4
  MoveToLine(Loc);
562
4
  OS << "#pragma character_execution_set(push";
563
4
  if (!Str.empty())
564
4
    OS << ", " << Str;
565
4
  OS << ')';
566
4
  setEmittedDirectiveOnThisLine();
567
4
}
568
569
3
void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
570
3
  startNewLineIfNeeded();
571
3
  MoveToLine(Loc);
572
3
  OS << "#pragma character_execution_set(pop)";
573
3
  setEmittedDirectiveOnThisLine();
574
3
}
575
576
void PrintPPOutputPPCallbacks::
577
1
PragmaAssumeNonNullBegin(SourceLocation Loc) {
578
1
  startNewLineIfNeeded();
579
1
  MoveToLine(Loc);
580
1
  OS << "#pragma clang assume_nonnull begin";
581
1
  setEmittedDirectiveOnThisLine();
582
1
}
583
584
void PrintPPOutputPPCallbacks::
585
1
PragmaAssumeNonNullEnd(SourceLocation Loc) {
586
1
  startNewLineIfNeeded();
587
1
  MoveToLine(Loc);
588
1
  OS << "#pragma clang assume_nonnull end";
589
1
  setEmittedDirectiveOnThisLine();
590
1
}
591
592
/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
593
/// is called for the first token on each new line.  If this really is the start
594
/// of a new logical line, handle it and return true, otherwise return false.
595
/// This may not be the start of a logical line because the "start of line"
596
/// marker is set for spelling lines, not expansion ones.
597
14.4k
bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
598
14.4k
  // Figure out what line we went to and insert the appropriate number of
599
14.4k
  // newline characters.
600
14.4k
  if (!MoveToLine(Tok.getLocation()))
601
157
    return false;
602
14.2k
603
14.2k
  // Print out space characters so that the first token on a line is
604
14.2k
  // indented for easy reading.
605
14.2k
  unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
606
14.2k
607
14.2k
  // The first token on a line can have a column number of 1, yet still expect
608
14.2k
  // leading white space, if a macro expansion in column 1 starts with an empty
609
14.2k
  // macro argument, or an empty nested macro expansion. In this case, move the
610
14.2k
  // token to column 2.
611
14.2k
  if (ColNo == 1 && 
Tok.hasLeadingSpace()5.16k
)
612
58
    ColNo = 2;
613
14.2k
614
14.2k
  // This hack prevents stuff like:
615
14.2k
  // #define HASH #
616
14.2k
  // HASH define foo bar
617
14.2k
  // From having the # character end up at column 1, which makes it so it
618
14.2k
  // is not handled as a #define next time through the preprocessor if in
619
14.2k
  // -fpreprocessed mode.
620
14.2k
  if (ColNo <= 1 && 
Tok.is(tok::hash)5.10k
)
621
35
    OS << ' ';
622
14.2k
623
14.2k
  // Otherwise, indent the appropriate number of spaces.
624
30.9k
  for (; ColNo > 1; 
--ColNo16.6k
)
625
16.6k
    OS << ' ';
626
14.2k
627
14.2k
  return true;
628
14.2k
}
629
630
void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
631
1.11k
                                                     unsigned Len) {
632
1.11k
  unsigned NumNewlines = 0;
633
7.35k
  for (; Len; 
--Len, ++TokStr6.24k
) {
634
6.24k
    if (*TokStr != '\n' &&
635
6.24k
        
*TokStr != '\r'6.02k
)
636
6.02k
      continue;
637
214
638
214
    ++NumNewlines;
639
214
640
214
    // If we have \n\r or \r\n, skip both and count as one line.
641
214
    if (Len != 1 &&
642
214
        
(104
TokStr[1] == '\n'104
||
TokStr[1] == '\r'50
) &&
643
214
        
TokStr[0] != TokStr[1]54
) {
644
0
      ++TokStr;
645
0
      --Len;
646
0
    }
647
214
  }
648
1.11k
649
1.11k
  if (NumNewlines == 0) 
return975
;
650
141
651
141
  CurLine += NumNewlines;
652
141
}
653
654
655
namespace {
656
struct UnknownPragmaHandler : public PragmaHandler {
657
  const char *Prefix;
658
  PrintPPOutputPPCallbacks *Callbacks;
659
660
  // Set to true if tokens should be expanded
661
  bool ShouldExpandTokens;
662
663
  UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
664
                       bool RequireTokenExpansion)
665
      : Prefix(prefix), Callbacks(callbacks),
666
4.71k
        ShouldExpandTokens(RequireTokenExpansion) {}
667
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
668
79
                    Token &PragmaTok) override {
669
79
    // Figure out what line we went to and insert the appropriate number of
670
79
    // newline characters.
671
79
    Callbacks->startNewLineIfNeeded();
672
79
    Callbacks->MoveToLine(PragmaTok.getLocation());
673
79
    Callbacks->OS.write(Prefix, strlen(Prefix));
674
79
675
79
    if (ShouldExpandTokens) {
676
53
      // The first token does not have expanded macros. Expand them, if
677
53
      // required.
678
53
      auto Toks = llvm::make_unique<Token[]>(1);
679
53
      Toks[0] = PragmaTok;
680
53
      PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
681
53
                          /*DisableMacroExpansion=*/false,
682
53
                          /*IsReinject=*/false);
683
53
      PP.Lex(PragmaTok);
684
53
    }
685
79
    Token PrevToken;
686
79
    Token PrevPrevToken;
687
79
    PrevToken.startToken();
688
79
    PrevPrevToken.startToken();
689
79
690
79
    // Read and print all of the pragma tokens.
691
434
    while (PragmaTok.isNot(tok::eod)) {
692
355
      if (PragmaTok.hasLeadingSpace() ||
693
355
          
Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok)198
)
694
158
        Callbacks->OS << ' ';
695
355
      std::string TokSpell = PP.getSpelling(PragmaTok);
696
355
      Callbacks->OS.write(&TokSpell[0], TokSpell.size());
697
355
698
355
      PrevPrevToken = PrevToken;
699
355
      PrevToken = PragmaTok;
700
355
701
355
      if (ShouldExpandTokens)
702
282
        PP.Lex(PragmaTok);
703
73
      else
704
73
        PP.LexUnexpandedToken(PragmaTok);
705
355
    }
706
79
    Callbacks->setEmittedDirectiveOnThisLine();
707
79
  }
708
};
709
} // end anonymous namespace
710
711
712
static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
713
                                    PrintPPOutputPPCallbacks *Callbacks,
714
1.17k
                                    raw_ostream &OS) {
715
1.17k
  bool DropComments = PP.getLangOpts().TraditionalCPP &&
716
1.17k
                      
!PP.getCommentRetentionState()3
;
717
1.17k
718
1.17k
  char Buffer[256];
719
1.17k
  Token PrevPrevTok, PrevTok;
720
1.17k
  PrevPrevTok.startToken();
721
1.17k
  PrevTok.startToken();
722
719k
  while (1) {
723
719k
    if (Callbacks->hasEmittedDirectiveOnThisLine()) {
724
76
      Callbacks->startNewLineIfNeeded();
725
76
      Callbacks->MoveToLine(Tok.getLocation());
726
76
    }
727
719k
728
719k
    // If this token is at the start of a line, emit newlines if needed.
729
719k
    if (Tok.isAtStartOfLine() && 
Callbacks->HandleFirstTokOnLine(Tok)14.4k
) {
730
14.2k
      // done.
731
704k
    } else if (Tok.hasLeadingSpace() ||
732
704k
               // If we haven't emitted a token on this line yet, PrevTok isn't
733
704k
               // useful to look at and no concatenation could happen anyway.
734
704k
               
(350k
Callbacks->hasEmittedTokensOnThisLine()350k
&&
735
350k
                // Don't print "-" next to "-", it would form "--".
736
355k
                
Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok)349k
)) {
737
355k
      OS << ' ';
738
355k
    }
739
719k
740
719k
    if (DropComments && 
Tok.is(tok::comment)275
) {
741
50
      // Skip comments. Normally the preprocessor does not generate
742
50
      // tok::comment nodes at all when not keeping comments, but under
743
50
      // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
744
50
      SourceLocation StartLoc = Tok.getLocation();
745
50
      Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
746
719k
    } else if (Tok.is(tok::eod)) {
747
89
      // Don't print end of directive tokens, since they are typically newlines
748
89
      // that mess up our line tracking. These come from unknown pre-processor
749
89
      // directives or hash-prefixed comments in standalone assembly files.
750
89
      PP.Lex(Tok);
751
89
      continue;
752
718k
    } else if (Tok.is(tok::annot_module_include)) {
753
47
      // PrintPPOutputPPCallbacks::InclusionDirective handles producing
754
47
      // appropriate output here. Ignore this token entirely.
755
47
      PP.Lex(Tok);
756
47
      continue;
757
718k
    } else if (Tok.is(tok::annot_module_begin)) {
758
37
      // FIXME: We retrieve this token after the FileChanged callback, and
759
37
      // retrieve the module_end token before the FileChanged callback, so
760
37
      // we render this within the file and render the module end outside the
761
37
      // file, but this is backwards from the token locations: the module_begin
762
37
      // token is at the include location (outside the file) and the module_end
763
37
      // token is at the EOF location (within the file).
764
37
      Callbacks->BeginModule(
765
37
          reinterpret_cast<Module *>(Tok.getAnnotationValue()));
766
37
      PP.Lex(Tok);
767
37
      continue;
768
718k
    } else if (Tok.is(tok::annot_module_end)) {
769
37
      Callbacks->EndModule(
770
37
          reinterpret_cast<Module *>(Tok.getAnnotationValue()));
771
37
      PP.Lex(Tok);
772
37
      continue;
773
718k
    } else if (Tok.is(tok::annot_header_unit)) {
774
5
      // This is a header-name that has been (effectively) converted into a
775
5
      // module-name.
776
5
      // FIXME: The module name could contain non-identifier module name
777
5
      // components. We don't have a good way to round-trip those.
778
5
      Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
779
5
      std::string Name = M->getFullModuleName();
780
5
      OS.write(Name.data(), Name.size());
781
5
      Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
782
718k
    } else if (Tok.isAnnotation()) {
783
3
      // Ignore annotation tokens created by pragmas - the pragmas themselves
784
3
      // will be reproduced in the preprocessed output.
785
3
      PP.Lex(Tok);
786
3
      continue;
787
718k
    } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
788
354k
      OS << II->getName();
789
364k
    } else if (Tok.isLiteral() && 
!Tok.needsCleaning()8.10k
&&
790
364k
               
Tok.getLiteralData()8.08k
) {
791
8.07k
      OS.write(Tok.getLiteralData(), Tok.getLength());
792
356k
    } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
793
356k
      const char *TokPtr = Buffer;
794
356k
      unsigned Len = PP.getSpelling(Tok, TokPtr);
795
356k
      OS.write(TokPtr, Len);
796
356k
797
356k
      // Tokens that can contain embedded newlines need to adjust our current
798
356k
      // line number.
799
356k
      if (Tok.getKind() == tok::comment || 
Tok.getKind() == tok::unknown356k
)
800
1.11k
        Callbacks->HandleNewlinesInToken(TokPtr, Len);
801
356k
    } else {
802
0
      std::string S = PP.getSpelling(Tok);
803
0
      OS.write(S.data(), S.size());
804
0
805
0
      // Tokens that can contain embedded newlines need to adjust our current
806
0
      // line number.
807
0
      if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
808
0
        Callbacks->HandleNewlinesInToken(S.data(), S.size());
809
0
    }
810
719k
    Callbacks->setEmittedTokensOnThisLine();
811
718k
812
718k
    if (Tok.is(tok::eof)) 
break1.17k
;
813
717k
814
717k
    PrevPrevTok = PrevTok;
815
717k
    PrevTok = Tok;
816
717k
    PP.Lex(Tok);
817
717k
  }
818
1.17k
}
819
820
typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
821
3.85M
static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
822
3.85M
  return LHS->first->getName().compare(RHS->first->getName());
823
3.85M
}
824
825
1.23k
static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
826
1.23k
  // Ignore unknown pragmas.
827
1.23k
  PP.IgnorePragmas();
828
1.23k
829
1.23k
  // -dM mode just scans and ignores all tokens in the files, then dumps out
830
1.23k
  // the macro table at the end.
831
1.23k
  PP.EnterMainSourceFile();
832
1.23k
833
1.23k
  Token Tok;
834
1.39k
  do PP.Lex(Tok);
835
1.39k
  while (Tok.isNot(tok::eof));
836
1.23k
837
1.23k
  SmallVector<id_macro_pair, 128> MacrosByID;
838
1.23k
  for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
839
458k
       I != E; 
++I456k
) {
840
456k
    auto *MD = I->second.getLatest();
841
456k
    if (MD && MD->isDefined())
842
456k
      MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
843
456k
  }
844
1.23k
  llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
845
1.23k
846
458k
  for (unsigned i = 0, e = MacrosByID.size(); i != e; 
++i456k
) {
847
456k
    MacroInfo &MI = *MacrosByID[i].second;
848
456k
    // Ignore computed macros like __LINE__ and friends.
849
456k
    if (MI.isBuiltinMacro()) 
continue30.9k
;
850
426k
851
426k
    PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
852
426k
    *OS << '\n';
853
426k
  }
854
1.23k
}
855
856
/// DoPrintPreprocessedInput - This implements -E mode.
857
///
858
void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
859
2.41k
                                     const PreprocessorOutputOptions &Opts) {
860
2.41k
  // Show macros with no output is handled specially.
861
2.41k
  if (!Opts.ShowCPP) {
862
1.23k
    assert(Opts.ShowMacros && "Not yet implemented!");
863
1.23k
    DoPrintMacros(PP, OS);
864
1.23k
    return;
865
1.23k
  }
866
1.17k
867
1.17k
  // Inform the preprocessor whether we want it to retain comments or not, due
868
1.17k
  // to -C or -CC.
869
1.17k
  PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
870
1.17k
871
1.17k
  PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
872
1.17k
      PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
873
1.17k
      Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
874
1.17k
875
1.17k
  // Expand macros in pragmas with -fms-extensions.  The assumption is that
876
1.17k
  // the majority of pragmas in such a file will be Microsoft pragmas.
877
1.17k
  // Remember the handlers we will add so that we can remove them later.
878
1.17k
  std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
879
1.17k
      new UnknownPragmaHandler(
880
1.17k
          "#pragma", Callbacks,
881
1.17k
          /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
882
1.17k
883
1.17k
  std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
884
1.17k
      "#pragma GCC", Callbacks,
885
1.17k
      /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
886
1.17k
887
1.17k
  std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
888
1.17k
      "#pragma clang", Callbacks,
889
1.17k
      /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
890
1.17k
891
1.17k
  PP.AddPragmaHandler(MicrosoftExtHandler.get());
892
1.17k
  PP.AddPragmaHandler("GCC", GCCHandler.get());
893
1.17k
  PP.AddPragmaHandler("clang", ClangHandler.get());
894
1.17k
895
1.17k
  // The tokens after pragma omp need to be expanded.
896
1.17k
  //
897
1.17k
  //  OpenMP [2.1, Directive format]
898
1.17k
  //  Preprocessing tokens following the #pragma omp are subject to macro
899
1.17k
  //  replacement.
900
1.17k
  std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
901
1.17k
      new UnknownPragmaHandler("#pragma omp", Callbacks,
902
1.17k
                               /*RequireTokenExpansion=*/true));
903
1.17k
  PP.AddPragmaHandler("omp", OpenMPHandler.get());
904
1.17k
905
1.17k
  PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
906
1.17k
907
1.17k
  // After we have configured the preprocessor, enter the main file.
908
1.17k
  PP.EnterMainSourceFile();
909
1.17k
910
1.17k
  // Consume all of the tokens that come from the predefines buffer.  Those
911
1.17k
  // should not be emitted into the output and are guaranteed to be at the
912
1.17k
  // start.
913
1.17k
  const SourceManager &SourceMgr = PP.getSourceManager();
914
1.17k
  Token Tok;
915
1.17k
  do {
916
1.17k
    PP.Lex(Tok);
917
1.17k
    if (Tok.is(tok::eof) || 
!Tok.getLocation().isFileID()1.09k
)
918
416
      break;
919
763
920
763
    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
921
763
    if (PLoc.isInvalid())
922
0
      break;
923
763
924
763
    if (strcmp(PLoc.getFilename(), "<built-in>"))
925
763
      break;
926
0
  } while (true);
927
1.17k
928
1.17k
  // Read all the preprocessed tokens, printing them out to the stream.
929
1.17k
  PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
930
1.17k
  *OS << '\n';
931
1.17k
932
1.17k
  // Remove the handlers we just added to leave the preprocessor in a sane state
933
1.17k
  // so that it can be reused (for example by a clang::Parser instance).
934
1.17k
  PP.RemovePragmaHandler(MicrosoftExtHandler.get());
935
1.17k
  PP.RemovePragmaHandler("GCC", GCCHandler.get());
936
1.17k
  PP.RemovePragmaHandler("clang", ClangHandler.get());
937
1.17k
  PP.RemovePragmaHandler("omp", OpenMPHandler.get());
938
1.17k
}