1 //===--- ParsePragma.cpp - Language specific pragma parsing ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the language specific #pragma handlers.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Parse/Parser.h"
20 #include "clang/Sema/LoopHint.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/ADT/StringSwitch.h"
23 using namespace clang;
24
25 namespace {
26
27 struct PragmaAlignHandler : public PragmaHandler {
PragmaAlignHandler__anon302a61390111::PragmaAlignHandler28 explicit PragmaAlignHandler() : PragmaHandler("align") {}
29 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
30 Token &FirstToken) override;
31 };
32
33 struct PragmaGCCVisibilityHandler : public PragmaHandler {
PragmaGCCVisibilityHandler__anon302a61390111::PragmaGCCVisibilityHandler34 explicit PragmaGCCVisibilityHandler() : PragmaHandler("visibility") {}
35 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
36 Token &FirstToken) override;
37 };
38
39 struct PragmaOptionsHandler : public PragmaHandler {
PragmaOptionsHandler__anon302a61390111::PragmaOptionsHandler40 explicit PragmaOptionsHandler() : PragmaHandler("options") {}
41 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
42 Token &FirstToken) override;
43 };
44
45 struct PragmaPackHandler : public PragmaHandler {
PragmaPackHandler__anon302a61390111::PragmaPackHandler46 explicit PragmaPackHandler() : PragmaHandler("pack") {}
47 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
48 Token &FirstToken) override;
49 };
50
51 struct PragmaMSStructHandler : public PragmaHandler {
PragmaMSStructHandler__anon302a61390111::PragmaMSStructHandler52 explicit PragmaMSStructHandler() : PragmaHandler("ms_struct") {}
53 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
54 Token &FirstToken) override;
55 };
56
57 struct PragmaUnusedHandler : public PragmaHandler {
PragmaUnusedHandler__anon302a61390111::PragmaUnusedHandler58 PragmaUnusedHandler() : PragmaHandler("unused") {}
59 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
60 Token &FirstToken) override;
61 };
62
63 struct PragmaWeakHandler : public PragmaHandler {
PragmaWeakHandler__anon302a61390111::PragmaWeakHandler64 explicit PragmaWeakHandler() : PragmaHandler("weak") {}
65 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
66 Token &FirstToken) override;
67 };
68
69 struct PragmaRedefineExtnameHandler : public PragmaHandler {
PragmaRedefineExtnameHandler__anon302a61390111::PragmaRedefineExtnameHandler70 explicit PragmaRedefineExtnameHandler() : PragmaHandler("redefine_extname") {}
71 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
72 Token &FirstToken) override;
73 };
74
75 struct PragmaOpenCLExtensionHandler : public PragmaHandler {
PragmaOpenCLExtensionHandler__anon302a61390111::PragmaOpenCLExtensionHandler76 PragmaOpenCLExtensionHandler() : PragmaHandler("EXTENSION") {}
77 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
78 Token &FirstToken) override;
79 };
80
81
82 struct PragmaFPContractHandler : public PragmaHandler {
PragmaFPContractHandler__anon302a61390111::PragmaFPContractHandler83 PragmaFPContractHandler() : PragmaHandler("FP_CONTRACT") {}
84 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
85 Token &FirstToken) override;
86 };
87
88 struct PragmaNoOpenMPHandler : public PragmaHandler {
PragmaNoOpenMPHandler__anon302a61390111::PragmaNoOpenMPHandler89 PragmaNoOpenMPHandler() : PragmaHandler("omp") { }
90 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
91 Token &FirstToken) override;
92 };
93
94 struct PragmaOpenMPHandler : public PragmaHandler {
PragmaOpenMPHandler__anon302a61390111::PragmaOpenMPHandler95 PragmaOpenMPHandler() : PragmaHandler("omp") { }
96 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
97 Token &FirstToken) override;
98 };
99
100 /// PragmaCommentHandler - "\#pragma comment ...".
101 struct PragmaCommentHandler : public PragmaHandler {
PragmaCommentHandler__anon302a61390111::PragmaCommentHandler102 PragmaCommentHandler(Sema &Actions)
103 : PragmaHandler("comment"), Actions(Actions) {}
104 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
105 Token &FirstToken) override;
106 private:
107 Sema &Actions;
108 };
109
110 struct PragmaDetectMismatchHandler : public PragmaHandler {
PragmaDetectMismatchHandler__anon302a61390111::PragmaDetectMismatchHandler111 PragmaDetectMismatchHandler(Sema &Actions)
112 : PragmaHandler("detect_mismatch"), Actions(Actions) {}
113 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
114 Token &FirstToken) override;
115 private:
116 Sema &Actions;
117 };
118
119 struct PragmaMSPointersToMembers : public PragmaHandler {
PragmaMSPointersToMembers__anon302a61390111::PragmaMSPointersToMembers120 explicit PragmaMSPointersToMembers() : PragmaHandler("pointers_to_members") {}
121 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
122 Token &FirstToken) override;
123 };
124
125 struct PragmaMSVtorDisp : public PragmaHandler {
PragmaMSVtorDisp__anon302a61390111::PragmaMSVtorDisp126 explicit PragmaMSVtorDisp() : PragmaHandler("vtordisp") {}
127 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
128 Token &FirstToken) override;
129 };
130
131 struct PragmaMSPragma : public PragmaHandler {
PragmaMSPragma__anon302a61390111::PragmaMSPragma132 explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {}
133 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
134 Token &FirstToken) override;
135 };
136
137 /// PragmaOptimizeHandler - "\#pragma clang optimize on/off".
138 struct PragmaOptimizeHandler : public PragmaHandler {
PragmaOptimizeHandler__anon302a61390111::PragmaOptimizeHandler139 PragmaOptimizeHandler(Sema &S)
140 : PragmaHandler("optimize"), Actions(S) {}
141 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
142 Token &FirstToken) override;
143 private:
144 Sema &Actions;
145 };
146
147 struct PragmaLoopHintHandler : public PragmaHandler {
PragmaLoopHintHandler__anon302a61390111::PragmaLoopHintHandler148 PragmaLoopHintHandler() : PragmaHandler("loop") {}
149 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
150 Token &FirstToken) override;
151 };
152
153 struct PragmaUnrollHintHandler : public PragmaHandler {
PragmaUnrollHintHandler__anon302a61390111::PragmaUnrollHintHandler154 PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {}
155 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
156 Token &FirstToken) override;
157 };
158
159 } // end namespace
160
initializePragmaHandlers()161 void Parser::initializePragmaHandlers() {
162 AlignHandler.reset(new PragmaAlignHandler());
163 PP.AddPragmaHandler(AlignHandler.get());
164
165 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
166 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
167
168 OptionsHandler.reset(new PragmaOptionsHandler());
169 PP.AddPragmaHandler(OptionsHandler.get());
170
171 PackHandler.reset(new PragmaPackHandler());
172 PP.AddPragmaHandler(PackHandler.get());
173
174 MSStructHandler.reset(new PragmaMSStructHandler());
175 PP.AddPragmaHandler(MSStructHandler.get());
176
177 UnusedHandler.reset(new PragmaUnusedHandler());
178 PP.AddPragmaHandler(UnusedHandler.get());
179
180 WeakHandler.reset(new PragmaWeakHandler());
181 PP.AddPragmaHandler(WeakHandler.get());
182
183 RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
184 PP.AddPragmaHandler(RedefineExtnameHandler.get());
185
186 FPContractHandler.reset(new PragmaFPContractHandler());
187 PP.AddPragmaHandler("STDC", FPContractHandler.get());
188
189 if (getLangOpts().OpenCL) {
190 OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
191 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
192
193 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
194 }
195 if (getLangOpts().OpenMP)
196 OpenMPHandler.reset(new PragmaOpenMPHandler());
197 else
198 OpenMPHandler.reset(new PragmaNoOpenMPHandler());
199 PP.AddPragmaHandler(OpenMPHandler.get());
200
201 if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) {
202 MSCommentHandler.reset(new PragmaCommentHandler(Actions));
203 PP.AddPragmaHandler(MSCommentHandler.get());
204 }
205
206 if (getLangOpts().MicrosoftExt) {
207 MSDetectMismatchHandler.reset(new PragmaDetectMismatchHandler(Actions));
208 PP.AddPragmaHandler(MSDetectMismatchHandler.get());
209 MSPointersToMembers.reset(new PragmaMSPointersToMembers());
210 PP.AddPragmaHandler(MSPointersToMembers.get());
211 MSVtorDisp.reset(new PragmaMSVtorDisp());
212 PP.AddPragmaHandler(MSVtorDisp.get());
213 MSInitSeg.reset(new PragmaMSPragma("init_seg"));
214 PP.AddPragmaHandler(MSInitSeg.get());
215 MSDataSeg.reset(new PragmaMSPragma("data_seg"));
216 PP.AddPragmaHandler(MSDataSeg.get());
217 MSBSSSeg.reset(new PragmaMSPragma("bss_seg"));
218 PP.AddPragmaHandler(MSBSSSeg.get());
219 MSConstSeg.reset(new PragmaMSPragma("const_seg"));
220 PP.AddPragmaHandler(MSConstSeg.get());
221 MSCodeSeg.reset(new PragmaMSPragma("code_seg"));
222 PP.AddPragmaHandler(MSCodeSeg.get());
223 MSSection.reset(new PragmaMSPragma("section"));
224 PP.AddPragmaHandler(MSSection.get());
225 }
226
227 OptimizeHandler.reset(new PragmaOptimizeHandler(Actions));
228 PP.AddPragmaHandler("clang", OptimizeHandler.get());
229
230 LoopHintHandler.reset(new PragmaLoopHintHandler());
231 PP.AddPragmaHandler("clang", LoopHintHandler.get());
232
233 UnrollHintHandler.reset(new PragmaUnrollHintHandler("unroll"));
234 PP.AddPragmaHandler(UnrollHintHandler.get());
235
236 NoUnrollHintHandler.reset(new PragmaUnrollHintHandler("nounroll"));
237 PP.AddPragmaHandler(NoUnrollHintHandler.get());
238 }
239
resetPragmaHandlers()240 void Parser::resetPragmaHandlers() {
241 // Remove the pragma handlers we installed.
242 PP.RemovePragmaHandler(AlignHandler.get());
243 AlignHandler.reset();
244 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
245 GCCVisibilityHandler.reset();
246 PP.RemovePragmaHandler(OptionsHandler.get());
247 OptionsHandler.reset();
248 PP.RemovePragmaHandler(PackHandler.get());
249 PackHandler.reset();
250 PP.RemovePragmaHandler(MSStructHandler.get());
251 MSStructHandler.reset();
252 PP.RemovePragmaHandler(UnusedHandler.get());
253 UnusedHandler.reset();
254 PP.RemovePragmaHandler(WeakHandler.get());
255 WeakHandler.reset();
256 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
257 RedefineExtnameHandler.reset();
258
259 if (getLangOpts().OpenCL) {
260 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
261 OpenCLExtensionHandler.reset();
262 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
263 }
264 PP.RemovePragmaHandler(OpenMPHandler.get());
265 OpenMPHandler.reset();
266
267 if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) {
268 PP.RemovePragmaHandler(MSCommentHandler.get());
269 MSCommentHandler.reset();
270 }
271
272 if (getLangOpts().MicrosoftExt) {
273 PP.RemovePragmaHandler(MSDetectMismatchHandler.get());
274 MSDetectMismatchHandler.reset();
275 PP.RemovePragmaHandler(MSPointersToMembers.get());
276 MSPointersToMembers.reset();
277 PP.RemovePragmaHandler(MSVtorDisp.get());
278 MSVtorDisp.reset();
279 PP.RemovePragmaHandler(MSInitSeg.get());
280 MSInitSeg.reset();
281 PP.RemovePragmaHandler(MSDataSeg.get());
282 MSDataSeg.reset();
283 PP.RemovePragmaHandler(MSBSSSeg.get());
284 MSBSSSeg.reset();
285 PP.RemovePragmaHandler(MSConstSeg.get());
286 MSConstSeg.reset();
287 PP.RemovePragmaHandler(MSCodeSeg.get());
288 MSCodeSeg.reset();
289 PP.RemovePragmaHandler(MSSection.get());
290 MSSection.reset();
291 }
292
293 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
294 FPContractHandler.reset();
295
296 PP.RemovePragmaHandler("clang", OptimizeHandler.get());
297 OptimizeHandler.reset();
298
299 PP.RemovePragmaHandler("clang", LoopHintHandler.get());
300 LoopHintHandler.reset();
301
302 PP.RemovePragmaHandler(UnrollHintHandler.get());
303 UnrollHintHandler.reset();
304
305 PP.RemovePragmaHandler(NoUnrollHintHandler.get());
306 NoUnrollHintHandler.reset();
307 }
308
309 /// \brief Handle the annotation token produced for #pragma unused(...)
310 ///
311 /// Each annot_pragma_unused is followed by the argument token so e.g.
312 /// "#pragma unused(x,y)" becomes:
313 /// annot_pragma_unused 'x' annot_pragma_unused 'y'
HandlePragmaUnused()314 void Parser::HandlePragmaUnused() {
315 assert(Tok.is(tok::annot_pragma_unused));
316 SourceLocation UnusedLoc = ConsumeToken();
317 Actions.ActOnPragmaUnused(Tok, getCurScope(), UnusedLoc);
318 ConsumeToken(); // The argument token.
319 }
320
HandlePragmaVisibility()321 void Parser::HandlePragmaVisibility() {
322 assert(Tok.is(tok::annot_pragma_vis));
323 const IdentifierInfo *VisType =
324 static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
325 SourceLocation VisLoc = ConsumeToken();
326 Actions.ActOnPragmaVisibility(VisType, VisLoc);
327 }
328
329 struct PragmaPackInfo {
330 Sema::PragmaPackKind Kind;
331 IdentifierInfo *Name;
332 Token Alignment;
333 SourceLocation LParenLoc;
334 SourceLocation RParenLoc;
335 };
336
HandlePragmaPack()337 void Parser::HandlePragmaPack() {
338 assert(Tok.is(tok::annot_pragma_pack));
339 PragmaPackInfo *Info =
340 static_cast<PragmaPackInfo *>(Tok.getAnnotationValue());
341 SourceLocation PragmaLoc = ConsumeToken();
342 ExprResult Alignment;
343 if (Info->Alignment.is(tok::numeric_constant)) {
344 Alignment = Actions.ActOnNumericConstant(Info->Alignment);
345 if (Alignment.isInvalid())
346 return;
347 }
348 Actions.ActOnPragmaPack(Info->Kind, Info->Name, Alignment.get(), PragmaLoc,
349 Info->LParenLoc, Info->RParenLoc);
350 }
351
HandlePragmaMSStruct()352 void Parser::HandlePragmaMSStruct() {
353 assert(Tok.is(tok::annot_pragma_msstruct));
354 Sema::PragmaMSStructKind Kind =
355 static_cast<Sema::PragmaMSStructKind>(
356 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
357 Actions.ActOnPragmaMSStruct(Kind);
358 ConsumeToken(); // The annotation token.
359 }
360
HandlePragmaAlign()361 void Parser::HandlePragmaAlign() {
362 assert(Tok.is(tok::annot_pragma_align));
363 Sema::PragmaOptionsAlignKind Kind =
364 static_cast<Sema::PragmaOptionsAlignKind>(
365 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
366 SourceLocation PragmaLoc = ConsumeToken();
367 Actions.ActOnPragmaOptionsAlign(Kind, PragmaLoc);
368 }
369
HandlePragmaWeak()370 void Parser::HandlePragmaWeak() {
371 assert(Tok.is(tok::annot_pragma_weak));
372 SourceLocation PragmaLoc = ConsumeToken();
373 Actions.ActOnPragmaWeakID(Tok.getIdentifierInfo(), PragmaLoc,
374 Tok.getLocation());
375 ConsumeToken(); // The weak name.
376 }
377
HandlePragmaWeakAlias()378 void Parser::HandlePragmaWeakAlias() {
379 assert(Tok.is(tok::annot_pragma_weakalias));
380 SourceLocation PragmaLoc = ConsumeToken();
381 IdentifierInfo *WeakName = Tok.getIdentifierInfo();
382 SourceLocation WeakNameLoc = Tok.getLocation();
383 ConsumeToken();
384 IdentifierInfo *AliasName = Tok.getIdentifierInfo();
385 SourceLocation AliasNameLoc = Tok.getLocation();
386 ConsumeToken();
387 Actions.ActOnPragmaWeakAlias(WeakName, AliasName, PragmaLoc,
388 WeakNameLoc, AliasNameLoc);
389
390 }
391
HandlePragmaRedefineExtname()392 void Parser::HandlePragmaRedefineExtname() {
393 assert(Tok.is(tok::annot_pragma_redefine_extname));
394 SourceLocation RedefLoc = ConsumeToken();
395 IdentifierInfo *RedefName = Tok.getIdentifierInfo();
396 SourceLocation RedefNameLoc = Tok.getLocation();
397 ConsumeToken();
398 IdentifierInfo *AliasName = Tok.getIdentifierInfo();
399 SourceLocation AliasNameLoc = Tok.getLocation();
400 ConsumeToken();
401 Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc,
402 RedefNameLoc, AliasNameLoc);
403 }
404
HandlePragmaFPContract()405 void Parser::HandlePragmaFPContract() {
406 assert(Tok.is(tok::annot_pragma_fp_contract));
407 tok::OnOffSwitch OOS =
408 static_cast<tok::OnOffSwitch>(
409 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
410 Actions.ActOnPragmaFPContract(OOS);
411 ConsumeToken(); // The annotation token.
412 }
413
HandlePragmaCaptured()414 StmtResult Parser::HandlePragmaCaptured()
415 {
416 assert(Tok.is(tok::annot_pragma_captured));
417 ConsumeToken();
418
419 if (Tok.isNot(tok::l_brace)) {
420 PP.Diag(Tok, diag::err_expected) << tok::l_brace;
421 return StmtError();
422 }
423
424 SourceLocation Loc = Tok.getLocation();
425
426 ParseScope CapturedRegionScope(this, Scope::FnScope | Scope::DeclScope);
427 Actions.ActOnCapturedRegionStart(Loc, getCurScope(), CR_Default,
428 /*NumParams=*/1);
429
430 StmtResult R = ParseCompoundStatement();
431 CapturedRegionScope.Exit();
432
433 if (R.isInvalid()) {
434 Actions.ActOnCapturedRegionError();
435 return StmtError();
436 }
437
438 return Actions.ActOnCapturedRegionEnd(R.get());
439 }
440
441 namespace {
442 typedef llvm::PointerIntPair<IdentifierInfo *, 1, bool> OpenCLExtData;
443 }
444
HandlePragmaOpenCLExtension()445 void Parser::HandlePragmaOpenCLExtension() {
446 assert(Tok.is(tok::annot_pragma_opencl_extension));
447 OpenCLExtData data =
448 OpenCLExtData::getFromOpaqueValue(Tok.getAnnotationValue());
449 unsigned state = data.getInt();
450 IdentifierInfo *ename = data.getPointer();
451 SourceLocation NameLoc = Tok.getLocation();
452 ConsumeToken(); // The annotation token.
453
454 OpenCLOptions &f = Actions.getOpenCLOptions();
455 // OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions,
456 // overriding all previously issued extension directives, but only if the
457 // behavior is set to disable."
458 if (state == 0 && ename->isStr("all")) {
459 #define OPENCLEXT(nm) f.nm = 0;
460 #include "clang/Basic/OpenCLExtensions.def"
461 }
462 #define OPENCLEXT(nm) else if (ename->isStr(#nm)) { f.nm = state; }
463 #include "clang/Basic/OpenCLExtensions.def"
464 else {
465 PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << ename;
466 return;
467 }
468 }
469
HandlePragmaMSPointersToMembers()470 void Parser::HandlePragmaMSPointersToMembers() {
471 assert(Tok.is(tok::annot_pragma_ms_pointers_to_members));
472 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod =
473 static_cast<LangOptions::PragmaMSPointersToMembersKind>(
474 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
475 SourceLocation PragmaLoc = ConsumeToken(); // The annotation token.
476 Actions.ActOnPragmaMSPointersToMembers(RepresentationMethod, PragmaLoc);
477 }
478
HandlePragmaMSVtorDisp()479 void Parser::HandlePragmaMSVtorDisp() {
480 assert(Tok.is(tok::annot_pragma_ms_vtordisp));
481 uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
482 Sema::PragmaVtorDispKind Kind =
483 static_cast<Sema::PragmaVtorDispKind>((Value >> 16) & 0xFFFF);
484 MSVtorDispAttr::Mode Mode = MSVtorDispAttr::Mode(Value & 0xFFFF);
485 SourceLocation PragmaLoc = ConsumeToken(); // The annotation token.
486 Actions.ActOnPragmaMSVtorDisp(Kind, PragmaLoc, Mode);
487 }
488
HandlePragmaMSPragma()489 void Parser::HandlePragmaMSPragma() {
490 assert(Tok.is(tok::annot_pragma_ms_pragma));
491 // Grab the tokens out of the annotation and enter them into the stream.
492 auto TheTokens = (std::pair<Token*, size_t> *)Tok.getAnnotationValue();
493 PP.EnterTokenStream(TheTokens->first, TheTokens->second, true, true);
494 SourceLocation PragmaLocation = ConsumeToken(); // The annotation token.
495 assert(Tok.isAnyIdentifier());
496 StringRef PragmaName = Tok.getIdentifierInfo()->getName();
497 PP.Lex(Tok); // pragma kind
498
499 // Figure out which #pragma we're dealing with. The switch has no default
500 // because lex shouldn't emit the annotation token for unrecognized pragmas.
501 typedef bool (Parser::*PragmaHandler)(StringRef, SourceLocation);
502 PragmaHandler Handler = llvm::StringSwitch<PragmaHandler>(PragmaName)
503 .Case("data_seg", &Parser::HandlePragmaMSSegment)
504 .Case("bss_seg", &Parser::HandlePragmaMSSegment)
505 .Case("const_seg", &Parser::HandlePragmaMSSegment)
506 .Case("code_seg", &Parser::HandlePragmaMSSegment)
507 .Case("section", &Parser::HandlePragmaMSSection)
508 .Case("init_seg", &Parser::HandlePragmaMSInitSeg);
509
510 if (!(this->*Handler)(PragmaName, PragmaLocation)) {
511 // Pragma handling failed, and has been diagnosed. Slurp up the tokens
512 // until eof (really end of line) to prevent follow-on errors.
513 while (Tok.isNot(tok::eof))
514 PP.Lex(Tok);
515 PP.Lex(Tok);
516 }
517 }
518
HandlePragmaMSSection(StringRef PragmaName,SourceLocation PragmaLocation)519 bool Parser::HandlePragmaMSSection(StringRef PragmaName,
520 SourceLocation PragmaLocation) {
521 if (Tok.isNot(tok::l_paren)) {
522 PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
523 return false;
524 }
525 PP.Lex(Tok); // (
526 // Parsing code for pragma section
527 if (Tok.isNot(tok::string_literal)) {
528 PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name)
529 << PragmaName;
530 return false;
531 }
532 ExprResult StringResult = ParseStringLiteralExpression();
533 if (StringResult.isInvalid())
534 return false; // Already diagnosed.
535 StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get());
536 if (SegmentName->getCharByteWidth() != 1) {
537 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
538 << PragmaName;
539 return false;
540 }
541 int SectionFlags = ASTContext::PSF_Read;
542 bool SectionFlagsAreDefault = true;
543 while (Tok.is(tok::comma)) {
544 PP.Lex(Tok); // ,
545 // Ignore "long" and "short".
546 // They are undocumented, but widely used, section attributes which appear
547 // to do nothing.
548 if (Tok.is(tok::kw_long) || Tok.is(tok::kw_short)) {
549 PP.Lex(Tok); // long/short
550 continue;
551 }
552
553 if (!Tok.isAnyIdentifier()) {
554 PP.Diag(PragmaLocation, diag::warn_pragma_expected_action_or_r_paren)
555 << PragmaName;
556 return false;
557 }
558 ASTContext::PragmaSectionFlag Flag =
559 llvm::StringSwitch<ASTContext::PragmaSectionFlag>(
560 Tok.getIdentifierInfo()->getName())
561 .Case("read", ASTContext::PSF_Read)
562 .Case("write", ASTContext::PSF_Write)
563 .Case("execute", ASTContext::PSF_Execute)
564 .Case("shared", ASTContext::PSF_Invalid)
565 .Case("nopage", ASTContext::PSF_Invalid)
566 .Case("nocache", ASTContext::PSF_Invalid)
567 .Case("discard", ASTContext::PSF_Invalid)
568 .Case("remove", ASTContext::PSF_Invalid)
569 .Default(ASTContext::PSF_None);
570 if (Flag == ASTContext::PSF_None || Flag == ASTContext::PSF_Invalid) {
571 PP.Diag(PragmaLocation, Flag == ASTContext::PSF_None
572 ? diag::warn_pragma_invalid_specific_action
573 : diag::warn_pragma_unsupported_action)
574 << PragmaName << Tok.getIdentifierInfo()->getName();
575 return false;
576 }
577 SectionFlags |= Flag;
578 SectionFlagsAreDefault = false;
579 PP.Lex(Tok); // Identifier
580 }
581 // If no section attributes are specified, the section will be marked as
582 // read/write.
583 if (SectionFlagsAreDefault)
584 SectionFlags |= ASTContext::PSF_Write;
585 if (Tok.isNot(tok::r_paren)) {
586 PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
587 return false;
588 }
589 PP.Lex(Tok); // )
590 if (Tok.isNot(tok::eof)) {
591 PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
592 << PragmaName;
593 return false;
594 }
595 PP.Lex(Tok); // eof
596 Actions.ActOnPragmaMSSection(PragmaLocation, SectionFlags, SegmentName);
597 return true;
598 }
599
HandlePragmaMSSegment(StringRef PragmaName,SourceLocation PragmaLocation)600 bool Parser::HandlePragmaMSSegment(StringRef PragmaName,
601 SourceLocation PragmaLocation) {
602 if (Tok.isNot(tok::l_paren)) {
603 PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
604 return false;
605 }
606 PP.Lex(Tok); // (
607 Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
608 StringRef SlotLabel;
609 if (Tok.isAnyIdentifier()) {
610 StringRef PushPop = Tok.getIdentifierInfo()->getName();
611 if (PushPop == "push")
612 Action = Sema::PSK_Push;
613 else if (PushPop == "pop")
614 Action = Sema::PSK_Pop;
615 else {
616 PP.Diag(PragmaLocation,
617 diag::warn_pragma_expected_section_push_pop_or_name)
618 << PragmaName;
619 return false;
620 }
621 if (Action != Sema::PSK_Reset) {
622 PP.Lex(Tok); // push | pop
623 if (Tok.is(tok::comma)) {
624 PP.Lex(Tok); // ,
625 // If we've got a comma, we either need a label or a string.
626 if (Tok.isAnyIdentifier()) {
627 SlotLabel = Tok.getIdentifierInfo()->getName();
628 PP.Lex(Tok); // identifier
629 if (Tok.is(tok::comma))
630 PP.Lex(Tok);
631 else if (Tok.isNot(tok::r_paren)) {
632 PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc)
633 << PragmaName;
634 return false;
635 }
636 }
637 } else if (Tok.isNot(tok::r_paren)) {
638 PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName;
639 return false;
640 }
641 }
642 }
643 // Grab the string literal for our section name.
644 StringLiteral *SegmentName = nullptr;
645 if (Tok.isNot(tok::r_paren)) {
646 if (Tok.isNot(tok::string_literal)) {
647 unsigned DiagID = Action != Sema::PSK_Reset ? !SlotLabel.empty() ?
648 diag::warn_pragma_expected_section_name :
649 diag::warn_pragma_expected_section_label_or_name :
650 diag::warn_pragma_expected_section_push_pop_or_name;
651 PP.Diag(PragmaLocation, DiagID) << PragmaName;
652 return false;
653 }
654 ExprResult StringResult = ParseStringLiteralExpression();
655 if (StringResult.isInvalid())
656 return false; // Already diagnosed.
657 SegmentName = cast<StringLiteral>(StringResult.get());
658 if (SegmentName->getCharByteWidth() != 1) {
659 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
660 << PragmaName;
661 return false;
662 }
663 // Setting section "" has no effect
664 if (SegmentName->getLength())
665 Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
666 }
667 if (Tok.isNot(tok::r_paren)) {
668 PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
669 return false;
670 }
671 PP.Lex(Tok); // )
672 if (Tok.isNot(tok::eof)) {
673 PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
674 << PragmaName;
675 return false;
676 }
677 PP.Lex(Tok); // eof
678 Actions.ActOnPragmaMSSeg(PragmaLocation, Action, SlotLabel,
679 SegmentName, PragmaName);
680 return true;
681 }
682
683 // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
HandlePragmaMSInitSeg(StringRef PragmaName,SourceLocation PragmaLocation)684 bool Parser::HandlePragmaMSInitSeg(StringRef PragmaName,
685 SourceLocation PragmaLocation) {
686 if (getTargetInfo().getTriple().getEnvironment() != llvm::Triple::MSVC) {
687 PP.Diag(PragmaLocation, diag::warn_pragma_init_seg_unsupported_target);
688 return false;
689 }
690
691 if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
692 PragmaName))
693 return false;
694
695 // Parse either the known section names or the string section name.
696 StringLiteral *SegmentName = nullptr;
697 if (Tok.isAnyIdentifier()) {
698 auto *II = Tok.getIdentifierInfo();
699 StringRef Section = llvm::StringSwitch<StringRef>(II->getName())
700 .Case("compiler", "\".CRT$XCC\"")
701 .Case("lib", "\".CRT$XCL\"")
702 .Case("user", "\".CRT$XCU\"")
703 .Default("");
704
705 if (!Section.empty()) {
706 // Pretend the user wrote the appropriate string literal here.
707 Token Toks[1];
708 Toks[0].startToken();
709 Toks[0].setKind(tok::string_literal);
710 Toks[0].setLocation(Tok.getLocation());
711 Toks[0].setLiteralData(Section.data());
712 Toks[0].setLength(Section.size());
713 SegmentName =
714 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
715 PP.Lex(Tok);
716 }
717 } else if (Tok.is(tok::string_literal)) {
718 ExprResult StringResult = ParseStringLiteralExpression();
719 if (StringResult.isInvalid())
720 return false;
721 SegmentName = cast<StringLiteral>(StringResult.get());
722 if (SegmentName->getCharByteWidth() != 1) {
723 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
724 << PragmaName;
725 return false;
726 }
727 // FIXME: Add support for the '[, func-name]' part of the pragma.
728 }
729
730 if (!SegmentName) {
731 PP.Diag(PragmaLocation, diag::warn_pragma_expected_init_seg) << PragmaName;
732 return false;
733 }
734
735 if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
736 PragmaName) ||
737 ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
738 PragmaName))
739 return false;
740
741 Actions.ActOnPragmaMSInitSeg(PragmaLocation, SegmentName);
742 return true;
743 }
744
745 struct PragmaLoopHintInfo {
746 Token PragmaName;
747 Token Option;
748 Token *Toks;
749 size_t TokSize;
PragmaLoopHintInfoPragmaLoopHintInfo750 PragmaLoopHintInfo() : Toks(nullptr), TokSize(0) {}
751 };
752
PragmaLoopHintString(Token PragmaName,Token Option)753 static std::string PragmaLoopHintString(Token PragmaName, Token Option) {
754 std::string PragmaString;
755 if (PragmaName.getIdentifierInfo()->getName() == "loop") {
756 PragmaString = "clang loop ";
757 PragmaString += Option.getIdentifierInfo()->getName();
758 } else {
759 assert(PragmaName.getIdentifierInfo()->getName() == "unroll" &&
760 "Unexpected pragma name");
761 PragmaString = "unroll";
762 }
763 return PragmaString;
764 }
765
HandlePragmaLoopHint(LoopHint & Hint)766 bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
767 assert(Tok.is(tok::annot_pragma_loop_hint));
768 PragmaLoopHintInfo *Info =
769 static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
770
771 IdentifierInfo *PragmaNameInfo = Info->PragmaName.getIdentifierInfo();
772 Hint.PragmaNameLoc = IdentifierLoc::create(
773 Actions.Context, Info->PragmaName.getLocation(), PragmaNameInfo);
774
775 // It is possible that the loop hint has no option identifier, such as
776 // #pragma unroll(4).
777 IdentifierInfo *OptionInfo = Info->Option.is(tok::identifier)
778 ? Info->Option.getIdentifierInfo()
779 : nullptr;
780 Hint.OptionLoc = IdentifierLoc::create(
781 Actions.Context, Info->Option.getLocation(), OptionInfo);
782
783 Token *Toks = Info->Toks;
784 size_t TokSize = Info->TokSize;
785
786 // Return a valid hint if pragma unroll or nounroll were specified
787 // without an argument.
788 bool PragmaUnroll = PragmaNameInfo->getName() == "unroll";
789 bool PragmaNoUnroll = PragmaNameInfo->getName() == "nounroll";
790 if (TokSize == 0 && (PragmaUnroll || PragmaNoUnroll)) {
791 ConsumeToken(); // The annotation token.
792 Hint.Range = Info->PragmaName.getLocation();
793 return true;
794 }
795
796 // The constant expression is always followed by an eof token, which increases
797 // the TokSize by 1.
798 assert(TokSize > 0 &&
799 "PragmaLoopHintInfo::Toks must contain at least one token.");
800
801 // If no option is specified the argument is assumed to be a constant expr.
802 bool StateOption = false;
803 if (OptionInfo) { // Pragma unroll does not specify an option.
804 StateOption = llvm::StringSwitch<bool>(OptionInfo->getName())
805 .Case("vectorize", true)
806 .Case("interleave", true)
807 .Case("unroll", true)
808 .Default(false);
809 }
810
811 // Verify loop hint has an argument.
812 if (Toks[0].is(tok::eof)) {
813 ConsumeToken(); // The annotation token.
814 Diag(Toks[0].getLocation(), diag::err_pragma_loop_missing_argument)
815 << /*StateArgument=*/StateOption << /*FullKeyword=*/PragmaUnroll;
816 return false;
817 }
818
819 // Validate the argument.
820 if (StateOption) {
821 ConsumeToken(); // The annotation token.
822 bool OptionUnroll = OptionInfo->isStr("unroll");
823 SourceLocation StateLoc = Toks[0].getLocation();
824 IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
825 if (!StateInfo || ((OptionUnroll ? !StateInfo->isStr("full")
826 : !StateInfo->isStr("enable")) &&
827 !StateInfo->isStr("disable"))) {
828 Diag(Toks[0].getLocation(), diag::err_pragma_invalid_keyword)
829 << /*FullKeyword=*/OptionUnroll;
830 return false;
831 }
832 if (TokSize > 2)
833 Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
834 << PragmaLoopHintString(Info->PragmaName, Info->Option);
835 Hint.StateLoc = IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
836 } else {
837 // Enter constant expression including eof terminator into token stream.
838 PP.EnterTokenStream(Toks, TokSize, /*DisableMacroExpansion=*/false,
839 /*OwnsTokens=*/false);
840 ConsumeToken(); // The annotation token.
841
842 ExprResult R = ParseConstantExpression();
843
844 // Tokens following an error in an ill-formed constant expression will
845 // remain in the token stream and must be removed.
846 if (Tok.isNot(tok::eof)) {
847 Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
848 << PragmaLoopHintString(Info->PragmaName, Info->Option);
849 while (Tok.isNot(tok::eof))
850 ConsumeAnyToken();
851 }
852
853 ConsumeToken(); // Consume the constant expression eof terminator.
854
855 if (R.isInvalid() ||
856 Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
857 return false;
858
859 // Argument is a constant expression with an integer type.
860 Hint.ValueExpr = R.get();
861 }
862
863 Hint.Range = SourceRange(Info->PragmaName.getLocation(),
864 Info->Toks[TokSize - 1].getLocation());
865 return true;
866 }
867
868 // #pragma GCC visibility comes in two variants:
869 // 'push' '(' [visibility] ')'
870 // 'pop'
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & VisTok)871 void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP,
872 PragmaIntroducerKind Introducer,
873 Token &VisTok) {
874 SourceLocation VisLoc = VisTok.getLocation();
875
876 Token Tok;
877 PP.LexUnexpandedToken(Tok);
878
879 const IdentifierInfo *PushPop = Tok.getIdentifierInfo();
880
881 const IdentifierInfo *VisType;
882 if (PushPop && PushPop->isStr("pop")) {
883 VisType = nullptr;
884 } else if (PushPop && PushPop->isStr("push")) {
885 PP.LexUnexpandedToken(Tok);
886 if (Tok.isNot(tok::l_paren)) {
887 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
888 << "visibility";
889 return;
890 }
891 PP.LexUnexpandedToken(Tok);
892 VisType = Tok.getIdentifierInfo();
893 if (!VisType) {
894 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
895 << "visibility";
896 return;
897 }
898 PP.LexUnexpandedToken(Tok);
899 if (Tok.isNot(tok::r_paren)) {
900 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
901 << "visibility";
902 return;
903 }
904 } else {
905 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
906 << "visibility";
907 return;
908 }
909 SourceLocation EndLoc = Tok.getLocation();
910 PP.LexUnexpandedToken(Tok);
911 if (Tok.isNot(tok::eod)) {
912 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
913 << "visibility";
914 return;
915 }
916
917 Token *Toks = new Token[1];
918 Toks[0].startToken();
919 Toks[0].setKind(tok::annot_pragma_vis);
920 Toks[0].setLocation(VisLoc);
921 Toks[0].setAnnotationEndLoc(EndLoc);
922 Toks[0].setAnnotationValue(
923 const_cast<void*>(static_cast<const void*>(VisType)));
924 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
925 /*OwnsTokens=*/true);
926 }
927
928 // #pragma pack(...) comes in the following delicious flavors:
929 // pack '(' [integer] ')'
930 // pack '(' 'show' ')'
931 // pack '(' ('push' | 'pop') [',' identifier] [, integer] ')'
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & PackTok)932 void PragmaPackHandler::HandlePragma(Preprocessor &PP,
933 PragmaIntroducerKind Introducer,
934 Token &PackTok) {
935 SourceLocation PackLoc = PackTok.getLocation();
936
937 Token Tok;
938 PP.Lex(Tok);
939 if (Tok.isNot(tok::l_paren)) {
940 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack";
941 return;
942 }
943
944 Sema::PragmaPackKind Kind = Sema::PPK_Default;
945 IdentifierInfo *Name = nullptr;
946 Token Alignment;
947 Alignment.startToken();
948 SourceLocation LParenLoc = Tok.getLocation();
949 PP.Lex(Tok);
950 if (Tok.is(tok::numeric_constant)) {
951 Alignment = Tok;
952
953 PP.Lex(Tok);
954
955 // In MSVC/gcc, #pragma pack(4) sets the alignment without affecting
956 // the push/pop stack.
957 // In Apple gcc, #pragma pack(4) is equivalent to #pragma pack(push, 4)
958 if (PP.getLangOpts().ApplePragmaPack)
959 Kind = Sema::PPK_Push;
960 } else if (Tok.is(tok::identifier)) {
961 const IdentifierInfo *II = Tok.getIdentifierInfo();
962 if (II->isStr("show")) {
963 Kind = Sema::PPK_Show;
964 PP.Lex(Tok);
965 } else {
966 if (II->isStr("push")) {
967 Kind = Sema::PPK_Push;
968 } else if (II->isStr("pop")) {
969 Kind = Sema::PPK_Pop;
970 } else {
971 PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "pack";
972 return;
973 }
974 PP.Lex(Tok);
975
976 if (Tok.is(tok::comma)) {
977 PP.Lex(Tok);
978
979 if (Tok.is(tok::numeric_constant)) {
980 Alignment = Tok;
981
982 PP.Lex(Tok);
983 } else if (Tok.is(tok::identifier)) {
984 Name = Tok.getIdentifierInfo();
985 PP.Lex(Tok);
986
987 if (Tok.is(tok::comma)) {
988 PP.Lex(Tok);
989
990 if (Tok.isNot(tok::numeric_constant)) {
991 PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
992 return;
993 }
994
995 Alignment = Tok;
996
997 PP.Lex(Tok);
998 }
999 } else {
1000 PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
1001 return;
1002 }
1003 }
1004 }
1005 } else if (PP.getLangOpts().ApplePragmaPack) {
1006 // In MSVC/gcc, #pragma pack() resets the alignment without affecting
1007 // the push/pop stack.
1008 // In Apple gcc #pragma pack() is equivalent to #pragma pack(pop).
1009 Kind = Sema::PPK_Pop;
1010 }
1011
1012 if (Tok.isNot(tok::r_paren)) {
1013 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack";
1014 return;
1015 }
1016
1017 SourceLocation RParenLoc = Tok.getLocation();
1018 PP.Lex(Tok);
1019 if (Tok.isNot(tok::eod)) {
1020 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pack";
1021 return;
1022 }
1023
1024 PragmaPackInfo *Info =
1025 (PragmaPackInfo*) PP.getPreprocessorAllocator().Allocate(
1026 sizeof(PragmaPackInfo), llvm::alignOf<PragmaPackInfo>());
1027 new (Info) PragmaPackInfo();
1028 Info->Kind = Kind;
1029 Info->Name = Name;
1030 Info->Alignment = Alignment;
1031 Info->LParenLoc = LParenLoc;
1032 Info->RParenLoc = RParenLoc;
1033
1034 Token *Toks =
1035 (Token*) PP.getPreprocessorAllocator().Allocate(
1036 sizeof(Token) * 1, llvm::alignOf<Token>());
1037 new (Toks) Token();
1038 Toks[0].startToken();
1039 Toks[0].setKind(tok::annot_pragma_pack);
1040 Toks[0].setLocation(PackLoc);
1041 Toks[0].setAnnotationEndLoc(RParenLoc);
1042 Toks[0].setAnnotationValue(static_cast<void*>(Info));
1043 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1044 /*OwnsTokens=*/false);
1045 }
1046
1047 // #pragma ms_struct on
1048 // #pragma ms_struct off
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & MSStructTok)1049 void PragmaMSStructHandler::HandlePragma(Preprocessor &PP,
1050 PragmaIntroducerKind Introducer,
1051 Token &MSStructTok) {
1052 Sema::PragmaMSStructKind Kind = Sema::PMSST_OFF;
1053
1054 Token Tok;
1055 PP.Lex(Tok);
1056 if (Tok.isNot(tok::identifier)) {
1057 PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
1058 return;
1059 }
1060 SourceLocation EndLoc = Tok.getLocation();
1061 const IdentifierInfo *II = Tok.getIdentifierInfo();
1062 if (II->isStr("on")) {
1063 Kind = Sema::PMSST_ON;
1064 PP.Lex(Tok);
1065 }
1066 else if (II->isStr("off") || II->isStr("reset"))
1067 PP.Lex(Tok);
1068 else {
1069 PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
1070 return;
1071 }
1072
1073 if (Tok.isNot(tok::eod)) {
1074 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1075 << "ms_struct";
1076 return;
1077 }
1078
1079 Token *Toks =
1080 (Token*) PP.getPreprocessorAllocator().Allocate(
1081 sizeof(Token) * 1, llvm::alignOf<Token>());
1082 new (Toks) Token();
1083 Toks[0].startToken();
1084 Toks[0].setKind(tok::annot_pragma_msstruct);
1085 Toks[0].setLocation(MSStructTok.getLocation());
1086 Toks[0].setAnnotationEndLoc(EndLoc);
1087 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1088 static_cast<uintptr_t>(Kind)));
1089 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1090 /*OwnsTokens=*/false);
1091 }
1092
1093 // #pragma 'align' '=' {'native','natural','mac68k','power','reset'}
1094 // #pragma 'options 'align' '=' {'native','natural','mac68k','power','reset'}
ParseAlignPragma(Preprocessor & PP,Token & FirstTok,bool IsOptions)1095 static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok,
1096 bool IsOptions) {
1097 Token Tok;
1098
1099 if (IsOptions) {
1100 PP.Lex(Tok);
1101 if (Tok.isNot(tok::identifier) ||
1102 !Tok.getIdentifierInfo()->isStr("align")) {
1103 PP.Diag(Tok.getLocation(), diag::warn_pragma_options_expected_align);
1104 return;
1105 }
1106 }
1107
1108 PP.Lex(Tok);
1109 if (Tok.isNot(tok::equal)) {
1110 PP.Diag(Tok.getLocation(), diag::warn_pragma_align_expected_equal)
1111 << IsOptions;
1112 return;
1113 }
1114
1115 PP.Lex(Tok);
1116 if (Tok.isNot(tok::identifier)) {
1117 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1118 << (IsOptions ? "options" : "align");
1119 return;
1120 }
1121
1122 Sema::PragmaOptionsAlignKind Kind = Sema::POAK_Natural;
1123 const IdentifierInfo *II = Tok.getIdentifierInfo();
1124 if (II->isStr("native"))
1125 Kind = Sema::POAK_Native;
1126 else if (II->isStr("natural"))
1127 Kind = Sema::POAK_Natural;
1128 else if (II->isStr("packed"))
1129 Kind = Sema::POAK_Packed;
1130 else if (II->isStr("power"))
1131 Kind = Sema::POAK_Power;
1132 else if (II->isStr("mac68k"))
1133 Kind = Sema::POAK_Mac68k;
1134 else if (II->isStr("reset"))
1135 Kind = Sema::POAK_Reset;
1136 else {
1137 PP.Diag(Tok.getLocation(), diag::warn_pragma_align_invalid_option)
1138 << IsOptions;
1139 return;
1140 }
1141
1142 SourceLocation EndLoc = Tok.getLocation();
1143 PP.Lex(Tok);
1144 if (Tok.isNot(tok::eod)) {
1145 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1146 << (IsOptions ? "options" : "align");
1147 return;
1148 }
1149
1150 Token *Toks =
1151 (Token*) PP.getPreprocessorAllocator().Allocate(
1152 sizeof(Token) * 1, llvm::alignOf<Token>());
1153 new (Toks) Token();
1154 Toks[0].startToken();
1155 Toks[0].setKind(tok::annot_pragma_align);
1156 Toks[0].setLocation(FirstTok.getLocation());
1157 Toks[0].setAnnotationEndLoc(EndLoc);
1158 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1159 static_cast<uintptr_t>(Kind)));
1160 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1161 /*OwnsTokens=*/false);
1162 }
1163
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & AlignTok)1164 void PragmaAlignHandler::HandlePragma(Preprocessor &PP,
1165 PragmaIntroducerKind Introducer,
1166 Token &AlignTok) {
1167 ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false);
1168 }
1169
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & OptionsTok)1170 void PragmaOptionsHandler::HandlePragma(Preprocessor &PP,
1171 PragmaIntroducerKind Introducer,
1172 Token &OptionsTok) {
1173 ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true);
1174 }
1175
1176 // #pragma unused(identifier)
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & UnusedTok)1177 void PragmaUnusedHandler::HandlePragma(Preprocessor &PP,
1178 PragmaIntroducerKind Introducer,
1179 Token &UnusedTok) {
1180 // FIXME: Should we be expanding macros here? My guess is no.
1181 SourceLocation UnusedLoc = UnusedTok.getLocation();
1182
1183 // Lex the left '('.
1184 Token Tok;
1185 PP.Lex(Tok);
1186 if (Tok.isNot(tok::l_paren)) {
1187 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused";
1188 return;
1189 }
1190
1191 // Lex the declaration reference(s).
1192 SmallVector<Token, 5> Identifiers;
1193 SourceLocation RParenLoc;
1194 bool LexID = true;
1195
1196 while (true) {
1197 PP.Lex(Tok);
1198
1199 if (LexID) {
1200 if (Tok.is(tok::identifier)) {
1201 Identifiers.push_back(Tok);
1202 LexID = false;
1203 continue;
1204 }
1205
1206 // Illegal token!
1207 PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var);
1208 return;
1209 }
1210
1211 // We are execting a ')' or a ','.
1212 if (Tok.is(tok::comma)) {
1213 LexID = true;
1214 continue;
1215 }
1216
1217 if (Tok.is(tok::r_paren)) {
1218 RParenLoc = Tok.getLocation();
1219 break;
1220 }
1221
1222 // Illegal token!
1223 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_punc) << "unused";
1224 return;
1225 }
1226
1227 PP.Lex(Tok);
1228 if (Tok.isNot(tok::eod)) {
1229 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1230 "unused";
1231 return;
1232 }
1233
1234 // Verify that we have a location for the right parenthesis.
1235 assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'");
1236 assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments");
1237
1238 // For each identifier token, insert into the token stream a
1239 // annot_pragma_unused token followed by the identifier token.
1240 // This allows us to cache a "#pragma unused" that occurs inside an inline
1241 // C++ member function.
1242
1243 Token *Toks =
1244 (Token*) PP.getPreprocessorAllocator().Allocate(
1245 sizeof(Token) * 2 * Identifiers.size(), llvm::alignOf<Token>());
1246 for (unsigned i=0; i != Identifiers.size(); i++) {
1247 Token &pragmaUnusedTok = Toks[2*i], &idTok = Toks[2*i+1];
1248 pragmaUnusedTok.startToken();
1249 pragmaUnusedTok.setKind(tok::annot_pragma_unused);
1250 pragmaUnusedTok.setLocation(UnusedLoc);
1251 idTok = Identifiers[i];
1252 }
1253 PP.EnterTokenStream(Toks, 2*Identifiers.size(),
1254 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false);
1255 }
1256
1257 // #pragma weak identifier
1258 // #pragma weak identifier '=' identifier
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & WeakTok)1259 void PragmaWeakHandler::HandlePragma(Preprocessor &PP,
1260 PragmaIntroducerKind Introducer,
1261 Token &WeakTok) {
1262 SourceLocation WeakLoc = WeakTok.getLocation();
1263
1264 Token Tok;
1265 PP.Lex(Tok);
1266 if (Tok.isNot(tok::identifier)) {
1267 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak";
1268 return;
1269 }
1270
1271 Token WeakName = Tok;
1272 bool HasAlias = false;
1273 Token AliasName;
1274
1275 PP.Lex(Tok);
1276 if (Tok.is(tok::equal)) {
1277 HasAlias = true;
1278 PP.Lex(Tok);
1279 if (Tok.isNot(tok::identifier)) {
1280 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1281 << "weak";
1282 return;
1283 }
1284 AliasName = Tok;
1285 PP.Lex(Tok);
1286 }
1287
1288 if (Tok.isNot(tok::eod)) {
1289 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "weak";
1290 return;
1291 }
1292
1293 if (HasAlias) {
1294 Token *Toks =
1295 (Token*) PP.getPreprocessorAllocator().Allocate(
1296 sizeof(Token) * 3, llvm::alignOf<Token>());
1297 Token &pragmaUnusedTok = Toks[0];
1298 pragmaUnusedTok.startToken();
1299 pragmaUnusedTok.setKind(tok::annot_pragma_weakalias);
1300 pragmaUnusedTok.setLocation(WeakLoc);
1301 pragmaUnusedTok.setAnnotationEndLoc(AliasName.getLocation());
1302 Toks[1] = WeakName;
1303 Toks[2] = AliasName;
1304 PP.EnterTokenStream(Toks, 3,
1305 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false);
1306 } else {
1307 Token *Toks =
1308 (Token*) PP.getPreprocessorAllocator().Allocate(
1309 sizeof(Token) * 2, llvm::alignOf<Token>());
1310 Token &pragmaUnusedTok = Toks[0];
1311 pragmaUnusedTok.startToken();
1312 pragmaUnusedTok.setKind(tok::annot_pragma_weak);
1313 pragmaUnusedTok.setLocation(WeakLoc);
1314 pragmaUnusedTok.setAnnotationEndLoc(WeakLoc);
1315 Toks[1] = WeakName;
1316 PP.EnterTokenStream(Toks, 2,
1317 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false);
1318 }
1319 }
1320
1321 // #pragma redefine_extname identifier identifier
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & RedefToken)1322 void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP,
1323 PragmaIntroducerKind Introducer,
1324 Token &RedefToken) {
1325 SourceLocation RedefLoc = RedefToken.getLocation();
1326
1327 Token Tok;
1328 PP.Lex(Tok);
1329 if (Tok.isNot(tok::identifier)) {
1330 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
1331 "redefine_extname";
1332 return;
1333 }
1334
1335 Token RedefName = Tok;
1336 PP.Lex(Tok);
1337
1338 if (Tok.isNot(tok::identifier)) {
1339 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1340 << "redefine_extname";
1341 return;
1342 }
1343
1344 Token AliasName = Tok;
1345 PP.Lex(Tok);
1346
1347 if (Tok.isNot(tok::eod)) {
1348 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1349 "redefine_extname";
1350 return;
1351 }
1352
1353 Token *Toks =
1354 (Token*) PP.getPreprocessorAllocator().Allocate(
1355 sizeof(Token) * 3, llvm::alignOf<Token>());
1356 Token &pragmaRedefTok = Toks[0];
1357 pragmaRedefTok.startToken();
1358 pragmaRedefTok.setKind(tok::annot_pragma_redefine_extname);
1359 pragmaRedefTok.setLocation(RedefLoc);
1360 pragmaRedefTok.setAnnotationEndLoc(AliasName.getLocation());
1361 Toks[1] = RedefName;
1362 Toks[2] = AliasName;
1363 PP.EnterTokenStream(Toks, 3,
1364 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false);
1365 }
1366
1367
1368 void
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)1369 PragmaFPContractHandler::HandlePragma(Preprocessor &PP,
1370 PragmaIntroducerKind Introducer,
1371 Token &Tok) {
1372 tok::OnOffSwitch OOS;
1373 if (PP.LexOnOffSwitch(OOS))
1374 return;
1375
1376 Token *Toks =
1377 (Token*) PP.getPreprocessorAllocator().Allocate(
1378 sizeof(Token) * 1, llvm::alignOf<Token>());
1379 new (Toks) Token();
1380 Toks[0].startToken();
1381 Toks[0].setKind(tok::annot_pragma_fp_contract);
1382 Toks[0].setLocation(Tok.getLocation());
1383 Toks[0].setAnnotationEndLoc(Tok.getLocation());
1384 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1385 static_cast<uintptr_t>(OOS)));
1386 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1387 /*OwnsTokens=*/false);
1388 }
1389
1390 void
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)1391 PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP,
1392 PragmaIntroducerKind Introducer,
1393 Token &Tok) {
1394 PP.LexUnexpandedToken(Tok);
1395 if (Tok.isNot(tok::identifier)) {
1396 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
1397 "OPENCL";
1398 return;
1399 }
1400 IdentifierInfo *ename = Tok.getIdentifierInfo();
1401 SourceLocation NameLoc = Tok.getLocation();
1402
1403 PP.Lex(Tok);
1404 if (Tok.isNot(tok::colon)) {
1405 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << ename;
1406 return;
1407 }
1408
1409 PP.Lex(Tok);
1410 if (Tok.isNot(tok::identifier)) {
1411 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable);
1412 return;
1413 }
1414 IdentifierInfo *op = Tok.getIdentifierInfo();
1415
1416 unsigned state;
1417 if (op->isStr("enable")) {
1418 state = 1;
1419 } else if (op->isStr("disable")) {
1420 state = 0;
1421 } else {
1422 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable);
1423 return;
1424 }
1425 SourceLocation StateLoc = Tok.getLocation();
1426
1427 PP.Lex(Tok);
1428 if (Tok.isNot(tok::eod)) {
1429 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1430 "OPENCL EXTENSION";
1431 return;
1432 }
1433
1434 OpenCLExtData data(ename, state);
1435 Token *Toks =
1436 (Token*) PP.getPreprocessorAllocator().Allocate(
1437 sizeof(Token) * 1, llvm::alignOf<Token>());
1438 new (Toks) Token();
1439 Toks[0].startToken();
1440 Toks[0].setKind(tok::annot_pragma_opencl_extension);
1441 Toks[0].setLocation(NameLoc);
1442 Toks[0].setAnnotationValue(data.getOpaqueValue());
1443 Toks[0].setAnnotationEndLoc(StateLoc);
1444 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1445 /*OwnsTokens=*/false);
1446
1447 if (PP.getPPCallbacks())
1448 PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, ename,
1449 StateLoc, state);
1450 }
1451
1452 /// \brief Handle '#pragma omp ...' when OpenMP is disabled.
1453 ///
1454 void
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & FirstTok)1455 PragmaNoOpenMPHandler::HandlePragma(Preprocessor &PP,
1456 PragmaIntroducerKind Introducer,
1457 Token &FirstTok) {
1458 if (!PP.getDiagnostics().isIgnored(diag::warn_pragma_omp_ignored,
1459 FirstTok.getLocation())) {
1460 PP.Diag(FirstTok, diag::warn_pragma_omp_ignored);
1461 PP.getDiagnostics().setSeverity(diag::warn_pragma_omp_ignored,
1462 diag::Severity::Ignored, SourceLocation());
1463 }
1464 PP.DiscardUntilEndOfDirective();
1465 }
1466
1467 /// \brief Handle '#pragma omp ...' when OpenMP is enabled.
1468 ///
1469 void
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & FirstTok)1470 PragmaOpenMPHandler::HandlePragma(Preprocessor &PP,
1471 PragmaIntroducerKind Introducer,
1472 Token &FirstTok) {
1473 SmallVector<Token, 16> Pragma;
1474 Token Tok;
1475 Tok.startToken();
1476 Tok.setKind(tok::annot_pragma_openmp);
1477 Tok.setLocation(FirstTok.getLocation());
1478
1479 while (Tok.isNot(tok::eod)) {
1480 Pragma.push_back(Tok);
1481 PP.Lex(Tok);
1482 }
1483 SourceLocation EodLoc = Tok.getLocation();
1484 Tok.startToken();
1485 Tok.setKind(tok::annot_pragma_openmp_end);
1486 Tok.setLocation(EodLoc);
1487 Pragma.push_back(Tok);
1488
1489 Token *Toks = new Token[Pragma.size()];
1490 std::copy(Pragma.begin(), Pragma.end(), Toks);
1491 PP.EnterTokenStream(Toks, Pragma.size(),
1492 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/true);
1493 }
1494
1495 /// \brief Handle '#pragma pointers_to_members'
1496 // The grammar for this pragma is as follows:
1497 //
1498 // <inheritance model> ::= ('single' | 'multiple' | 'virtual') '_inheritance'
1499 //
1500 // #pragma pointers_to_members '(' 'best_case' ')'
1501 // #pragma pointers_to_members '(' 'full_generality' [',' inheritance-model] ')'
1502 // #pragma pointers_to_members '(' inheritance-model ')'
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)1503 void PragmaMSPointersToMembers::HandlePragma(Preprocessor &PP,
1504 PragmaIntroducerKind Introducer,
1505 Token &Tok) {
1506 SourceLocation PointersToMembersLoc = Tok.getLocation();
1507 PP.Lex(Tok);
1508 if (Tok.isNot(tok::l_paren)) {
1509 PP.Diag(PointersToMembersLoc, diag::warn_pragma_expected_lparen)
1510 << "pointers_to_members";
1511 return;
1512 }
1513 PP.Lex(Tok);
1514 const IdentifierInfo *Arg = Tok.getIdentifierInfo();
1515 if (!Arg) {
1516 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1517 << "pointers_to_members";
1518 return;
1519 }
1520 PP.Lex(Tok);
1521
1522 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod;
1523 if (Arg->isStr("best_case")) {
1524 RepresentationMethod = LangOptions::PPTMK_BestCase;
1525 } else {
1526 if (Arg->isStr("full_generality")) {
1527 if (Tok.is(tok::comma)) {
1528 PP.Lex(Tok);
1529
1530 Arg = Tok.getIdentifierInfo();
1531 if (!Arg) {
1532 PP.Diag(Tok.getLocation(),
1533 diag::err_pragma_pointers_to_members_unknown_kind)
1534 << Tok.getKind() << /*OnlyInheritanceModels*/ 0;
1535 return;
1536 }
1537 PP.Lex(Tok);
1538 } else if (Tok.is(tok::r_paren)) {
1539 // #pragma pointers_to_members(full_generality) implicitly specifies
1540 // virtual_inheritance.
1541 Arg = nullptr;
1542 RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance;
1543 } else {
1544 PP.Diag(Tok.getLocation(), diag::err_expected_punc)
1545 << "full_generality";
1546 return;
1547 }
1548 }
1549
1550 if (Arg) {
1551 if (Arg->isStr("single_inheritance")) {
1552 RepresentationMethod =
1553 LangOptions::PPTMK_FullGeneralitySingleInheritance;
1554 } else if (Arg->isStr("multiple_inheritance")) {
1555 RepresentationMethod =
1556 LangOptions::PPTMK_FullGeneralityMultipleInheritance;
1557 } else if (Arg->isStr("virtual_inheritance")) {
1558 RepresentationMethod =
1559 LangOptions::PPTMK_FullGeneralityVirtualInheritance;
1560 } else {
1561 PP.Diag(Tok.getLocation(),
1562 diag::err_pragma_pointers_to_members_unknown_kind)
1563 << Arg << /*HasPointerDeclaration*/ 1;
1564 return;
1565 }
1566 }
1567 }
1568
1569 if (Tok.isNot(tok::r_paren)) {
1570 PP.Diag(Tok.getLocation(), diag::err_expected_rparen_after)
1571 << (Arg ? Arg->getName() : "full_generality");
1572 return;
1573 }
1574
1575 SourceLocation EndLoc = Tok.getLocation();
1576 PP.Lex(Tok);
1577 if (Tok.isNot(tok::eod)) {
1578 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1579 << "pointers_to_members";
1580 return;
1581 }
1582
1583 Token AnnotTok;
1584 AnnotTok.startToken();
1585 AnnotTok.setKind(tok::annot_pragma_ms_pointers_to_members);
1586 AnnotTok.setLocation(PointersToMembersLoc);
1587 AnnotTok.setAnnotationEndLoc(EndLoc);
1588 AnnotTok.setAnnotationValue(
1589 reinterpret_cast<void *>(static_cast<uintptr_t>(RepresentationMethod)));
1590 PP.EnterToken(AnnotTok);
1591 }
1592
1593 /// \brief Handle '#pragma vtordisp'
1594 // The grammar for this pragma is as follows:
1595 //
1596 // <vtordisp-mode> ::= ('off' | 'on' | '0' | '1' | '2' )
1597 //
1598 // #pragma vtordisp '(' ['push' ','] vtordisp-mode ')'
1599 // #pragma vtordisp '(' 'pop' ')'
1600 // #pragma vtordisp '(' ')'
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)1601 void PragmaMSVtorDisp::HandlePragma(Preprocessor &PP,
1602 PragmaIntroducerKind Introducer,
1603 Token &Tok) {
1604 SourceLocation VtorDispLoc = Tok.getLocation();
1605 PP.Lex(Tok);
1606 if (Tok.isNot(tok::l_paren)) {
1607 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_lparen) << "vtordisp";
1608 return;
1609 }
1610 PP.Lex(Tok);
1611
1612 Sema::PragmaVtorDispKind Kind = Sema::PVDK_Set;
1613 const IdentifierInfo *II = Tok.getIdentifierInfo();
1614 if (II) {
1615 if (II->isStr("push")) {
1616 // #pragma vtordisp(push, mode)
1617 PP.Lex(Tok);
1618 if (Tok.isNot(tok::comma)) {
1619 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_punc) << "vtordisp";
1620 return;
1621 }
1622 PP.Lex(Tok);
1623 Kind = Sema::PVDK_Push;
1624 // not push, could be on/off
1625 } else if (II->isStr("pop")) {
1626 // #pragma vtordisp(pop)
1627 PP.Lex(Tok);
1628 Kind = Sema::PVDK_Pop;
1629 }
1630 // not push or pop, could be on/off
1631 } else {
1632 if (Tok.is(tok::r_paren)) {
1633 // #pragma vtordisp()
1634 Kind = Sema::PVDK_Reset;
1635 }
1636 }
1637
1638
1639 uint64_t Value = 0;
1640 if (Kind == Sema::PVDK_Push || Kind == Sema::PVDK_Set) {
1641 const IdentifierInfo *II = Tok.getIdentifierInfo();
1642 if (II && II->isStr("off")) {
1643 PP.Lex(Tok);
1644 Value = 0;
1645 } else if (II && II->isStr("on")) {
1646 PP.Lex(Tok);
1647 Value = 1;
1648 } else if (Tok.is(tok::numeric_constant) &&
1649 PP.parseSimpleIntegerLiteral(Tok, Value)) {
1650 if (Value > 2) {
1651 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_integer)
1652 << 0 << 2 << "vtordisp";
1653 return;
1654 }
1655 } else {
1656 PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action)
1657 << "vtordisp";
1658 return;
1659 }
1660 }
1661
1662 // Finish the pragma: ')' $
1663 if (Tok.isNot(tok::r_paren)) {
1664 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_rparen) << "vtordisp";
1665 return;
1666 }
1667 SourceLocation EndLoc = Tok.getLocation();
1668 PP.Lex(Tok);
1669 if (Tok.isNot(tok::eod)) {
1670 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1671 << "vtordisp";
1672 return;
1673 }
1674
1675 // Enter the annotation.
1676 Token AnnotTok;
1677 AnnotTok.startToken();
1678 AnnotTok.setKind(tok::annot_pragma_ms_vtordisp);
1679 AnnotTok.setLocation(VtorDispLoc);
1680 AnnotTok.setAnnotationEndLoc(EndLoc);
1681 AnnotTok.setAnnotationValue(reinterpret_cast<void *>(
1682 static_cast<uintptr_t>((Kind << 16) | (Value & 0xFFFF))));
1683 PP.EnterToken(AnnotTok);
1684 }
1685
1686 /// \brief Handle all MS pragmas. Simply forwards the tokens after inserting
1687 /// an annotation token.
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)1688 void PragmaMSPragma::HandlePragma(Preprocessor &PP,
1689 PragmaIntroducerKind Introducer,
1690 Token &Tok) {
1691 Token EoF, AnnotTok;
1692 EoF.startToken();
1693 EoF.setKind(tok::eof);
1694 AnnotTok.startToken();
1695 AnnotTok.setKind(tok::annot_pragma_ms_pragma);
1696 AnnotTok.setLocation(Tok.getLocation());
1697 AnnotTok.setAnnotationEndLoc(Tok.getLocation());
1698 SmallVector<Token, 8> TokenVector;
1699 // Suck up all of the tokens before the eod.
1700 for (; Tok.isNot(tok::eod); PP.Lex(Tok)) {
1701 TokenVector.push_back(Tok);
1702 AnnotTok.setAnnotationEndLoc(Tok.getLocation());
1703 }
1704 // Add a sentinal EoF token to the end of the list.
1705 TokenVector.push_back(EoF);
1706 // We must allocate this array with new because EnterTokenStream is going to
1707 // delete it later.
1708 Token *TokenArray = new Token[TokenVector.size()];
1709 std::copy(TokenVector.begin(), TokenVector.end(), TokenArray);
1710 auto Value = new (PP.getPreprocessorAllocator())
1711 std::pair<Token*, size_t>(std::make_pair(TokenArray, TokenVector.size()));
1712 AnnotTok.setAnnotationValue(Value);
1713 PP.EnterToken(AnnotTok);
1714 }
1715
1716 /// \brief Handle the Microsoft \#pragma detect_mismatch extension.
1717 ///
1718 /// The syntax is:
1719 /// \code
1720 /// #pragma detect_mismatch("name", "value")
1721 /// \endcode
1722 /// Where 'name' and 'value' are quoted strings. The values are embedded in
1723 /// the object file and passed along to the linker. If the linker detects a
1724 /// mismatch in the object file's values for the given name, a LNK2038 error
1725 /// is emitted. See MSDN for more details.
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)1726 void PragmaDetectMismatchHandler::HandlePragma(Preprocessor &PP,
1727 PragmaIntroducerKind Introducer,
1728 Token &Tok) {
1729 SourceLocation CommentLoc = Tok.getLocation();
1730 PP.Lex(Tok);
1731 if (Tok.isNot(tok::l_paren)) {
1732 PP.Diag(CommentLoc, diag::err_expected) << tok::l_paren;
1733 return;
1734 }
1735
1736 // Read the name to embed, which must be a string literal.
1737 std::string NameString;
1738 if (!PP.LexStringLiteral(Tok, NameString,
1739 "pragma detect_mismatch",
1740 /*MacroExpansion=*/true))
1741 return;
1742
1743 // Read the comma followed by a second string literal.
1744 std::string ValueString;
1745 if (Tok.isNot(tok::comma)) {
1746 PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
1747 return;
1748 }
1749
1750 if (!PP.LexStringLiteral(Tok, ValueString, "pragma detect_mismatch",
1751 /*MacroExpansion=*/true))
1752 return;
1753
1754 if (Tok.isNot(tok::r_paren)) {
1755 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1756 return;
1757 }
1758 PP.Lex(Tok); // Eat the r_paren.
1759
1760 if (Tok.isNot(tok::eod)) {
1761 PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
1762 return;
1763 }
1764
1765 // If the pragma is lexically sound, notify any interested PPCallbacks.
1766 if (PP.getPPCallbacks())
1767 PP.getPPCallbacks()->PragmaDetectMismatch(CommentLoc, NameString,
1768 ValueString);
1769
1770 Actions.ActOnPragmaDetectMismatch(NameString, ValueString);
1771 }
1772
1773 /// \brief Handle the microsoft \#pragma comment extension.
1774 ///
1775 /// The syntax is:
1776 /// \code
1777 /// #pragma comment(linker, "foo")
1778 /// \endcode
1779 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
1780 /// "foo" is a string, which is fully macro expanded, and permits string
1781 /// concatenation, embedded escape characters etc. See MSDN for more details.
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)1782 void PragmaCommentHandler::HandlePragma(Preprocessor &PP,
1783 PragmaIntroducerKind Introducer,
1784 Token &Tok) {
1785 SourceLocation CommentLoc = Tok.getLocation();
1786 PP.Lex(Tok);
1787 if (Tok.isNot(tok::l_paren)) {
1788 PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
1789 return;
1790 }
1791
1792 // Read the identifier.
1793 PP.Lex(Tok);
1794 if (Tok.isNot(tok::identifier)) {
1795 PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
1796 return;
1797 }
1798
1799 // Verify that this is one of the 5 whitelisted options.
1800 IdentifierInfo *II = Tok.getIdentifierInfo();
1801 Sema::PragmaMSCommentKind Kind =
1802 llvm::StringSwitch<Sema::PragmaMSCommentKind>(II->getName())
1803 .Case("linker", Sema::PCK_Linker)
1804 .Case("lib", Sema::PCK_Lib)
1805 .Case("compiler", Sema::PCK_Compiler)
1806 .Case("exestr", Sema::PCK_ExeStr)
1807 .Case("user", Sema::PCK_User)
1808 .Default(Sema::PCK_Unknown);
1809 if (Kind == Sema::PCK_Unknown) {
1810 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
1811 return;
1812 }
1813
1814 // On PS4, issue a warning about any pragma comments other than
1815 // #pragma comment lib.
1816 if (PP.getTargetInfo().getTriple().isPS4() && Kind != Sema::PCK_Lib) {
1817 PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
1818 << II->getName();
1819 return;
1820 }
1821
1822 // Read the optional string if present.
1823 PP.Lex(Tok);
1824 std::string ArgumentString;
1825 if (Tok.is(tok::comma) && !PP.LexStringLiteral(Tok, ArgumentString,
1826 "pragma comment",
1827 /*MacroExpansion=*/true))
1828 return;
1829
1830 // FIXME: warn that 'exestr' is deprecated.
1831 // FIXME: If the kind is "compiler" warn if the string is present (it is
1832 // ignored).
1833 // The MSDN docs say that "lib" and "linker" require a string and have a short
1834 // whitelist of linker options they support, but in practice MSVC doesn't
1835 // issue a diagnostic. Therefore neither does clang.
1836
1837 if (Tok.isNot(tok::r_paren)) {
1838 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
1839 return;
1840 }
1841 PP.Lex(Tok); // eat the r_paren.
1842
1843 if (Tok.isNot(tok::eod)) {
1844 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
1845 return;
1846 }
1847
1848 // If the pragma is lexically sound, notify any interested PPCallbacks.
1849 if (PP.getPPCallbacks())
1850 PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString);
1851
1852 Actions.ActOnPragmaMSComment(Kind, ArgumentString);
1853 }
1854
1855 // #pragma clang optimize off
1856 // #pragma clang optimize on
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & FirstToken)1857 void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP,
1858 PragmaIntroducerKind Introducer,
1859 Token &FirstToken) {
1860 Token Tok;
1861 PP.Lex(Tok);
1862 if (Tok.is(tok::eod)) {
1863 PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
1864 << "clang optimize" << /*Expected=*/true << "'on' or 'off'";
1865 return;
1866 }
1867 if (Tok.isNot(tok::identifier)) {
1868 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
1869 << PP.getSpelling(Tok);
1870 return;
1871 }
1872 const IdentifierInfo *II = Tok.getIdentifierInfo();
1873 // The only accepted values are 'on' or 'off'.
1874 bool IsOn = false;
1875 if (II->isStr("on")) {
1876 IsOn = true;
1877 } else if (!II->isStr("off")) {
1878 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
1879 << PP.getSpelling(Tok);
1880 return;
1881 }
1882 PP.Lex(Tok);
1883
1884 if (Tok.isNot(tok::eod)) {
1885 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument)
1886 << PP.getSpelling(Tok);
1887 return;
1888 }
1889
1890 Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());
1891 }
1892
1893 /// \brief Parses loop or unroll pragma hint value and fills in Info.
ParseLoopHintValue(Preprocessor & PP,Token & Tok,Token PragmaName,Token Option,bool ValueInParens,PragmaLoopHintInfo & Info)1894 static bool ParseLoopHintValue(Preprocessor &PP, Token &Tok, Token PragmaName,
1895 Token Option, bool ValueInParens,
1896 PragmaLoopHintInfo &Info) {
1897 SmallVector<Token, 1> ValueList;
1898 int OpenParens = ValueInParens ? 1 : 0;
1899 // Read constant expression.
1900 while (Tok.isNot(tok::eod)) {
1901 if (Tok.is(tok::l_paren))
1902 OpenParens++;
1903 else if (Tok.is(tok::r_paren)) {
1904 OpenParens--;
1905 if (OpenParens == 0 && ValueInParens)
1906 break;
1907 }
1908
1909 ValueList.push_back(Tok);
1910 PP.Lex(Tok);
1911 }
1912
1913 if (ValueInParens) {
1914 // Read ')'
1915 if (Tok.isNot(tok::r_paren)) {
1916 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1917 return true;
1918 }
1919 PP.Lex(Tok);
1920 }
1921
1922 Token EOFTok;
1923 EOFTok.startToken();
1924 EOFTok.setKind(tok::eof);
1925 EOFTok.setLocation(Tok.getLocation());
1926 ValueList.push_back(EOFTok); // Terminates expression for parsing.
1927
1928 Token *TokenArray = (Token *)PP.getPreprocessorAllocator().Allocate(
1929 ValueList.size() * sizeof(Token), llvm::alignOf<Token>());
1930 std::copy(ValueList.begin(), ValueList.end(), TokenArray);
1931 Info.Toks = TokenArray;
1932 Info.TokSize = ValueList.size();
1933
1934 Info.PragmaName = PragmaName;
1935 Info.Option = Option;
1936 return false;
1937 }
1938
1939 /// \brief Handle the \#pragma clang loop directive.
1940 /// #pragma clang 'loop' loop-hints
1941 ///
1942 /// loop-hints:
1943 /// loop-hint loop-hints[opt]
1944 ///
1945 /// loop-hint:
1946 /// 'vectorize' '(' loop-hint-keyword ')'
1947 /// 'interleave' '(' loop-hint-keyword ')'
1948 /// 'unroll' '(' unroll-hint-keyword ')'
1949 /// 'vectorize_width' '(' loop-hint-value ')'
1950 /// 'interleave_count' '(' loop-hint-value ')'
1951 /// 'unroll_count' '(' loop-hint-value ')'
1952 ///
1953 /// loop-hint-keyword:
1954 /// 'enable'
1955 /// 'disable'
1956 ///
1957 /// unroll-hint-keyword:
1958 /// 'full'
1959 /// 'disable'
1960 ///
1961 /// loop-hint-value:
1962 /// constant-expression
1963 ///
1964 /// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to
1965 /// try vectorizing the instructions of the loop it precedes. Specifying
1966 /// interleave(enable) or interleave_count(_value_) instructs llvm to try
1967 /// interleaving multiple iterations of the loop it precedes. The width of the
1968 /// vector instructions is specified by vectorize_width() and the number of
1969 /// interleaved loop iterations is specified by interleave_count(). Specifying a
1970 /// value of 1 effectively disables vectorization/interleaving, even if it is
1971 /// possible and profitable, and 0 is invalid. The loop vectorizer currently
1972 /// only works on inner loops.
1973 ///
1974 /// The unroll and unroll_count directives control the concatenation
1975 /// unroller. Specifying unroll(full) instructs llvm to try to
1976 /// unroll the loop completely, and unroll(disable) disables unrolling
1977 /// for the loop. Specifying unroll_count(_value_) instructs llvm to
1978 /// try to unroll the loop the number of times indicated by the value.
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)1979 void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP,
1980 PragmaIntroducerKind Introducer,
1981 Token &Tok) {
1982 // Incoming token is "loop" from "#pragma clang loop".
1983 Token PragmaName = Tok;
1984 SmallVector<Token, 1> TokenList;
1985
1986 // Lex the optimization option and verify it is an identifier.
1987 PP.Lex(Tok);
1988 if (Tok.isNot(tok::identifier)) {
1989 PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
1990 << /*MissingOption=*/true << "";
1991 return;
1992 }
1993
1994 while (Tok.is(tok::identifier)) {
1995 Token Option = Tok;
1996 IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
1997
1998 bool OptionValid = llvm::StringSwitch<bool>(OptionInfo->getName())
1999 .Case("vectorize", true)
2000 .Case("interleave", true)
2001 .Case("unroll", true)
2002 .Case("vectorize_width", true)
2003 .Case("interleave_count", true)
2004 .Case("unroll_count", true)
2005 .Default(false);
2006 if (!OptionValid) {
2007 PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
2008 << /*MissingOption=*/false << OptionInfo;
2009 return;
2010 }
2011 PP.Lex(Tok);
2012
2013 // Read '('
2014 if (Tok.isNot(tok::l_paren)) {
2015 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
2016 return;
2017 }
2018 PP.Lex(Tok);
2019
2020 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2021 if (ParseLoopHintValue(PP, Tok, PragmaName, Option, /*ValueInParens=*/true,
2022 *Info))
2023 return;
2024
2025 // Generate the loop hint token.
2026 Token LoopHintTok;
2027 LoopHintTok.startToken();
2028 LoopHintTok.setKind(tok::annot_pragma_loop_hint);
2029 LoopHintTok.setLocation(PragmaName.getLocation());
2030 LoopHintTok.setAnnotationEndLoc(PragmaName.getLocation());
2031 LoopHintTok.setAnnotationValue(static_cast<void *>(Info));
2032 TokenList.push_back(LoopHintTok);
2033 }
2034
2035 if (Tok.isNot(tok::eod)) {
2036 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2037 << "clang loop";
2038 return;
2039 }
2040
2041 Token *TokenArray = new Token[TokenList.size()];
2042 std::copy(TokenList.begin(), TokenList.end(), TokenArray);
2043
2044 PP.EnterTokenStream(TokenArray, TokenList.size(),
2045 /*DisableMacroExpansion=*/false,
2046 /*OwnsTokens=*/true);
2047 }
2048
2049 /// \brief Handle the loop unroll optimization pragmas.
2050 /// #pragma unroll
2051 /// #pragma unroll unroll-hint-value
2052 /// #pragma unroll '(' unroll-hint-value ')'
2053 /// #pragma nounroll
2054 ///
2055 /// unroll-hint-value:
2056 /// constant-expression
2057 ///
2058 /// Loop unrolling hints can be specified with '#pragma unroll' or
2059 /// '#pragma nounroll'. '#pragma unroll' can take a numeric argument optionally
2060 /// contained in parentheses. With no argument the directive instructs llvm to
2061 /// try to unroll the loop completely. A positive integer argument can be
2062 /// specified to indicate the number of times the loop should be unrolled. To
2063 /// maximize compatibility with other compilers the unroll count argument can be
2064 /// specified with or without parentheses. Specifying, '#pragma nounroll'
2065 /// disables unrolling of the loop.
HandlePragma(Preprocessor & PP,PragmaIntroducerKind Introducer,Token & Tok)2066 void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP,
2067 PragmaIntroducerKind Introducer,
2068 Token &Tok) {
2069 // Incoming token is "unroll" for "#pragma unroll", or "nounroll" for
2070 // "#pragma nounroll".
2071 Token PragmaName = Tok;
2072 PP.Lex(Tok);
2073 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2074 if (Tok.is(tok::eod)) {
2075 // nounroll or unroll pragma without an argument.
2076 Info->PragmaName = PragmaName;
2077 Info->Option.startToken();
2078 } else if (PragmaName.getIdentifierInfo()->getName() == "nounroll") {
2079 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2080 << "nounroll";
2081 return;
2082 } else {
2083 // Unroll pragma with an argument: "#pragma unroll N" or
2084 // "#pragma unroll(N)".
2085 // Read '(' if it exists.
2086 bool ValueInParens = Tok.is(tok::l_paren);
2087 if (ValueInParens)
2088 PP.Lex(Tok);
2089
2090 Token Option;
2091 Option.startToken();
2092 if (ParseLoopHintValue(PP, Tok, PragmaName, Option, ValueInParens, *Info))
2093 return;
2094
2095 // In CUDA, the argument to '#pragma unroll' should not be contained in
2096 // parentheses.
2097 if (PP.getLangOpts().CUDA && ValueInParens)
2098 PP.Diag(Info->Toks[0].getLocation(),
2099 diag::warn_pragma_unroll_cuda_value_in_parens);
2100
2101 if (Tok.isNot(tok::eod)) {
2102 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2103 << "unroll";
2104 return;
2105 }
2106 }
2107
2108 // Generate the hint token.
2109 Token *TokenArray = new Token[1];
2110 TokenArray[0].startToken();
2111 TokenArray[0].setKind(tok::annot_pragma_loop_hint);
2112 TokenArray[0].setLocation(PragmaName.getLocation());
2113 TokenArray[0].setAnnotationEndLoc(PragmaName.getLocation());
2114 TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
2115 PP.EnterTokenStream(TokenArray, 1, /*DisableMacroExpansion=*/false,
2116 /*OwnsTokens=*/true);
2117 }
2118