ParsePragma.cpp 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281
  1. //===--- ParsePragma.cpp - Language specific pragma parsing ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the language specific #pragma handlers.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/Basic/PragmaKinds.h"
  14. #include "clang/Basic/TargetInfo.h"
  15. #include "clang/Lex/Preprocessor.h"
  16. #include "clang/Parse/LoopHint.h"
  17. #include "clang/Parse/ParseDiagnostic.h"
  18. #include "clang/Parse/Parser.h"
  19. #include "clang/Parse/RAIIObjectsForParser.h"
  20. #include "clang/Sema/Scope.h"
  21. #include "llvm/ADT/StringSwitch.h"
  22. using namespace clang;
  23. namespace {
  24. struct PragmaAlignHandler : public PragmaHandler {
  25. explicit PragmaAlignHandler() : PragmaHandler("align") {}
  26. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  27. Token &FirstToken) override;
  28. };
  29. struct PragmaGCCVisibilityHandler : public PragmaHandler {
  30. explicit PragmaGCCVisibilityHandler() : PragmaHandler("visibility") {}
  31. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  32. Token &FirstToken) override;
  33. };
  34. struct PragmaOptionsHandler : public PragmaHandler {
  35. explicit PragmaOptionsHandler() : PragmaHandler("options") {}
  36. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  37. Token &FirstToken) override;
  38. };
  39. struct PragmaPackHandler : public PragmaHandler {
  40. explicit PragmaPackHandler() : PragmaHandler("pack") {}
  41. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  42. Token &FirstToken) override;
  43. };
  44. struct PragmaClangSectionHandler : public PragmaHandler {
  45. explicit PragmaClangSectionHandler(Sema &S)
  46. : PragmaHandler("section"), Actions(S) {}
  47. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  48. Token &FirstToken) override;
  49. private:
  50. Sema &Actions;
  51. };
  52. struct PragmaMSStructHandler : public PragmaHandler {
  53. explicit PragmaMSStructHandler() : PragmaHandler("ms_struct") {}
  54. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  55. Token &FirstToken) override;
  56. };
  57. struct PragmaUnusedHandler : public PragmaHandler {
  58. PragmaUnusedHandler() : PragmaHandler("unused") {}
  59. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  60. Token &FirstToken) override;
  61. };
  62. struct PragmaWeakHandler : public PragmaHandler {
  63. explicit PragmaWeakHandler() : PragmaHandler("weak") {}
  64. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  65. Token &FirstToken) override;
  66. };
  67. struct PragmaRedefineExtnameHandler : public PragmaHandler {
  68. explicit PragmaRedefineExtnameHandler() : PragmaHandler("redefine_extname") {}
  69. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  70. Token &FirstToken) override;
  71. };
  72. struct PragmaOpenCLExtensionHandler : public PragmaHandler {
  73. PragmaOpenCLExtensionHandler() : PragmaHandler("EXTENSION") {}
  74. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  75. Token &FirstToken) override;
  76. };
  77. struct PragmaFPContractHandler : public PragmaHandler {
  78. PragmaFPContractHandler() : PragmaHandler("FP_CONTRACT") {}
  79. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  80. Token &FirstToken) override;
  81. };
  82. // Pragma STDC implementations.
  83. /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
  84. struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
  85. PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
  86. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  87. Token &Tok) override {
  88. tok::OnOffSwitch OOS;
  89. if (PP.LexOnOffSwitch(OOS))
  90. return;
  91. if (OOS == tok::OOS_ON) {
  92. PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
  93. }
  94. MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
  95. 1);
  96. Toks[0].startToken();
  97. Toks[0].setKind(tok::annot_pragma_fenv_access);
  98. Toks[0].setLocation(Tok.getLocation());
  99. Toks[0].setAnnotationEndLoc(Tok.getLocation());
  100. Toks[0].setAnnotationValue(reinterpret_cast<void*>(
  101. static_cast<uintptr_t>(OOS)));
  102. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  103. /*IsReinject=*/false);
  104. }
  105. };
  106. /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
  107. struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
  108. PragmaSTDC_CX_LIMITED_RANGEHandler() : PragmaHandler("CX_LIMITED_RANGE") {}
  109. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  110. Token &Tok) override {
  111. tok::OnOffSwitch OOS;
  112. PP.LexOnOffSwitch(OOS);
  113. }
  114. };
  115. /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
  116. struct PragmaSTDC_UnknownHandler : public PragmaHandler {
  117. PragmaSTDC_UnknownHandler() = default;
  118. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  119. Token &UnknownTok) override {
  120. // C99 6.10.6p2, unknown forms are not allowed.
  121. PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
  122. }
  123. };
  124. struct PragmaFPHandler : public PragmaHandler {
  125. PragmaFPHandler() : PragmaHandler("fp") {}
  126. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  127. Token &FirstToken) override;
  128. };
  129. struct PragmaNoOpenMPHandler : public PragmaHandler {
  130. PragmaNoOpenMPHandler() : PragmaHandler("omp") { }
  131. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  132. Token &FirstToken) override;
  133. };
  134. struct PragmaOpenMPHandler : public PragmaHandler {
  135. PragmaOpenMPHandler() : PragmaHandler("omp") { }
  136. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  137. Token &FirstToken) override;
  138. };
  139. /// PragmaCommentHandler - "\#pragma comment ...".
  140. struct PragmaCommentHandler : public PragmaHandler {
  141. PragmaCommentHandler(Sema &Actions)
  142. : PragmaHandler("comment"), Actions(Actions) {}
  143. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  144. Token &FirstToken) override;
  145. private:
  146. Sema &Actions;
  147. };
  148. struct PragmaDetectMismatchHandler : public PragmaHandler {
  149. PragmaDetectMismatchHandler(Sema &Actions)
  150. : PragmaHandler("detect_mismatch"), Actions(Actions) {}
  151. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  152. Token &FirstToken) override;
  153. private:
  154. Sema &Actions;
  155. };
  156. struct PragmaMSPointersToMembers : public PragmaHandler {
  157. explicit PragmaMSPointersToMembers() : PragmaHandler("pointers_to_members") {}
  158. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  159. Token &FirstToken) override;
  160. };
  161. struct PragmaMSVtorDisp : public PragmaHandler {
  162. explicit PragmaMSVtorDisp() : PragmaHandler("vtordisp") {}
  163. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  164. Token &FirstToken) override;
  165. };
  166. struct PragmaMSPragma : public PragmaHandler {
  167. explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {}
  168. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  169. Token &FirstToken) override;
  170. };
  171. /// PragmaOptimizeHandler - "\#pragma clang optimize on/off".
  172. struct PragmaOptimizeHandler : public PragmaHandler {
  173. PragmaOptimizeHandler(Sema &S)
  174. : PragmaHandler("optimize"), Actions(S) {}
  175. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  176. Token &FirstToken) override;
  177. private:
  178. Sema &Actions;
  179. };
  180. struct PragmaLoopHintHandler : public PragmaHandler {
  181. PragmaLoopHintHandler() : PragmaHandler("loop") {}
  182. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  183. Token &FirstToken) override;
  184. };
  185. struct PragmaUnrollHintHandler : public PragmaHandler {
  186. PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {}
  187. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  188. Token &FirstToken) override;
  189. };
  190. struct PragmaMSRuntimeChecksHandler : public EmptyPragmaHandler {
  191. PragmaMSRuntimeChecksHandler() : EmptyPragmaHandler("runtime_checks") {}
  192. };
  193. struct PragmaMSIntrinsicHandler : public PragmaHandler {
  194. PragmaMSIntrinsicHandler() : PragmaHandler("intrinsic") {}
  195. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  196. Token &FirstToken) override;
  197. };
  198. struct PragmaMSOptimizeHandler : public PragmaHandler {
  199. PragmaMSOptimizeHandler() : PragmaHandler("optimize") {}
  200. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  201. Token &FirstToken) override;
  202. };
  203. struct PragmaForceCUDAHostDeviceHandler : public PragmaHandler {
  204. PragmaForceCUDAHostDeviceHandler(Sema &Actions)
  205. : PragmaHandler("force_cuda_host_device"), Actions(Actions) {}
  206. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  207. Token &FirstToken) override;
  208. private:
  209. Sema &Actions;
  210. };
  211. /// PragmaAttributeHandler - "\#pragma clang attribute ...".
  212. struct PragmaAttributeHandler : public PragmaHandler {
  213. PragmaAttributeHandler(AttributeFactory &AttrFactory)
  214. : PragmaHandler("attribute"), AttributesForPragmaAttribute(AttrFactory) {}
  215. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  216. Token &FirstToken) override;
  217. /// A pool of attributes that were parsed in \#pragma clang attribute.
  218. ParsedAttributes AttributesForPragmaAttribute;
  219. };
  220. } // end namespace
  221. void Parser::initializePragmaHandlers() {
  222. AlignHandler = std::make_unique<PragmaAlignHandler>();
  223. PP.AddPragmaHandler(AlignHandler.get());
  224. GCCVisibilityHandler = std::make_unique<PragmaGCCVisibilityHandler>();
  225. PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
  226. OptionsHandler = std::make_unique<PragmaOptionsHandler>();
  227. PP.AddPragmaHandler(OptionsHandler.get());
  228. PackHandler = std::make_unique<PragmaPackHandler>();
  229. PP.AddPragmaHandler(PackHandler.get());
  230. MSStructHandler = std::make_unique<PragmaMSStructHandler>();
  231. PP.AddPragmaHandler(MSStructHandler.get());
  232. UnusedHandler = std::make_unique<PragmaUnusedHandler>();
  233. PP.AddPragmaHandler(UnusedHandler.get());
  234. WeakHandler = std::make_unique<PragmaWeakHandler>();
  235. PP.AddPragmaHandler(WeakHandler.get());
  236. RedefineExtnameHandler = std::make_unique<PragmaRedefineExtnameHandler>();
  237. PP.AddPragmaHandler(RedefineExtnameHandler.get());
  238. FPContractHandler = std::make_unique<PragmaFPContractHandler>();
  239. PP.AddPragmaHandler("STDC", FPContractHandler.get());
  240. STDCFENVHandler = std::make_unique<PragmaSTDC_FENV_ACCESSHandler>();
  241. PP.AddPragmaHandler("STDC", STDCFENVHandler.get());
  242. STDCCXLIMITHandler = std::make_unique<PragmaSTDC_CX_LIMITED_RANGEHandler>();
  243. PP.AddPragmaHandler("STDC", STDCCXLIMITHandler.get());
  244. STDCUnknownHandler = std::make_unique<PragmaSTDC_UnknownHandler>();
  245. PP.AddPragmaHandler("STDC", STDCUnknownHandler.get());
  246. PCSectionHandler = std::make_unique<PragmaClangSectionHandler>(Actions);
  247. PP.AddPragmaHandler("clang", PCSectionHandler.get());
  248. if (getLangOpts().OpenCL) {
  249. OpenCLExtensionHandler = std::make_unique<PragmaOpenCLExtensionHandler>();
  250. PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
  251. PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
  252. }
  253. if (getLangOpts().OpenMP)
  254. OpenMPHandler = std::make_unique<PragmaOpenMPHandler>();
  255. else
  256. OpenMPHandler = std::make_unique<PragmaNoOpenMPHandler>();
  257. PP.AddPragmaHandler(OpenMPHandler.get());
  258. if (getLangOpts().MicrosoftExt ||
  259. getTargetInfo().getTriple().isOSBinFormatELF()) {
  260. MSCommentHandler = std::make_unique<PragmaCommentHandler>(Actions);
  261. PP.AddPragmaHandler(MSCommentHandler.get());
  262. }
  263. if (getLangOpts().MicrosoftExt) {
  264. MSDetectMismatchHandler =
  265. std::make_unique<PragmaDetectMismatchHandler>(Actions);
  266. PP.AddPragmaHandler(MSDetectMismatchHandler.get());
  267. MSPointersToMembers = std::make_unique<PragmaMSPointersToMembers>();
  268. PP.AddPragmaHandler(MSPointersToMembers.get());
  269. MSVtorDisp = std::make_unique<PragmaMSVtorDisp>();
  270. PP.AddPragmaHandler(MSVtorDisp.get());
  271. MSInitSeg = std::make_unique<PragmaMSPragma>("init_seg");
  272. PP.AddPragmaHandler(MSInitSeg.get());
  273. MSDataSeg = std::make_unique<PragmaMSPragma>("data_seg");
  274. PP.AddPragmaHandler(MSDataSeg.get());
  275. MSBSSSeg = std::make_unique<PragmaMSPragma>("bss_seg");
  276. PP.AddPragmaHandler(MSBSSSeg.get());
  277. MSConstSeg = std::make_unique<PragmaMSPragma>("const_seg");
  278. PP.AddPragmaHandler(MSConstSeg.get());
  279. MSCodeSeg = std::make_unique<PragmaMSPragma>("code_seg");
  280. PP.AddPragmaHandler(MSCodeSeg.get());
  281. MSSection = std::make_unique<PragmaMSPragma>("section");
  282. PP.AddPragmaHandler(MSSection.get());
  283. MSRuntimeChecks = std::make_unique<PragmaMSRuntimeChecksHandler>();
  284. PP.AddPragmaHandler(MSRuntimeChecks.get());
  285. MSIntrinsic = std::make_unique<PragmaMSIntrinsicHandler>();
  286. PP.AddPragmaHandler(MSIntrinsic.get());
  287. MSOptimize = std::make_unique<PragmaMSOptimizeHandler>();
  288. PP.AddPragmaHandler(MSOptimize.get());
  289. }
  290. if (getLangOpts().CUDA) {
  291. CUDAForceHostDeviceHandler =
  292. std::make_unique<PragmaForceCUDAHostDeviceHandler>(Actions);
  293. PP.AddPragmaHandler("clang", CUDAForceHostDeviceHandler.get());
  294. }
  295. OptimizeHandler = std::make_unique<PragmaOptimizeHandler>(Actions);
  296. PP.AddPragmaHandler("clang", OptimizeHandler.get());
  297. LoopHintHandler = std::make_unique<PragmaLoopHintHandler>();
  298. PP.AddPragmaHandler("clang", LoopHintHandler.get());
  299. UnrollHintHandler = std::make_unique<PragmaUnrollHintHandler>("unroll");
  300. PP.AddPragmaHandler(UnrollHintHandler.get());
  301. NoUnrollHintHandler = std::make_unique<PragmaUnrollHintHandler>("nounroll");
  302. PP.AddPragmaHandler(NoUnrollHintHandler.get());
  303. UnrollAndJamHintHandler =
  304. std::make_unique<PragmaUnrollHintHandler>("unroll_and_jam");
  305. PP.AddPragmaHandler(UnrollAndJamHintHandler.get());
  306. NoUnrollAndJamHintHandler =
  307. std::make_unique<PragmaUnrollHintHandler>("nounroll_and_jam");
  308. PP.AddPragmaHandler(NoUnrollAndJamHintHandler.get());
  309. FPHandler = std::make_unique<PragmaFPHandler>();
  310. PP.AddPragmaHandler("clang", FPHandler.get());
  311. AttributePragmaHandler =
  312. std::make_unique<PragmaAttributeHandler>(AttrFactory);
  313. PP.AddPragmaHandler("clang", AttributePragmaHandler.get());
  314. }
  315. void Parser::resetPragmaHandlers() {
  316. // Remove the pragma handlers we installed.
  317. PP.RemovePragmaHandler(AlignHandler.get());
  318. AlignHandler.reset();
  319. PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
  320. GCCVisibilityHandler.reset();
  321. PP.RemovePragmaHandler(OptionsHandler.get());
  322. OptionsHandler.reset();
  323. PP.RemovePragmaHandler(PackHandler.get());
  324. PackHandler.reset();
  325. PP.RemovePragmaHandler(MSStructHandler.get());
  326. MSStructHandler.reset();
  327. PP.RemovePragmaHandler(UnusedHandler.get());
  328. UnusedHandler.reset();
  329. PP.RemovePragmaHandler(WeakHandler.get());
  330. WeakHandler.reset();
  331. PP.RemovePragmaHandler(RedefineExtnameHandler.get());
  332. RedefineExtnameHandler.reset();
  333. if (getLangOpts().OpenCL) {
  334. PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
  335. OpenCLExtensionHandler.reset();
  336. PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
  337. }
  338. PP.RemovePragmaHandler(OpenMPHandler.get());
  339. OpenMPHandler.reset();
  340. if (getLangOpts().MicrosoftExt ||
  341. getTargetInfo().getTriple().isOSBinFormatELF()) {
  342. PP.RemovePragmaHandler(MSCommentHandler.get());
  343. MSCommentHandler.reset();
  344. }
  345. PP.RemovePragmaHandler("clang", PCSectionHandler.get());
  346. PCSectionHandler.reset();
  347. if (getLangOpts().MicrosoftExt) {
  348. PP.RemovePragmaHandler(MSDetectMismatchHandler.get());
  349. MSDetectMismatchHandler.reset();
  350. PP.RemovePragmaHandler(MSPointersToMembers.get());
  351. MSPointersToMembers.reset();
  352. PP.RemovePragmaHandler(MSVtorDisp.get());
  353. MSVtorDisp.reset();
  354. PP.RemovePragmaHandler(MSInitSeg.get());
  355. MSInitSeg.reset();
  356. PP.RemovePragmaHandler(MSDataSeg.get());
  357. MSDataSeg.reset();
  358. PP.RemovePragmaHandler(MSBSSSeg.get());
  359. MSBSSSeg.reset();
  360. PP.RemovePragmaHandler(MSConstSeg.get());
  361. MSConstSeg.reset();
  362. PP.RemovePragmaHandler(MSCodeSeg.get());
  363. MSCodeSeg.reset();
  364. PP.RemovePragmaHandler(MSSection.get());
  365. MSSection.reset();
  366. PP.RemovePragmaHandler(MSRuntimeChecks.get());
  367. MSRuntimeChecks.reset();
  368. PP.RemovePragmaHandler(MSIntrinsic.get());
  369. MSIntrinsic.reset();
  370. PP.RemovePragmaHandler(MSOptimize.get());
  371. MSOptimize.reset();
  372. }
  373. if (getLangOpts().CUDA) {
  374. PP.RemovePragmaHandler("clang", CUDAForceHostDeviceHandler.get());
  375. CUDAForceHostDeviceHandler.reset();
  376. }
  377. PP.RemovePragmaHandler("STDC", FPContractHandler.get());
  378. FPContractHandler.reset();
  379. PP.RemovePragmaHandler("STDC", STDCFENVHandler.get());
  380. STDCFENVHandler.reset();
  381. PP.RemovePragmaHandler("STDC", STDCCXLIMITHandler.get());
  382. STDCCXLIMITHandler.reset();
  383. PP.RemovePragmaHandler("STDC", STDCUnknownHandler.get());
  384. STDCUnknownHandler.reset();
  385. PP.RemovePragmaHandler("clang", OptimizeHandler.get());
  386. OptimizeHandler.reset();
  387. PP.RemovePragmaHandler("clang", LoopHintHandler.get());
  388. LoopHintHandler.reset();
  389. PP.RemovePragmaHandler(UnrollHintHandler.get());
  390. UnrollHintHandler.reset();
  391. PP.RemovePragmaHandler(NoUnrollHintHandler.get());
  392. NoUnrollHintHandler.reset();
  393. PP.RemovePragmaHandler(UnrollAndJamHintHandler.get());
  394. UnrollAndJamHintHandler.reset();
  395. PP.RemovePragmaHandler(NoUnrollAndJamHintHandler.get());
  396. NoUnrollAndJamHintHandler.reset();
  397. PP.RemovePragmaHandler("clang", FPHandler.get());
  398. FPHandler.reset();
  399. PP.RemovePragmaHandler("clang", AttributePragmaHandler.get());
  400. AttributePragmaHandler.reset();
  401. }
  402. /// Handle the annotation token produced for #pragma unused(...)
  403. ///
  404. /// Each annot_pragma_unused is followed by the argument token so e.g.
  405. /// "#pragma unused(x,y)" becomes:
  406. /// annot_pragma_unused 'x' annot_pragma_unused 'y'
  407. void Parser::HandlePragmaUnused() {
  408. assert(Tok.is(tok::annot_pragma_unused));
  409. SourceLocation UnusedLoc = ConsumeAnnotationToken();
  410. Actions.ActOnPragmaUnused(Tok, getCurScope(), UnusedLoc);
  411. ConsumeToken(); // The argument token.
  412. }
  413. void Parser::HandlePragmaVisibility() {
  414. assert(Tok.is(tok::annot_pragma_vis));
  415. const IdentifierInfo *VisType =
  416. static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
  417. SourceLocation VisLoc = ConsumeAnnotationToken();
  418. Actions.ActOnPragmaVisibility(VisType, VisLoc);
  419. }
  420. namespace {
  421. struct PragmaPackInfo {
  422. Sema::PragmaMsStackAction Action;
  423. StringRef SlotLabel;
  424. Token Alignment;
  425. };
  426. } // end anonymous namespace
  427. void Parser::HandlePragmaPack() {
  428. assert(Tok.is(tok::annot_pragma_pack));
  429. PragmaPackInfo *Info =
  430. static_cast<PragmaPackInfo *>(Tok.getAnnotationValue());
  431. SourceLocation PragmaLoc = Tok.getLocation();
  432. ExprResult Alignment;
  433. if (Info->Alignment.is(tok::numeric_constant)) {
  434. Alignment = Actions.ActOnNumericConstant(Info->Alignment);
  435. if (Alignment.isInvalid()) {
  436. ConsumeAnnotationToken();
  437. return;
  438. }
  439. }
  440. Actions.ActOnPragmaPack(PragmaLoc, Info->Action, Info->SlotLabel,
  441. Alignment.get());
  442. // Consume the token after processing the pragma to enable pragma-specific
  443. // #include warnings.
  444. ConsumeAnnotationToken();
  445. }
  446. void Parser::HandlePragmaMSStruct() {
  447. assert(Tok.is(tok::annot_pragma_msstruct));
  448. PragmaMSStructKind Kind = static_cast<PragmaMSStructKind>(
  449. reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
  450. Actions.ActOnPragmaMSStruct(Kind);
  451. ConsumeAnnotationToken();
  452. }
  453. void Parser::HandlePragmaAlign() {
  454. assert(Tok.is(tok::annot_pragma_align));
  455. Sema::PragmaOptionsAlignKind Kind =
  456. static_cast<Sema::PragmaOptionsAlignKind>(
  457. reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
  458. Actions.ActOnPragmaOptionsAlign(Kind, Tok.getLocation());
  459. // Consume the token after processing the pragma to enable pragma-specific
  460. // #include warnings.
  461. ConsumeAnnotationToken();
  462. }
  463. void Parser::HandlePragmaDump() {
  464. assert(Tok.is(tok::annot_pragma_dump));
  465. IdentifierInfo *II =
  466. reinterpret_cast<IdentifierInfo *>(Tok.getAnnotationValue());
  467. Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
  468. ConsumeAnnotationToken();
  469. }
  470. void Parser::HandlePragmaWeak() {
  471. assert(Tok.is(tok::annot_pragma_weak));
  472. SourceLocation PragmaLoc = ConsumeAnnotationToken();
  473. Actions.ActOnPragmaWeakID(Tok.getIdentifierInfo(), PragmaLoc,
  474. Tok.getLocation());
  475. ConsumeToken(); // The weak name.
  476. }
  477. void Parser::HandlePragmaWeakAlias() {
  478. assert(Tok.is(tok::annot_pragma_weakalias));
  479. SourceLocation PragmaLoc = ConsumeAnnotationToken();
  480. IdentifierInfo *WeakName = Tok.getIdentifierInfo();
  481. SourceLocation WeakNameLoc = Tok.getLocation();
  482. ConsumeToken();
  483. IdentifierInfo *AliasName = Tok.getIdentifierInfo();
  484. SourceLocation AliasNameLoc = Tok.getLocation();
  485. ConsumeToken();
  486. Actions.ActOnPragmaWeakAlias(WeakName, AliasName, PragmaLoc,
  487. WeakNameLoc, AliasNameLoc);
  488. }
  489. void Parser::HandlePragmaRedefineExtname() {
  490. assert(Tok.is(tok::annot_pragma_redefine_extname));
  491. SourceLocation RedefLoc = ConsumeAnnotationToken();
  492. IdentifierInfo *RedefName = Tok.getIdentifierInfo();
  493. SourceLocation RedefNameLoc = Tok.getLocation();
  494. ConsumeToken();
  495. IdentifierInfo *AliasName = Tok.getIdentifierInfo();
  496. SourceLocation AliasNameLoc = Tok.getLocation();
  497. ConsumeToken();
  498. Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc,
  499. RedefNameLoc, AliasNameLoc);
  500. }
  501. void Parser::HandlePragmaFPContract() {
  502. assert(Tok.is(tok::annot_pragma_fp_contract));
  503. tok::OnOffSwitch OOS =
  504. static_cast<tok::OnOffSwitch>(
  505. reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
  506. LangOptions::FPContractModeKind FPC;
  507. switch (OOS) {
  508. case tok::OOS_ON:
  509. FPC = LangOptions::FPC_On;
  510. break;
  511. case tok::OOS_OFF:
  512. FPC = LangOptions::FPC_Off;
  513. break;
  514. case tok::OOS_DEFAULT:
  515. FPC = getLangOpts().getDefaultFPContractMode();
  516. break;
  517. }
  518. Actions.ActOnPragmaFPContract(FPC);
  519. ConsumeAnnotationToken();
  520. }
  521. void Parser::HandlePragmaFEnvAccess() {
  522. assert(Tok.is(tok::annot_pragma_fenv_access));
  523. tok::OnOffSwitch OOS =
  524. static_cast<tok::OnOffSwitch>(
  525. reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
  526. LangOptions::FEnvAccessModeKind FPC;
  527. switch (OOS) {
  528. case tok::OOS_ON:
  529. FPC = LangOptions::FEA_On;
  530. break;
  531. case tok::OOS_OFF:
  532. FPC = LangOptions::FEA_Off;
  533. break;
  534. case tok::OOS_DEFAULT: // FIXME: Add this cli option when it makes sense.
  535. FPC = LangOptions::FEA_Off;
  536. break;
  537. }
  538. Actions.ActOnPragmaFEnvAccess(FPC);
  539. ConsumeAnnotationToken();
  540. }
  541. StmtResult Parser::HandlePragmaCaptured()
  542. {
  543. assert(Tok.is(tok::annot_pragma_captured));
  544. ConsumeAnnotationToken();
  545. if (Tok.isNot(tok::l_brace)) {
  546. PP.Diag(Tok, diag::err_expected) << tok::l_brace;
  547. return StmtError();
  548. }
  549. SourceLocation Loc = Tok.getLocation();
  550. ParseScope CapturedRegionScope(this, Scope::FnScope | Scope::DeclScope |
  551. Scope::CompoundStmtScope);
  552. Actions.ActOnCapturedRegionStart(Loc, getCurScope(), CR_Default,
  553. /*NumParams=*/1);
  554. StmtResult R = ParseCompoundStatement();
  555. CapturedRegionScope.Exit();
  556. if (R.isInvalid()) {
  557. Actions.ActOnCapturedRegionError();
  558. return StmtError();
  559. }
  560. return Actions.ActOnCapturedRegionEnd(R.get());
  561. }
  562. namespace {
  563. enum OpenCLExtState : char {
  564. Disable, Enable, Begin, End
  565. };
  566. typedef std::pair<const IdentifierInfo *, OpenCLExtState> OpenCLExtData;
  567. }
  568. void Parser::HandlePragmaOpenCLExtension() {
  569. assert(Tok.is(tok::annot_pragma_opencl_extension));
  570. OpenCLExtData *Data = static_cast<OpenCLExtData*>(Tok.getAnnotationValue());
  571. auto State = Data->second;
  572. auto Ident = Data->first;
  573. SourceLocation NameLoc = Tok.getLocation();
  574. ConsumeAnnotationToken();
  575. auto &Opt = Actions.getOpenCLOptions();
  576. auto Name = Ident->getName();
  577. // OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions,
  578. // overriding all previously issued extension directives, but only if the
  579. // behavior is set to disable."
  580. if (Name == "all") {
  581. if (State == Disable) {
  582. Opt.disableAll();
  583. Opt.enableSupportedCore(getLangOpts());
  584. } else {
  585. PP.Diag(NameLoc, diag::warn_pragma_expected_predicate) << 1;
  586. }
  587. } else if (State == Begin) {
  588. if (!Opt.isKnown(Name) || !Opt.isSupported(Name, getLangOpts())) {
  589. Opt.support(Name);
  590. }
  591. Actions.setCurrentOpenCLExtension(Name);
  592. } else if (State == End) {
  593. if (Name != Actions.getCurrentOpenCLExtension())
  594. PP.Diag(NameLoc, diag::warn_pragma_begin_end_mismatch);
  595. Actions.setCurrentOpenCLExtension("");
  596. } else if (!Opt.isKnown(Name))
  597. PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << Ident;
  598. else if (Opt.isSupportedExtension(Name, getLangOpts()))
  599. Opt.enable(Name, State == Enable);
  600. else if (Opt.isSupportedCore(Name, getLangOpts()))
  601. PP.Diag(NameLoc, diag::warn_pragma_extension_is_core) << Ident;
  602. else
  603. PP.Diag(NameLoc, diag::warn_pragma_unsupported_extension) << Ident;
  604. }
  605. void Parser::HandlePragmaMSPointersToMembers() {
  606. assert(Tok.is(tok::annot_pragma_ms_pointers_to_members));
  607. LangOptions::PragmaMSPointersToMembersKind RepresentationMethod =
  608. static_cast<LangOptions::PragmaMSPointersToMembersKind>(
  609. reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
  610. SourceLocation PragmaLoc = ConsumeAnnotationToken();
  611. Actions.ActOnPragmaMSPointersToMembers(RepresentationMethod, PragmaLoc);
  612. }
  613. void Parser::HandlePragmaMSVtorDisp() {
  614. assert(Tok.is(tok::annot_pragma_ms_vtordisp));
  615. uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
  616. Sema::PragmaMsStackAction Action =
  617. static_cast<Sema::PragmaMsStackAction>((Value >> 16) & 0xFFFF);
  618. MSVtorDispAttr::Mode Mode = MSVtorDispAttr::Mode(Value & 0xFFFF);
  619. SourceLocation PragmaLoc = ConsumeAnnotationToken();
  620. Actions.ActOnPragmaMSVtorDisp(Action, PragmaLoc, Mode);
  621. }
  622. void Parser::HandlePragmaMSPragma() {
  623. assert(Tok.is(tok::annot_pragma_ms_pragma));
  624. // Grab the tokens out of the annotation and enter them into the stream.
  625. auto TheTokens =
  626. (std::pair<std::unique_ptr<Token[]>, size_t> *)Tok.getAnnotationValue();
  627. PP.EnterTokenStream(std::move(TheTokens->first), TheTokens->second, true,
  628. /*IsReinject=*/true);
  629. SourceLocation PragmaLocation = ConsumeAnnotationToken();
  630. assert(Tok.isAnyIdentifier());
  631. StringRef PragmaName = Tok.getIdentifierInfo()->getName();
  632. PP.Lex(Tok); // pragma kind
  633. // Figure out which #pragma we're dealing with. The switch has no default
  634. // because lex shouldn't emit the annotation token for unrecognized pragmas.
  635. typedef bool (Parser::*PragmaHandler)(StringRef, SourceLocation);
  636. PragmaHandler Handler = llvm::StringSwitch<PragmaHandler>(PragmaName)
  637. .Case("data_seg", &Parser::HandlePragmaMSSegment)
  638. .Case("bss_seg", &Parser::HandlePragmaMSSegment)
  639. .Case("const_seg", &Parser::HandlePragmaMSSegment)
  640. .Case("code_seg", &Parser::HandlePragmaMSSegment)
  641. .Case("section", &Parser::HandlePragmaMSSection)
  642. .Case("init_seg", &Parser::HandlePragmaMSInitSeg);
  643. if (!(this->*Handler)(PragmaName, PragmaLocation)) {
  644. // Pragma handling failed, and has been diagnosed. Slurp up the tokens
  645. // until eof (really end of line) to prevent follow-on errors.
  646. while (Tok.isNot(tok::eof))
  647. PP.Lex(Tok);
  648. PP.Lex(Tok);
  649. }
  650. }
  651. bool Parser::HandlePragmaMSSection(StringRef PragmaName,
  652. SourceLocation PragmaLocation) {
  653. if (Tok.isNot(tok::l_paren)) {
  654. PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
  655. return false;
  656. }
  657. PP.Lex(Tok); // (
  658. // Parsing code for pragma section
  659. if (Tok.isNot(tok::string_literal)) {
  660. PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name)
  661. << PragmaName;
  662. return false;
  663. }
  664. ExprResult StringResult = ParseStringLiteralExpression();
  665. if (StringResult.isInvalid())
  666. return false; // Already diagnosed.
  667. StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get());
  668. if (SegmentName->getCharByteWidth() != 1) {
  669. PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
  670. << PragmaName;
  671. return false;
  672. }
  673. int SectionFlags = ASTContext::PSF_Read;
  674. bool SectionFlagsAreDefault = true;
  675. while (Tok.is(tok::comma)) {
  676. PP.Lex(Tok); // ,
  677. // Ignore "long" and "short".
  678. // They are undocumented, but widely used, section attributes which appear
  679. // to do nothing.
  680. if (Tok.is(tok::kw_long) || Tok.is(tok::kw_short)) {
  681. PP.Lex(Tok); // long/short
  682. continue;
  683. }
  684. if (!Tok.isAnyIdentifier()) {
  685. PP.Diag(PragmaLocation, diag::warn_pragma_expected_action_or_r_paren)
  686. << PragmaName;
  687. return false;
  688. }
  689. ASTContext::PragmaSectionFlag Flag =
  690. llvm::StringSwitch<ASTContext::PragmaSectionFlag>(
  691. Tok.getIdentifierInfo()->getName())
  692. .Case("read", ASTContext::PSF_Read)
  693. .Case("write", ASTContext::PSF_Write)
  694. .Case("execute", ASTContext::PSF_Execute)
  695. .Case("shared", ASTContext::PSF_Invalid)
  696. .Case("nopage", ASTContext::PSF_Invalid)
  697. .Case("nocache", ASTContext::PSF_Invalid)
  698. .Case("discard", ASTContext::PSF_Invalid)
  699. .Case("remove", ASTContext::PSF_Invalid)
  700. .Default(ASTContext::PSF_None);
  701. if (Flag == ASTContext::PSF_None || Flag == ASTContext::PSF_Invalid) {
  702. PP.Diag(PragmaLocation, Flag == ASTContext::PSF_None
  703. ? diag::warn_pragma_invalid_specific_action
  704. : diag::warn_pragma_unsupported_action)
  705. << PragmaName << Tok.getIdentifierInfo()->getName();
  706. return false;
  707. }
  708. SectionFlags |= Flag;
  709. SectionFlagsAreDefault = false;
  710. PP.Lex(Tok); // Identifier
  711. }
  712. // If no section attributes are specified, the section will be marked as
  713. // read/write.
  714. if (SectionFlagsAreDefault)
  715. SectionFlags |= ASTContext::PSF_Write;
  716. if (Tok.isNot(tok::r_paren)) {
  717. PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
  718. return false;
  719. }
  720. PP.Lex(Tok); // )
  721. if (Tok.isNot(tok::eof)) {
  722. PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
  723. << PragmaName;
  724. return false;
  725. }
  726. PP.Lex(Tok); // eof
  727. Actions.ActOnPragmaMSSection(PragmaLocation, SectionFlags, SegmentName);
  728. return true;
  729. }
  730. bool Parser::HandlePragmaMSSegment(StringRef PragmaName,
  731. SourceLocation PragmaLocation) {
  732. if (Tok.isNot(tok::l_paren)) {
  733. PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
  734. return false;
  735. }
  736. PP.Lex(Tok); // (
  737. Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
  738. StringRef SlotLabel;
  739. if (Tok.isAnyIdentifier()) {
  740. StringRef PushPop = Tok.getIdentifierInfo()->getName();
  741. if (PushPop == "push")
  742. Action = Sema::PSK_Push;
  743. else if (PushPop == "pop")
  744. Action = Sema::PSK_Pop;
  745. else {
  746. PP.Diag(PragmaLocation,
  747. diag::warn_pragma_expected_section_push_pop_or_name)
  748. << PragmaName;
  749. return false;
  750. }
  751. if (Action != Sema::PSK_Reset) {
  752. PP.Lex(Tok); // push | pop
  753. if (Tok.is(tok::comma)) {
  754. PP.Lex(Tok); // ,
  755. // If we've got a comma, we either need a label or a string.
  756. if (Tok.isAnyIdentifier()) {
  757. SlotLabel = Tok.getIdentifierInfo()->getName();
  758. PP.Lex(Tok); // identifier
  759. if (Tok.is(tok::comma))
  760. PP.Lex(Tok);
  761. else if (Tok.isNot(tok::r_paren)) {
  762. PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc)
  763. << PragmaName;
  764. return false;
  765. }
  766. }
  767. } else if (Tok.isNot(tok::r_paren)) {
  768. PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName;
  769. return false;
  770. }
  771. }
  772. }
  773. // Grab the string literal for our section name.
  774. StringLiteral *SegmentName = nullptr;
  775. if (Tok.isNot(tok::r_paren)) {
  776. if (Tok.isNot(tok::string_literal)) {
  777. unsigned DiagID = Action != Sema::PSK_Reset ? !SlotLabel.empty() ?
  778. diag::warn_pragma_expected_section_name :
  779. diag::warn_pragma_expected_section_label_or_name :
  780. diag::warn_pragma_expected_section_push_pop_or_name;
  781. PP.Diag(PragmaLocation, DiagID) << PragmaName;
  782. return false;
  783. }
  784. ExprResult StringResult = ParseStringLiteralExpression();
  785. if (StringResult.isInvalid())
  786. return false; // Already diagnosed.
  787. SegmentName = cast<StringLiteral>(StringResult.get());
  788. if (SegmentName->getCharByteWidth() != 1) {
  789. PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
  790. << PragmaName;
  791. return false;
  792. }
  793. // Setting section "" has no effect
  794. if (SegmentName->getLength())
  795. Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
  796. }
  797. if (Tok.isNot(tok::r_paren)) {
  798. PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
  799. return false;
  800. }
  801. PP.Lex(Tok); // )
  802. if (Tok.isNot(tok::eof)) {
  803. PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
  804. << PragmaName;
  805. return false;
  806. }
  807. PP.Lex(Tok); // eof
  808. Actions.ActOnPragmaMSSeg(PragmaLocation, Action, SlotLabel,
  809. SegmentName, PragmaName);
  810. return true;
  811. }
  812. // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
  813. bool Parser::HandlePragmaMSInitSeg(StringRef PragmaName,
  814. SourceLocation PragmaLocation) {
  815. if (getTargetInfo().getTriple().getEnvironment() != llvm::Triple::MSVC) {
  816. PP.Diag(PragmaLocation, diag::warn_pragma_init_seg_unsupported_target);
  817. return false;
  818. }
  819. if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
  820. PragmaName))
  821. return false;
  822. // Parse either the known section names or the string section name.
  823. StringLiteral *SegmentName = nullptr;
  824. if (Tok.isAnyIdentifier()) {
  825. auto *II = Tok.getIdentifierInfo();
  826. StringRef Section = llvm::StringSwitch<StringRef>(II->getName())
  827. .Case("compiler", "\".CRT$XCC\"")
  828. .Case("lib", "\".CRT$XCL\"")
  829. .Case("user", "\".CRT$XCU\"")
  830. .Default("");
  831. if (!Section.empty()) {
  832. // Pretend the user wrote the appropriate string literal here.
  833. Token Toks[1];
  834. Toks[0].startToken();
  835. Toks[0].setKind(tok::string_literal);
  836. Toks[0].setLocation(Tok.getLocation());
  837. Toks[0].setLiteralData(Section.data());
  838. Toks[0].setLength(Section.size());
  839. SegmentName =
  840. cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
  841. PP.Lex(Tok);
  842. }
  843. } else if (Tok.is(tok::string_literal)) {
  844. ExprResult StringResult = ParseStringLiteralExpression();
  845. if (StringResult.isInvalid())
  846. return false;
  847. SegmentName = cast<StringLiteral>(StringResult.get());
  848. if (SegmentName->getCharByteWidth() != 1) {
  849. PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
  850. << PragmaName;
  851. return false;
  852. }
  853. // FIXME: Add support for the '[, func-name]' part of the pragma.
  854. }
  855. if (!SegmentName) {
  856. PP.Diag(PragmaLocation, diag::warn_pragma_expected_init_seg) << PragmaName;
  857. return false;
  858. }
  859. if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
  860. PragmaName) ||
  861. ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
  862. PragmaName))
  863. return false;
  864. Actions.ActOnPragmaMSInitSeg(PragmaLocation, SegmentName);
  865. return true;
  866. }
  867. namespace {
  868. struct PragmaLoopHintInfo {
  869. Token PragmaName;
  870. Token Option;
  871. ArrayRef<Token> Toks;
  872. };
  873. } // end anonymous namespace
  874. static std::string PragmaLoopHintString(Token PragmaName, Token Option) {
  875. StringRef Str = PragmaName.getIdentifierInfo()->getName();
  876. std::string ClangLoopStr = (llvm::Twine("clang loop ") + Str).str();
  877. return llvm::StringSwitch<StringRef>(Str)
  878. .Case("loop", ClangLoopStr)
  879. .Case("unroll_and_jam", Str)
  880. .Case("unroll", Str)
  881. .Default("");
  882. }
  883. bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
  884. assert(Tok.is(tok::annot_pragma_loop_hint));
  885. PragmaLoopHintInfo *Info =
  886. static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
  887. IdentifierInfo *PragmaNameInfo = Info->PragmaName.getIdentifierInfo();
  888. Hint.PragmaNameLoc = IdentifierLoc::create(
  889. Actions.Context, Info->PragmaName.getLocation(), PragmaNameInfo);
  890. // It is possible that the loop hint has no option identifier, such as
  891. // #pragma unroll(4).
  892. IdentifierInfo *OptionInfo = Info->Option.is(tok::identifier)
  893. ? Info->Option.getIdentifierInfo()
  894. : nullptr;
  895. Hint.OptionLoc = IdentifierLoc::create(
  896. Actions.Context, Info->Option.getLocation(), OptionInfo);
  897. llvm::ArrayRef<Token> Toks = Info->Toks;
  898. // Return a valid hint if pragma unroll or nounroll were specified
  899. // without an argument.
  900. auto IsLoopHint = llvm::StringSwitch<bool>(PragmaNameInfo->getName())
  901. .Cases("unroll", "nounroll", "unroll_and_jam",
  902. "nounroll_and_jam", true)
  903. .Default(false);
  904. if (Toks.empty() && IsLoopHint) {
  905. ConsumeAnnotationToken();
  906. Hint.Range = Info->PragmaName.getLocation();
  907. return true;
  908. }
  909. // The constant expression is always followed by an eof token, which increases
  910. // the TokSize by 1.
  911. assert(!Toks.empty() &&
  912. "PragmaLoopHintInfo::Toks must contain at least one token.");
  913. // If no option is specified the argument is assumed to be a constant expr.
  914. bool OptionUnroll = false;
  915. bool OptionUnrollAndJam = false;
  916. bool OptionDistribute = false;
  917. bool OptionPipelineDisabled = false;
  918. bool StateOption = false;
  919. if (OptionInfo) { // Pragma Unroll does not specify an option.
  920. OptionUnroll = OptionInfo->isStr("unroll");
  921. OptionUnrollAndJam = OptionInfo->isStr("unroll_and_jam");
  922. OptionDistribute = OptionInfo->isStr("distribute");
  923. OptionPipelineDisabled = OptionInfo->isStr("pipeline");
  924. StateOption = llvm::StringSwitch<bool>(OptionInfo->getName())
  925. .Case("vectorize", true)
  926. .Case("interleave", true)
  927. .Case("vectorize_predicate", true)
  928. .Default(false) ||
  929. OptionUnroll || OptionUnrollAndJam || OptionDistribute ||
  930. OptionPipelineDisabled;
  931. }
  932. bool AssumeSafetyArg = !OptionUnroll && !OptionUnrollAndJam &&
  933. !OptionDistribute && !OptionPipelineDisabled;
  934. // Verify loop hint has an argument.
  935. if (Toks[0].is(tok::eof)) {
  936. ConsumeAnnotationToken();
  937. Diag(Toks[0].getLocation(), diag::err_pragma_loop_missing_argument)
  938. << /*StateArgument=*/StateOption
  939. << /*FullKeyword=*/(OptionUnroll || OptionUnrollAndJam)
  940. << /*AssumeSafetyKeyword=*/AssumeSafetyArg;
  941. return false;
  942. }
  943. // Validate the argument.
  944. if (StateOption) {
  945. ConsumeAnnotationToken();
  946. SourceLocation StateLoc = Toks[0].getLocation();
  947. IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
  948. bool Valid = StateInfo &&
  949. llvm::StringSwitch<bool>(StateInfo->getName())
  950. .Case("disable", true)
  951. .Case("enable", !OptionPipelineDisabled)
  952. .Case("full", OptionUnroll || OptionUnrollAndJam)
  953. .Case("assume_safety", AssumeSafetyArg)
  954. .Default(false);
  955. if (!Valid) {
  956. if (OptionPipelineDisabled) {
  957. Diag(Toks[0].getLocation(), diag::err_pragma_pipeline_invalid_keyword);
  958. } else {
  959. Diag(Toks[0].getLocation(), diag::err_pragma_invalid_keyword)
  960. << /*FullKeyword=*/(OptionUnroll || OptionUnrollAndJam)
  961. << /*AssumeSafetyKeyword=*/AssumeSafetyArg;
  962. }
  963. return false;
  964. }
  965. if (Toks.size() > 2)
  966. Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  967. << PragmaLoopHintString(Info->PragmaName, Info->Option);
  968. Hint.StateLoc = IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
  969. } else {
  970. // Enter constant expression including eof terminator into token stream.
  971. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false,
  972. /*IsReinject=*/false);
  973. ConsumeAnnotationToken();
  974. ExprResult R = ParseConstantExpression();
  975. // Tokens following an error in an ill-formed constant expression will
  976. // remain in the token stream and must be removed.
  977. if (Tok.isNot(tok::eof)) {
  978. Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  979. << PragmaLoopHintString(Info->PragmaName, Info->Option);
  980. while (Tok.isNot(tok::eof))
  981. ConsumeAnyToken();
  982. }
  983. ConsumeToken(); // Consume the constant expression eof terminator.
  984. if (R.isInvalid() ||
  985. Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
  986. return false;
  987. // Argument is a constant expression with an integer type.
  988. Hint.ValueExpr = R.get();
  989. }
  990. Hint.Range = SourceRange(Info->PragmaName.getLocation(),
  991. Info->Toks.back().getLocation());
  992. return true;
  993. }
  994. namespace {
  995. struct PragmaAttributeInfo {
  996. enum ActionType { Push, Pop, Attribute };
  997. ParsedAttributes &Attributes;
  998. ActionType Action;
  999. const IdentifierInfo *Namespace = nullptr;
  1000. ArrayRef<Token> Tokens;
  1001. PragmaAttributeInfo(ParsedAttributes &Attributes) : Attributes(Attributes) {}
  1002. };
  1003. #include "clang/Parse/AttrSubMatchRulesParserStringSwitches.inc"
  1004. } // end anonymous namespace
  1005. static StringRef getIdentifier(const Token &Tok) {
  1006. if (Tok.is(tok::identifier))
  1007. return Tok.getIdentifierInfo()->getName();
  1008. const char *S = tok::getKeywordSpelling(Tok.getKind());
  1009. if (!S)
  1010. return "";
  1011. return S;
  1012. }
  1013. static bool isAbstractAttrMatcherRule(attr::SubjectMatchRule Rule) {
  1014. using namespace attr;
  1015. switch (Rule) {
  1016. #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract) \
  1017. case Value: \
  1018. return IsAbstract;
  1019. #include "clang/Basic/AttrSubMatchRulesList.inc"
  1020. }
  1021. llvm_unreachable("Invalid attribute subject match rule");
  1022. return false;
  1023. }
  1024. static void diagnoseExpectedAttributeSubjectSubRule(
  1025. Parser &PRef, attr::SubjectMatchRule PrimaryRule, StringRef PrimaryRuleName,
  1026. SourceLocation SubRuleLoc) {
  1027. auto Diagnostic =
  1028. PRef.Diag(SubRuleLoc,
  1029. diag::err_pragma_attribute_expected_subject_sub_identifier)
  1030. << PrimaryRuleName;
  1031. if (const char *SubRules = validAttributeSubjectMatchSubRules(PrimaryRule))
  1032. Diagnostic << /*SubRulesSupported=*/1 << SubRules;
  1033. else
  1034. Diagnostic << /*SubRulesSupported=*/0;
  1035. }
  1036. static void diagnoseUnknownAttributeSubjectSubRule(
  1037. Parser &PRef, attr::SubjectMatchRule PrimaryRule, StringRef PrimaryRuleName,
  1038. StringRef SubRuleName, SourceLocation SubRuleLoc) {
  1039. auto Diagnostic =
  1040. PRef.Diag(SubRuleLoc, diag::err_pragma_attribute_unknown_subject_sub_rule)
  1041. << SubRuleName << PrimaryRuleName;
  1042. if (const char *SubRules = validAttributeSubjectMatchSubRules(PrimaryRule))
  1043. Diagnostic << /*SubRulesSupported=*/1 << SubRules;
  1044. else
  1045. Diagnostic << /*SubRulesSupported=*/0;
  1046. }
  1047. bool Parser::ParsePragmaAttributeSubjectMatchRuleSet(
  1048. attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc,
  1049. SourceLocation &LastMatchRuleEndLoc) {
  1050. bool IsAny = false;
  1051. BalancedDelimiterTracker AnyParens(*this, tok::l_paren);
  1052. if (getIdentifier(Tok) == "any") {
  1053. AnyLoc = ConsumeToken();
  1054. IsAny = true;
  1055. if (AnyParens.expectAndConsume())
  1056. return true;
  1057. }
  1058. do {
  1059. // Parse the subject matcher rule.
  1060. StringRef Name = getIdentifier(Tok);
  1061. if (Name.empty()) {
  1062. Diag(Tok, diag::err_pragma_attribute_expected_subject_identifier);
  1063. return true;
  1064. }
  1065. std::pair<Optional<attr::SubjectMatchRule>,
  1066. Optional<attr::SubjectMatchRule> (*)(StringRef, bool)>
  1067. Rule = isAttributeSubjectMatchRule(Name);
  1068. if (!Rule.first) {
  1069. Diag(Tok, diag::err_pragma_attribute_unknown_subject_rule) << Name;
  1070. return true;
  1071. }
  1072. attr::SubjectMatchRule PrimaryRule = *Rule.first;
  1073. SourceLocation RuleLoc = ConsumeToken();
  1074. BalancedDelimiterTracker Parens(*this, tok::l_paren);
  1075. if (isAbstractAttrMatcherRule(PrimaryRule)) {
  1076. if (Parens.expectAndConsume())
  1077. return true;
  1078. } else if (Parens.consumeOpen()) {
  1079. if (!SubjectMatchRules
  1080. .insert(
  1081. std::make_pair(PrimaryRule, SourceRange(RuleLoc, RuleLoc)))
  1082. .second)
  1083. Diag(RuleLoc, diag::err_pragma_attribute_duplicate_subject)
  1084. << Name
  1085. << FixItHint::CreateRemoval(SourceRange(
  1086. RuleLoc, Tok.is(tok::comma) ? Tok.getLocation() : RuleLoc));
  1087. LastMatchRuleEndLoc = RuleLoc;
  1088. continue;
  1089. }
  1090. // Parse the sub-rules.
  1091. StringRef SubRuleName = getIdentifier(Tok);
  1092. if (SubRuleName.empty()) {
  1093. diagnoseExpectedAttributeSubjectSubRule(*this, PrimaryRule, Name,
  1094. Tok.getLocation());
  1095. return true;
  1096. }
  1097. attr::SubjectMatchRule SubRule;
  1098. if (SubRuleName == "unless") {
  1099. SourceLocation SubRuleLoc = ConsumeToken();
  1100. BalancedDelimiterTracker Parens(*this, tok::l_paren);
  1101. if (Parens.expectAndConsume())
  1102. return true;
  1103. SubRuleName = getIdentifier(Tok);
  1104. if (SubRuleName.empty()) {
  1105. diagnoseExpectedAttributeSubjectSubRule(*this, PrimaryRule, Name,
  1106. SubRuleLoc);
  1107. return true;
  1108. }
  1109. auto SubRuleOrNone = Rule.second(SubRuleName, /*IsUnless=*/true);
  1110. if (!SubRuleOrNone) {
  1111. std::string SubRuleUnlessName = "unless(" + SubRuleName.str() + ")";
  1112. diagnoseUnknownAttributeSubjectSubRule(*this, PrimaryRule, Name,
  1113. SubRuleUnlessName, SubRuleLoc);
  1114. return true;
  1115. }
  1116. SubRule = *SubRuleOrNone;
  1117. ConsumeToken();
  1118. if (Parens.consumeClose())
  1119. return true;
  1120. } else {
  1121. auto SubRuleOrNone = Rule.second(SubRuleName, /*IsUnless=*/false);
  1122. if (!SubRuleOrNone) {
  1123. diagnoseUnknownAttributeSubjectSubRule(*this, PrimaryRule, Name,
  1124. SubRuleName, Tok.getLocation());
  1125. return true;
  1126. }
  1127. SubRule = *SubRuleOrNone;
  1128. ConsumeToken();
  1129. }
  1130. SourceLocation RuleEndLoc = Tok.getLocation();
  1131. LastMatchRuleEndLoc = RuleEndLoc;
  1132. if (Parens.consumeClose())
  1133. return true;
  1134. if (!SubjectMatchRules
  1135. .insert(std::make_pair(SubRule, SourceRange(RuleLoc, RuleEndLoc)))
  1136. .second) {
  1137. Diag(RuleLoc, diag::err_pragma_attribute_duplicate_subject)
  1138. << attr::getSubjectMatchRuleSpelling(SubRule)
  1139. << FixItHint::CreateRemoval(SourceRange(
  1140. RuleLoc, Tok.is(tok::comma) ? Tok.getLocation() : RuleEndLoc));
  1141. continue;
  1142. }
  1143. } while (IsAny && TryConsumeToken(tok::comma));
  1144. if (IsAny)
  1145. if (AnyParens.consumeClose())
  1146. return true;
  1147. return false;
  1148. }
  1149. namespace {
  1150. /// Describes the stage at which attribute subject rule parsing was interrupted.
  1151. enum class MissingAttributeSubjectRulesRecoveryPoint {
  1152. Comma,
  1153. ApplyTo,
  1154. Equals,
  1155. Any,
  1156. None,
  1157. };
  1158. MissingAttributeSubjectRulesRecoveryPoint
  1159. getAttributeSubjectRulesRecoveryPointForToken(const Token &Tok) {
  1160. if (const auto *II = Tok.getIdentifierInfo()) {
  1161. if (II->isStr("apply_to"))
  1162. return MissingAttributeSubjectRulesRecoveryPoint::ApplyTo;
  1163. if (II->isStr("any"))
  1164. return MissingAttributeSubjectRulesRecoveryPoint::Any;
  1165. }
  1166. if (Tok.is(tok::equal))
  1167. return MissingAttributeSubjectRulesRecoveryPoint::Equals;
  1168. return MissingAttributeSubjectRulesRecoveryPoint::None;
  1169. }
  1170. /// Creates a diagnostic for the attribute subject rule parsing diagnostic that
  1171. /// suggests the possible attribute subject rules in a fix-it together with
  1172. /// any other missing tokens.
  1173. DiagnosticBuilder createExpectedAttributeSubjectRulesTokenDiagnostic(
  1174. unsigned DiagID, ParsedAttr &Attribute,
  1175. MissingAttributeSubjectRulesRecoveryPoint Point, Parser &PRef) {
  1176. SourceLocation Loc = PRef.getEndOfPreviousToken();
  1177. if (Loc.isInvalid())
  1178. Loc = PRef.getCurToken().getLocation();
  1179. auto Diagnostic = PRef.Diag(Loc, DiagID);
  1180. std::string FixIt;
  1181. MissingAttributeSubjectRulesRecoveryPoint EndPoint =
  1182. getAttributeSubjectRulesRecoveryPointForToken(PRef.getCurToken());
  1183. if (Point == MissingAttributeSubjectRulesRecoveryPoint::Comma)
  1184. FixIt = ", ";
  1185. if (Point <= MissingAttributeSubjectRulesRecoveryPoint::ApplyTo &&
  1186. EndPoint > MissingAttributeSubjectRulesRecoveryPoint::ApplyTo)
  1187. FixIt += "apply_to";
  1188. if (Point <= MissingAttributeSubjectRulesRecoveryPoint::Equals &&
  1189. EndPoint > MissingAttributeSubjectRulesRecoveryPoint::Equals)
  1190. FixIt += " = ";
  1191. SourceRange FixItRange(Loc);
  1192. if (EndPoint == MissingAttributeSubjectRulesRecoveryPoint::None) {
  1193. // Gather the subject match rules that are supported by the attribute.
  1194. SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4> SubjectMatchRuleSet;
  1195. Attribute.getMatchRules(PRef.getLangOpts(), SubjectMatchRuleSet);
  1196. if (SubjectMatchRuleSet.empty()) {
  1197. // FIXME: We can emit a "fix-it" with a subject list placeholder when
  1198. // placeholders will be supported by the fix-its.
  1199. return Diagnostic;
  1200. }
  1201. FixIt += "any(";
  1202. bool NeedsComma = false;
  1203. for (const auto &I : SubjectMatchRuleSet) {
  1204. // Ensure that the missing rule is reported in the fix-it only when it's
  1205. // supported in the current language mode.
  1206. if (!I.second)
  1207. continue;
  1208. if (NeedsComma)
  1209. FixIt += ", ";
  1210. else
  1211. NeedsComma = true;
  1212. FixIt += attr::getSubjectMatchRuleSpelling(I.first);
  1213. }
  1214. FixIt += ")";
  1215. // Check if we need to remove the range
  1216. PRef.SkipUntil(tok::eof, Parser::StopBeforeMatch);
  1217. FixItRange.setEnd(PRef.getCurToken().getLocation());
  1218. }
  1219. if (FixItRange.getBegin() == FixItRange.getEnd())
  1220. Diagnostic << FixItHint::CreateInsertion(FixItRange.getBegin(), FixIt);
  1221. else
  1222. Diagnostic << FixItHint::CreateReplacement(
  1223. CharSourceRange::getCharRange(FixItRange), FixIt);
  1224. return Diagnostic;
  1225. }
  1226. } // end anonymous namespace
  1227. void Parser::HandlePragmaAttribute() {
  1228. assert(Tok.is(tok::annot_pragma_attribute) &&
  1229. "Expected #pragma attribute annotation token");
  1230. SourceLocation PragmaLoc = Tok.getLocation();
  1231. auto *Info = static_cast<PragmaAttributeInfo *>(Tok.getAnnotationValue());
  1232. if (Info->Action == PragmaAttributeInfo::Pop) {
  1233. ConsumeAnnotationToken();
  1234. Actions.ActOnPragmaAttributePop(PragmaLoc, Info->Namespace);
  1235. return;
  1236. }
  1237. // Parse the actual attribute with its arguments.
  1238. assert((Info->Action == PragmaAttributeInfo::Push ||
  1239. Info->Action == PragmaAttributeInfo::Attribute) &&
  1240. "Unexpected #pragma attribute command");
  1241. if (Info->Action == PragmaAttributeInfo::Push && Info->Tokens.empty()) {
  1242. ConsumeAnnotationToken();
  1243. Actions.ActOnPragmaAttributeEmptyPush(PragmaLoc, Info->Namespace);
  1244. return;
  1245. }
  1246. PP.EnterTokenStream(Info->Tokens, /*DisableMacroExpansion=*/false,
  1247. /*IsReinject=*/false);
  1248. ConsumeAnnotationToken();
  1249. ParsedAttributes &Attrs = Info->Attributes;
  1250. Attrs.clearListOnly();
  1251. auto SkipToEnd = [this]() {
  1252. SkipUntil(tok::eof, StopBeforeMatch);
  1253. ConsumeToken();
  1254. };
  1255. if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
  1256. // Parse the CXX11 style attribute.
  1257. ParseCXX11AttributeSpecifier(Attrs);
  1258. } else if (Tok.is(tok::kw___attribute)) {
  1259. ConsumeToken();
  1260. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
  1261. "attribute"))
  1262. return SkipToEnd();
  1263. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "("))
  1264. return SkipToEnd();
  1265. if (Tok.isNot(tok::identifier)) {
  1266. Diag(Tok, diag::err_pragma_attribute_expected_attribute_name);
  1267. SkipToEnd();
  1268. return;
  1269. }
  1270. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  1271. SourceLocation AttrNameLoc = ConsumeToken();
  1272. if (Tok.isNot(tok::l_paren))
  1273. Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  1274. ParsedAttr::AS_GNU);
  1275. else
  1276. ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, /*EndLoc=*/nullptr,
  1277. /*ScopeName=*/nullptr,
  1278. /*ScopeLoc=*/SourceLocation(), ParsedAttr::AS_GNU,
  1279. /*Declarator=*/nullptr);
  1280. if (ExpectAndConsume(tok::r_paren))
  1281. return SkipToEnd();
  1282. if (ExpectAndConsume(tok::r_paren))
  1283. return SkipToEnd();
  1284. } else if (Tok.is(tok::kw___declspec)) {
  1285. ParseMicrosoftDeclSpecs(Attrs);
  1286. } else {
  1287. Diag(Tok, diag::err_pragma_attribute_expected_attribute_syntax);
  1288. if (Tok.getIdentifierInfo()) {
  1289. // If we suspect that this is an attribute suggest the use of
  1290. // '__attribute__'.
  1291. if (ParsedAttr::getParsedKind(
  1292. Tok.getIdentifierInfo(), /*ScopeName=*/nullptr,
  1293. ParsedAttr::AS_GNU) != ParsedAttr::UnknownAttribute) {
  1294. SourceLocation InsertStartLoc = Tok.getLocation();
  1295. ConsumeToken();
  1296. if (Tok.is(tok::l_paren)) {
  1297. ConsumeAnyToken();
  1298. SkipUntil(tok::r_paren, StopBeforeMatch);
  1299. if (Tok.isNot(tok::r_paren))
  1300. return SkipToEnd();
  1301. }
  1302. Diag(Tok, diag::note_pragma_attribute_use_attribute_kw)
  1303. << FixItHint::CreateInsertion(InsertStartLoc, "__attribute__((")
  1304. << FixItHint::CreateInsertion(Tok.getEndLoc(), "))");
  1305. }
  1306. }
  1307. SkipToEnd();
  1308. return;
  1309. }
  1310. if (Attrs.empty() || Attrs.begin()->isInvalid()) {
  1311. SkipToEnd();
  1312. return;
  1313. }
  1314. // Ensure that we don't have more than one attribute.
  1315. if (Attrs.size() > 1) {
  1316. SourceLocation Loc = Attrs[1].getLoc();
  1317. Diag(Loc, diag::err_pragma_attribute_multiple_attributes);
  1318. SkipToEnd();
  1319. return;
  1320. }
  1321. ParsedAttr &Attribute = *Attrs.begin();
  1322. if (!Attribute.isSupportedByPragmaAttribute()) {
  1323. Diag(PragmaLoc, diag::err_pragma_attribute_unsupported_attribute)
  1324. << Attribute;
  1325. SkipToEnd();
  1326. return;
  1327. }
  1328. // Parse the subject-list.
  1329. if (!TryConsumeToken(tok::comma)) {
  1330. createExpectedAttributeSubjectRulesTokenDiagnostic(
  1331. diag::err_expected, Attribute,
  1332. MissingAttributeSubjectRulesRecoveryPoint::Comma, *this)
  1333. << tok::comma;
  1334. SkipToEnd();
  1335. return;
  1336. }
  1337. if (Tok.isNot(tok::identifier)) {
  1338. createExpectedAttributeSubjectRulesTokenDiagnostic(
  1339. diag::err_pragma_attribute_invalid_subject_set_specifier, Attribute,
  1340. MissingAttributeSubjectRulesRecoveryPoint::ApplyTo, *this);
  1341. SkipToEnd();
  1342. return;
  1343. }
  1344. const IdentifierInfo *II = Tok.getIdentifierInfo();
  1345. if (!II->isStr("apply_to")) {
  1346. createExpectedAttributeSubjectRulesTokenDiagnostic(
  1347. diag::err_pragma_attribute_invalid_subject_set_specifier, Attribute,
  1348. MissingAttributeSubjectRulesRecoveryPoint::ApplyTo, *this);
  1349. SkipToEnd();
  1350. return;
  1351. }
  1352. ConsumeToken();
  1353. if (!TryConsumeToken(tok::equal)) {
  1354. createExpectedAttributeSubjectRulesTokenDiagnostic(
  1355. diag::err_expected, Attribute,
  1356. MissingAttributeSubjectRulesRecoveryPoint::Equals, *this)
  1357. << tok::equal;
  1358. SkipToEnd();
  1359. return;
  1360. }
  1361. attr::ParsedSubjectMatchRuleSet SubjectMatchRules;
  1362. SourceLocation AnyLoc, LastMatchRuleEndLoc;
  1363. if (ParsePragmaAttributeSubjectMatchRuleSet(SubjectMatchRules, AnyLoc,
  1364. LastMatchRuleEndLoc)) {
  1365. SkipToEnd();
  1366. return;
  1367. }
  1368. // Tokens following an ill-formed attribute will remain in the token stream
  1369. // and must be removed.
  1370. if (Tok.isNot(tok::eof)) {
  1371. Diag(Tok, diag::err_pragma_attribute_extra_tokens_after_attribute);
  1372. SkipToEnd();
  1373. return;
  1374. }
  1375. // Consume the eof terminator token.
  1376. ConsumeToken();
  1377. // Handle a mixed push/attribute by desurging to a push, then an attribute.
  1378. if (Info->Action == PragmaAttributeInfo::Push)
  1379. Actions.ActOnPragmaAttributeEmptyPush(PragmaLoc, Info->Namespace);
  1380. Actions.ActOnPragmaAttributeAttribute(Attribute, PragmaLoc,
  1381. std::move(SubjectMatchRules));
  1382. }
  1383. // #pragma GCC visibility comes in two variants:
  1384. // 'push' '(' [visibility] ')'
  1385. // 'pop'
  1386. void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP,
  1387. PragmaIntroducer Introducer,
  1388. Token &VisTok) {
  1389. SourceLocation VisLoc = VisTok.getLocation();
  1390. Token Tok;
  1391. PP.LexUnexpandedToken(Tok);
  1392. const IdentifierInfo *PushPop = Tok.getIdentifierInfo();
  1393. const IdentifierInfo *VisType;
  1394. if (PushPop && PushPop->isStr("pop")) {
  1395. VisType = nullptr;
  1396. } else if (PushPop && PushPop->isStr("push")) {
  1397. PP.LexUnexpandedToken(Tok);
  1398. if (Tok.isNot(tok::l_paren)) {
  1399. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
  1400. << "visibility";
  1401. return;
  1402. }
  1403. PP.LexUnexpandedToken(Tok);
  1404. VisType = Tok.getIdentifierInfo();
  1405. if (!VisType) {
  1406. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
  1407. << "visibility";
  1408. return;
  1409. }
  1410. PP.LexUnexpandedToken(Tok);
  1411. if (Tok.isNot(tok::r_paren)) {
  1412. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
  1413. << "visibility";
  1414. return;
  1415. }
  1416. } else {
  1417. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
  1418. << "visibility";
  1419. return;
  1420. }
  1421. SourceLocation EndLoc = Tok.getLocation();
  1422. PP.LexUnexpandedToken(Tok);
  1423. if (Tok.isNot(tok::eod)) {
  1424. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  1425. << "visibility";
  1426. return;
  1427. }
  1428. auto Toks = std::make_unique<Token[]>(1);
  1429. Toks[0].startToken();
  1430. Toks[0].setKind(tok::annot_pragma_vis);
  1431. Toks[0].setLocation(VisLoc);
  1432. Toks[0].setAnnotationEndLoc(EndLoc);
  1433. Toks[0].setAnnotationValue(
  1434. const_cast<void *>(static_cast<const void *>(VisType)));
  1435. PP.EnterTokenStream(std::move(Toks), 1, /*DisableMacroExpansion=*/true,
  1436. /*IsReinject=*/false);
  1437. }
  1438. // #pragma pack(...) comes in the following delicious flavors:
  1439. // pack '(' [integer] ')'
  1440. // pack '(' 'show' ')'
  1441. // pack '(' ('push' | 'pop') [',' identifier] [, integer] ')'
  1442. void PragmaPackHandler::HandlePragma(Preprocessor &PP,
  1443. PragmaIntroducer Introducer,
  1444. Token &PackTok) {
  1445. SourceLocation PackLoc = PackTok.getLocation();
  1446. Token Tok;
  1447. PP.Lex(Tok);
  1448. if (Tok.isNot(tok::l_paren)) {
  1449. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack";
  1450. return;
  1451. }
  1452. Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
  1453. StringRef SlotLabel;
  1454. Token Alignment;
  1455. Alignment.startToken();
  1456. PP.Lex(Tok);
  1457. if (Tok.is(tok::numeric_constant)) {
  1458. Alignment = Tok;
  1459. PP.Lex(Tok);
  1460. // In MSVC/gcc, #pragma pack(4) sets the alignment without affecting
  1461. // the push/pop stack.
  1462. // In Apple gcc, #pragma pack(4) is equivalent to #pragma pack(push, 4)
  1463. Action =
  1464. PP.getLangOpts().ApplePragmaPack ? Sema::PSK_Push_Set : Sema::PSK_Set;
  1465. } else if (Tok.is(tok::identifier)) {
  1466. const IdentifierInfo *II = Tok.getIdentifierInfo();
  1467. if (II->isStr("show")) {
  1468. Action = Sema::PSK_Show;
  1469. PP.Lex(Tok);
  1470. } else {
  1471. if (II->isStr("push")) {
  1472. Action = Sema::PSK_Push;
  1473. } else if (II->isStr("pop")) {
  1474. Action = Sema::PSK_Pop;
  1475. } else {
  1476. PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "pack";
  1477. return;
  1478. }
  1479. PP.Lex(Tok);
  1480. if (Tok.is(tok::comma)) {
  1481. PP.Lex(Tok);
  1482. if (Tok.is(tok::numeric_constant)) {
  1483. Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
  1484. Alignment = Tok;
  1485. PP.Lex(Tok);
  1486. } else if (Tok.is(tok::identifier)) {
  1487. SlotLabel = Tok.getIdentifierInfo()->getName();
  1488. PP.Lex(Tok);
  1489. if (Tok.is(tok::comma)) {
  1490. PP.Lex(Tok);
  1491. if (Tok.isNot(tok::numeric_constant)) {
  1492. PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
  1493. return;
  1494. }
  1495. Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
  1496. Alignment = Tok;
  1497. PP.Lex(Tok);
  1498. }
  1499. } else {
  1500. PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
  1501. return;
  1502. }
  1503. }
  1504. }
  1505. } else if (PP.getLangOpts().ApplePragmaPack) {
  1506. // In MSVC/gcc, #pragma pack() resets the alignment without affecting
  1507. // the push/pop stack.
  1508. // In Apple gcc #pragma pack() is equivalent to #pragma pack(pop).
  1509. Action = Sema::PSK_Pop;
  1510. }
  1511. if (Tok.isNot(tok::r_paren)) {
  1512. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack";
  1513. return;
  1514. }
  1515. SourceLocation RParenLoc = Tok.getLocation();
  1516. PP.Lex(Tok);
  1517. if (Tok.isNot(tok::eod)) {
  1518. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pack";
  1519. return;
  1520. }
  1521. PragmaPackInfo *Info =
  1522. PP.getPreprocessorAllocator().Allocate<PragmaPackInfo>(1);
  1523. Info->Action = Action;
  1524. Info->SlotLabel = SlotLabel;
  1525. Info->Alignment = Alignment;
  1526. MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
  1527. 1);
  1528. Toks[0].startToken();
  1529. Toks[0].setKind(tok::annot_pragma_pack);
  1530. Toks[0].setLocation(PackLoc);
  1531. Toks[0].setAnnotationEndLoc(RParenLoc);
  1532. Toks[0].setAnnotationValue(static_cast<void*>(Info));
  1533. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1534. /*IsReinject=*/false);
  1535. }
  1536. // #pragma ms_struct on
  1537. // #pragma ms_struct off
  1538. void PragmaMSStructHandler::HandlePragma(Preprocessor &PP,
  1539. PragmaIntroducer Introducer,
  1540. Token &MSStructTok) {
  1541. PragmaMSStructKind Kind = PMSST_OFF;
  1542. Token Tok;
  1543. PP.Lex(Tok);
  1544. if (Tok.isNot(tok::identifier)) {
  1545. PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
  1546. return;
  1547. }
  1548. SourceLocation EndLoc = Tok.getLocation();
  1549. const IdentifierInfo *II = Tok.getIdentifierInfo();
  1550. if (II->isStr("on")) {
  1551. Kind = PMSST_ON;
  1552. PP.Lex(Tok);
  1553. }
  1554. else if (II->isStr("off") || II->isStr("reset"))
  1555. PP.Lex(Tok);
  1556. else {
  1557. PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
  1558. return;
  1559. }
  1560. if (Tok.isNot(tok::eod)) {
  1561. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  1562. << "ms_struct";
  1563. return;
  1564. }
  1565. MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
  1566. 1);
  1567. Toks[0].startToken();
  1568. Toks[0].setKind(tok::annot_pragma_msstruct);
  1569. Toks[0].setLocation(MSStructTok.getLocation());
  1570. Toks[0].setAnnotationEndLoc(EndLoc);
  1571. Toks[0].setAnnotationValue(reinterpret_cast<void*>(
  1572. static_cast<uintptr_t>(Kind)));
  1573. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1574. /*IsReinject=*/false);
  1575. }
  1576. // #pragma clang section bss="abc" data="" rodata="def" text="" relro=""
  1577. void PragmaClangSectionHandler::HandlePragma(Preprocessor &PP,
  1578. PragmaIntroducer Introducer,
  1579. Token &FirstToken) {
  1580. Token Tok;
  1581. auto SecKind = Sema::PragmaClangSectionKind::PCSK_Invalid;
  1582. PP.Lex(Tok); // eat 'section'
  1583. while (Tok.isNot(tok::eod)) {
  1584. if (Tok.isNot(tok::identifier)) {
  1585. PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section";
  1586. return;
  1587. }
  1588. const IdentifierInfo *SecType = Tok.getIdentifierInfo();
  1589. if (SecType->isStr("bss"))
  1590. SecKind = Sema::PragmaClangSectionKind::PCSK_BSS;
  1591. else if (SecType->isStr("data"))
  1592. SecKind = Sema::PragmaClangSectionKind::PCSK_Data;
  1593. else if (SecType->isStr("rodata"))
  1594. SecKind = Sema::PragmaClangSectionKind::PCSK_Rodata;
  1595. else if (SecType->isStr("relro"))
  1596. SecKind = Sema::PragmaClangSectionKind::PCSK_Relro;
  1597. else if (SecType->isStr("text"))
  1598. SecKind = Sema::PragmaClangSectionKind::PCSK_Text;
  1599. else {
  1600. PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section";
  1601. return;
  1602. }
  1603. PP.Lex(Tok); // eat ['bss'|'data'|'rodata'|'text']
  1604. if (Tok.isNot(tok::equal)) {
  1605. PP.Diag(Tok.getLocation(), diag::err_pragma_clang_section_expected_equal) << SecKind;
  1606. return;
  1607. }
  1608. std::string SecName;
  1609. if (!PP.LexStringLiteral(Tok, SecName, "pragma clang section", false))
  1610. return;
  1611. Actions.ActOnPragmaClangSection(Tok.getLocation(),
  1612. (SecName.size()? Sema::PragmaClangSectionAction::PCSA_Set :
  1613. Sema::PragmaClangSectionAction::PCSA_Clear),
  1614. SecKind, SecName);
  1615. }
  1616. }
  1617. // #pragma 'align' '=' {'native','natural','mac68k','power','reset'}
  1618. // #pragma 'options 'align' '=' {'native','natural','mac68k','power','reset'}
  1619. static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok,
  1620. bool IsOptions) {
  1621. Token Tok;
  1622. if (IsOptions) {
  1623. PP.Lex(Tok);
  1624. if (Tok.isNot(tok::identifier) ||
  1625. !Tok.getIdentifierInfo()->isStr("align")) {
  1626. PP.Diag(Tok.getLocation(), diag::warn_pragma_options_expected_align);
  1627. return;
  1628. }
  1629. }
  1630. PP.Lex(Tok);
  1631. if (Tok.isNot(tok::equal)) {
  1632. PP.Diag(Tok.getLocation(), diag::warn_pragma_align_expected_equal)
  1633. << IsOptions;
  1634. return;
  1635. }
  1636. PP.Lex(Tok);
  1637. if (Tok.isNot(tok::identifier)) {
  1638. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
  1639. << (IsOptions ? "options" : "align");
  1640. return;
  1641. }
  1642. Sema::PragmaOptionsAlignKind Kind = Sema::POAK_Natural;
  1643. const IdentifierInfo *II = Tok.getIdentifierInfo();
  1644. if (II->isStr("native"))
  1645. Kind = Sema::POAK_Native;
  1646. else if (II->isStr("natural"))
  1647. Kind = Sema::POAK_Natural;
  1648. else if (II->isStr("packed"))
  1649. Kind = Sema::POAK_Packed;
  1650. else if (II->isStr("power"))
  1651. Kind = Sema::POAK_Power;
  1652. else if (II->isStr("mac68k"))
  1653. Kind = Sema::POAK_Mac68k;
  1654. else if (II->isStr("reset"))
  1655. Kind = Sema::POAK_Reset;
  1656. else {
  1657. PP.Diag(Tok.getLocation(), diag::warn_pragma_align_invalid_option)
  1658. << IsOptions;
  1659. return;
  1660. }
  1661. SourceLocation EndLoc = Tok.getLocation();
  1662. PP.Lex(Tok);
  1663. if (Tok.isNot(tok::eod)) {
  1664. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  1665. << (IsOptions ? "options" : "align");
  1666. return;
  1667. }
  1668. MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
  1669. 1);
  1670. Toks[0].startToken();
  1671. Toks[0].setKind(tok::annot_pragma_align);
  1672. Toks[0].setLocation(FirstTok.getLocation());
  1673. Toks[0].setAnnotationEndLoc(EndLoc);
  1674. Toks[0].setAnnotationValue(reinterpret_cast<void*>(
  1675. static_cast<uintptr_t>(Kind)));
  1676. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1677. /*IsReinject=*/false);
  1678. }
  1679. void PragmaAlignHandler::HandlePragma(Preprocessor &PP,
  1680. PragmaIntroducer Introducer,
  1681. Token &AlignTok) {
  1682. ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false);
  1683. }
  1684. void PragmaOptionsHandler::HandlePragma(Preprocessor &PP,
  1685. PragmaIntroducer Introducer,
  1686. Token &OptionsTok) {
  1687. ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true);
  1688. }
  1689. // #pragma unused(identifier)
  1690. void PragmaUnusedHandler::HandlePragma(Preprocessor &PP,
  1691. PragmaIntroducer Introducer,
  1692. Token &UnusedTok) {
  1693. // FIXME: Should we be expanding macros here? My guess is no.
  1694. SourceLocation UnusedLoc = UnusedTok.getLocation();
  1695. // Lex the left '('.
  1696. Token Tok;
  1697. PP.Lex(Tok);
  1698. if (Tok.isNot(tok::l_paren)) {
  1699. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused";
  1700. return;
  1701. }
  1702. // Lex the declaration reference(s).
  1703. SmallVector<Token, 5> Identifiers;
  1704. SourceLocation RParenLoc;
  1705. bool LexID = true;
  1706. while (true) {
  1707. PP.Lex(Tok);
  1708. if (LexID) {
  1709. if (Tok.is(tok::identifier)) {
  1710. Identifiers.push_back(Tok);
  1711. LexID = false;
  1712. continue;
  1713. }
  1714. // Illegal token!
  1715. PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var);
  1716. return;
  1717. }
  1718. // We are execting a ')' or a ','.
  1719. if (Tok.is(tok::comma)) {
  1720. LexID = true;
  1721. continue;
  1722. }
  1723. if (Tok.is(tok::r_paren)) {
  1724. RParenLoc = Tok.getLocation();
  1725. break;
  1726. }
  1727. // Illegal token!
  1728. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_punc) << "unused";
  1729. return;
  1730. }
  1731. PP.Lex(Tok);
  1732. if (Tok.isNot(tok::eod)) {
  1733. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
  1734. "unused";
  1735. return;
  1736. }
  1737. // Verify that we have a location for the right parenthesis.
  1738. assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'");
  1739. assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments");
  1740. // For each identifier token, insert into the token stream a
  1741. // annot_pragma_unused token followed by the identifier token.
  1742. // This allows us to cache a "#pragma unused" that occurs inside an inline
  1743. // C++ member function.
  1744. MutableArrayRef<Token> Toks(
  1745. PP.getPreprocessorAllocator().Allocate<Token>(2 * Identifiers.size()),
  1746. 2 * Identifiers.size());
  1747. for (unsigned i=0; i != Identifiers.size(); i++) {
  1748. Token &pragmaUnusedTok = Toks[2*i], &idTok = Toks[2*i+1];
  1749. pragmaUnusedTok.startToken();
  1750. pragmaUnusedTok.setKind(tok::annot_pragma_unused);
  1751. pragmaUnusedTok.setLocation(UnusedLoc);
  1752. idTok = Identifiers[i];
  1753. }
  1754. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1755. /*IsReinject=*/false);
  1756. }
  1757. // #pragma weak identifier
  1758. // #pragma weak identifier '=' identifier
  1759. void PragmaWeakHandler::HandlePragma(Preprocessor &PP,
  1760. PragmaIntroducer Introducer,
  1761. Token &WeakTok) {
  1762. SourceLocation WeakLoc = WeakTok.getLocation();
  1763. Token Tok;
  1764. PP.Lex(Tok);
  1765. if (Tok.isNot(tok::identifier)) {
  1766. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak";
  1767. return;
  1768. }
  1769. Token WeakName = Tok;
  1770. bool HasAlias = false;
  1771. Token AliasName;
  1772. PP.Lex(Tok);
  1773. if (Tok.is(tok::equal)) {
  1774. HasAlias = true;
  1775. PP.Lex(Tok);
  1776. if (Tok.isNot(tok::identifier)) {
  1777. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
  1778. << "weak";
  1779. return;
  1780. }
  1781. AliasName = Tok;
  1782. PP.Lex(Tok);
  1783. }
  1784. if (Tok.isNot(tok::eod)) {
  1785. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "weak";
  1786. return;
  1787. }
  1788. if (HasAlias) {
  1789. MutableArrayRef<Token> Toks(
  1790. PP.getPreprocessorAllocator().Allocate<Token>(3), 3);
  1791. Token &pragmaUnusedTok = Toks[0];
  1792. pragmaUnusedTok.startToken();
  1793. pragmaUnusedTok.setKind(tok::annot_pragma_weakalias);
  1794. pragmaUnusedTok.setLocation(WeakLoc);
  1795. pragmaUnusedTok.setAnnotationEndLoc(AliasName.getLocation());
  1796. Toks[1] = WeakName;
  1797. Toks[2] = AliasName;
  1798. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1799. /*IsReinject=*/false);
  1800. } else {
  1801. MutableArrayRef<Token> Toks(
  1802. PP.getPreprocessorAllocator().Allocate<Token>(2), 2);
  1803. Token &pragmaUnusedTok = Toks[0];
  1804. pragmaUnusedTok.startToken();
  1805. pragmaUnusedTok.setKind(tok::annot_pragma_weak);
  1806. pragmaUnusedTok.setLocation(WeakLoc);
  1807. pragmaUnusedTok.setAnnotationEndLoc(WeakLoc);
  1808. Toks[1] = WeakName;
  1809. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1810. /*IsReinject=*/false);
  1811. }
  1812. }
  1813. // #pragma redefine_extname identifier identifier
  1814. void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP,
  1815. PragmaIntroducer Introducer,
  1816. Token &RedefToken) {
  1817. SourceLocation RedefLoc = RedefToken.getLocation();
  1818. Token Tok;
  1819. PP.Lex(Tok);
  1820. if (Tok.isNot(tok::identifier)) {
  1821. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
  1822. "redefine_extname";
  1823. return;
  1824. }
  1825. Token RedefName = Tok;
  1826. PP.Lex(Tok);
  1827. if (Tok.isNot(tok::identifier)) {
  1828. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
  1829. << "redefine_extname";
  1830. return;
  1831. }
  1832. Token AliasName = Tok;
  1833. PP.Lex(Tok);
  1834. if (Tok.isNot(tok::eod)) {
  1835. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
  1836. "redefine_extname";
  1837. return;
  1838. }
  1839. MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(3),
  1840. 3);
  1841. Token &pragmaRedefTok = Toks[0];
  1842. pragmaRedefTok.startToken();
  1843. pragmaRedefTok.setKind(tok::annot_pragma_redefine_extname);
  1844. pragmaRedefTok.setLocation(RedefLoc);
  1845. pragmaRedefTok.setAnnotationEndLoc(AliasName.getLocation());
  1846. Toks[1] = RedefName;
  1847. Toks[2] = AliasName;
  1848. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1849. /*IsReinject=*/false);
  1850. }
  1851. void PragmaFPContractHandler::HandlePragma(Preprocessor &PP,
  1852. PragmaIntroducer Introducer,
  1853. Token &Tok) {
  1854. tok::OnOffSwitch OOS;
  1855. if (PP.LexOnOffSwitch(OOS))
  1856. return;
  1857. MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
  1858. 1);
  1859. Toks[0].startToken();
  1860. Toks[0].setKind(tok::annot_pragma_fp_contract);
  1861. Toks[0].setLocation(Tok.getLocation());
  1862. Toks[0].setAnnotationEndLoc(Tok.getLocation());
  1863. Toks[0].setAnnotationValue(reinterpret_cast<void*>(
  1864. static_cast<uintptr_t>(OOS)));
  1865. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1866. /*IsReinject=*/false);
  1867. }
  1868. void PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP,
  1869. PragmaIntroducer Introducer,
  1870. Token &Tok) {
  1871. PP.LexUnexpandedToken(Tok);
  1872. if (Tok.isNot(tok::identifier)) {
  1873. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
  1874. "OPENCL";
  1875. return;
  1876. }
  1877. IdentifierInfo *Ext = Tok.getIdentifierInfo();
  1878. SourceLocation NameLoc = Tok.getLocation();
  1879. PP.Lex(Tok);
  1880. if (Tok.isNot(tok::colon)) {
  1881. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << Ext;
  1882. return;
  1883. }
  1884. PP.Lex(Tok);
  1885. if (Tok.isNot(tok::identifier)) {
  1886. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate) << 0;
  1887. return;
  1888. }
  1889. IdentifierInfo *Pred = Tok.getIdentifierInfo();
  1890. OpenCLExtState State;
  1891. if (Pred->isStr("enable")) {
  1892. State = Enable;
  1893. } else if (Pred->isStr("disable")) {
  1894. State = Disable;
  1895. } else if (Pred->isStr("begin"))
  1896. State = Begin;
  1897. else if (Pred->isStr("end"))
  1898. State = End;
  1899. else {
  1900. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate)
  1901. << Ext->isStr("all");
  1902. return;
  1903. }
  1904. SourceLocation StateLoc = Tok.getLocation();
  1905. PP.Lex(Tok);
  1906. if (Tok.isNot(tok::eod)) {
  1907. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
  1908. "OPENCL EXTENSION";
  1909. return;
  1910. }
  1911. auto Info = PP.getPreprocessorAllocator().Allocate<OpenCLExtData>(1);
  1912. Info->first = Ext;
  1913. Info->second = State;
  1914. MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
  1915. 1);
  1916. Toks[0].startToken();
  1917. Toks[0].setKind(tok::annot_pragma_opencl_extension);
  1918. Toks[0].setLocation(NameLoc);
  1919. Toks[0].setAnnotationValue(static_cast<void*>(Info));
  1920. Toks[0].setAnnotationEndLoc(StateLoc);
  1921. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1922. /*IsReinject=*/false);
  1923. if (PP.getPPCallbacks())
  1924. PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext,
  1925. StateLoc, State);
  1926. }
  1927. /// Handle '#pragma omp ...' when OpenMP is disabled.
  1928. ///
  1929. void PragmaNoOpenMPHandler::HandlePragma(Preprocessor &PP,
  1930. PragmaIntroducer Introducer,
  1931. Token &FirstTok) {
  1932. if (!PP.getDiagnostics().isIgnored(diag::warn_pragma_omp_ignored,
  1933. FirstTok.getLocation())) {
  1934. PP.Diag(FirstTok, diag::warn_pragma_omp_ignored);
  1935. PP.getDiagnostics().setSeverity(diag::warn_pragma_omp_ignored,
  1936. diag::Severity::Ignored, SourceLocation());
  1937. }
  1938. PP.DiscardUntilEndOfDirective();
  1939. }
  1940. /// Handle '#pragma omp ...' when OpenMP is enabled.
  1941. ///
  1942. void PragmaOpenMPHandler::HandlePragma(Preprocessor &PP,
  1943. PragmaIntroducer Introducer,
  1944. Token &FirstTok) {
  1945. SmallVector<Token, 16> Pragma;
  1946. Token Tok;
  1947. Tok.startToken();
  1948. Tok.setKind(tok::annot_pragma_openmp);
  1949. Tok.setLocation(Introducer.Loc);
  1950. while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) {
  1951. Pragma.push_back(Tok);
  1952. PP.Lex(Tok);
  1953. if (Tok.is(tok::annot_pragma_openmp)) {
  1954. PP.Diag(Tok, diag::err_omp_unexpected_directive) << 0;
  1955. unsigned InnerPragmaCnt = 1;
  1956. while (InnerPragmaCnt != 0) {
  1957. PP.Lex(Tok);
  1958. if (Tok.is(tok::annot_pragma_openmp))
  1959. ++InnerPragmaCnt;
  1960. else if (Tok.is(tok::annot_pragma_openmp_end))
  1961. --InnerPragmaCnt;
  1962. }
  1963. PP.Lex(Tok);
  1964. }
  1965. }
  1966. SourceLocation EodLoc = Tok.getLocation();
  1967. Tok.startToken();
  1968. Tok.setKind(tok::annot_pragma_openmp_end);
  1969. Tok.setLocation(EodLoc);
  1970. Pragma.push_back(Tok);
  1971. auto Toks = std::make_unique<Token[]>(Pragma.size());
  1972. std::copy(Pragma.begin(), Pragma.end(), Toks.get());
  1973. PP.EnterTokenStream(std::move(Toks), Pragma.size(),
  1974. /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
  1975. }
  1976. /// Handle '#pragma pointers_to_members'
  1977. // The grammar for this pragma is as follows:
  1978. //
  1979. // <inheritance model> ::= ('single' | 'multiple' | 'virtual') '_inheritance'
  1980. //
  1981. // #pragma pointers_to_members '(' 'best_case' ')'
  1982. // #pragma pointers_to_members '(' 'full_generality' [',' inheritance-model] ')'
  1983. // #pragma pointers_to_members '(' inheritance-model ')'
  1984. void PragmaMSPointersToMembers::HandlePragma(Preprocessor &PP,
  1985. PragmaIntroducer Introducer,
  1986. Token &Tok) {
  1987. SourceLocation PointersToMembersLoc = Tok.getLocation();
  1988. PP.Lex(Tok);
  1989. if (Tok.isNot(tok::l_paren)) {
  1990. PP.Diag(PointersToMembersLoc, diag::warn_pragma_expected_lparen)
  1991. << "pointers_to_members";
  1992. return;
  1993. }
  1994. PP.Lex(Tok);
  1995. const IdentifierInfo *Arg = Tok.getIdentifierInfo();
  1996. if (!Arg) {
  1997. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
  1998. << "pointers_to_members";
  1999. return;
  2000. }
  2001. PP.Lex(Tok);
  2002. LangOptions::PragmaMSPointersToMembersKind RepresentationMethod;
  2003. if (Arg->isStr("best_case")) {
  2004. RepresentationMethod = LangOptions::PPTMK_BestCase;
  2005. } else {
  2006. if (Arg->isStr("full_generality")) {
  2007. if (Tok.is(tok::comma)) {
  2008. PP.Lex(Tok);
  2009. Arg = Tok.getIdentifierInfo();
  2010. if (!Arg) {
  2011. PP.Diag(Tok.getLocation(),
  2012. diag::err_pragma_pointers_to_members_unknown_kind)
  2013. << Tok.getKind() << /*OnlyInheritanceModels*/ 0;
  2014. return;
  2015. }
  2016. PP.Lex(Tok);
  2017. } else if (Tok.is(tok::r_paren)) {
  2018. // #pragma pointers_to_members(full_generality) implicitly specifies
  2019. // virtual_inheritance.
  2020. Arg = nullptr;
  2021. RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance;
  2022. } else {
  2023. PP.Diag(Tok.getLocation(), diag::err_expected_punc)
  2024. << "full_generality";
  2025. return;
  2026. }
  2027. }
  2028. if (Arg) {
  2029. if (Arg->isStr("single_inheritance")) {
  2030. RepresentationMethod =
  2031. LangOptions::PPTMK_FullGeneralitySingleInheritance;
  2032. } else if (Arg->isStr("multiple_inheritance")) {
  2033. RepresentationMethod =
  2034. LangOptions::PPTMK_FullGeneralityMultipleInheritance;
  2035. } else if (Arg->isStr("virtual_inheritance")) {
  2036. RepresentationMethod =
  2037. LangOptions::PPTMK_FullGeneralityVirtualInheritance;
  2038. } else {
  2039. PP.Diag(Tok.getLocation(),
  2040. diag::err_pragma_pointers_to_members_unknown_kind)
  2041. << Arg << /*HasPointerDeclaration*/ 1;
  2042. return;
  2043. }
  2044. }
  2045. }
  2046. if (Tok.isNot(tok::r_paren)) {
  2047. PP.Diag(Tok.getLocation(), diag::err_expected_rparen_after)
  2048. << (Arg ? Arg->getName() : "full_generality");
  2049. return;
  2050. }
  2051. SourceLocation EndLoc = Tok.getLocation();
  2052. PP.Lex(Tok);
  2053. if (Tok.isNot(tok::eod)) {
  2054. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2055. << "pointers_to_members";
  2056. return;
  2057. }
  2058. Token AnnotTok;
  2059. AnnotTok.startToken();
  2060. AnnotTok.setKind(tok::annot_pragma_ms_pointers_to_members);
  2061. AnnotTok.setLocation(PointersToMembersLoc);
  2062. AnnotTok.setAnnotationEndLoc(EndLoc);
  2063. AnnotTok.setAnnotationValue(
  2064. reinterpret_cast<void *>(static_cast<uintptr_t>(RepresentationMethod)));
  2065. PP.EnterToken(AnnotTok, /*IsReinject=*/true);
  2066. }
  2067. /// Handle '#pragma vtordisp'
  2068. // The grammar for this pragma is as follows:
  2069. //
  2070. // <vtordisp-mode> ::= ('off' | 'on' | '0' | '1' | '2' )
  2071. //
  2072. // #pragma vtordisp '(' ['push' ','] vtordisp-mode ')'
  2073. // #pragma vtordisp '(' 'pop' ')'
  2074. // #pragma vtordisp '(' ')'
  2075. void PragmaMSVtorDisp::HandlePragma(Preprocessor &PP,
  2076. PragmaIntroducer Introducer, Token &Tok) {
  2077. SourceLocation VtorDispLoc = Tok.getLocation();
  2078. PP.Lex(Tok);
  2079. if (Tok.isNot(tok::l_paren)) {
  2080. PP.Diag(VtorDispLoc, diag::warn_pragma_expected_lparen) << "vtordisp";
  2081. return;
  2082. }
  2083. PP.Lex(Tok);
  2084. Sema::PragmaMsStackAction Action = Sema::PSK_Set;
  2085. const IdentifierInfo *II = Tok.getIdentifierInfo();
  2086. if (II) {
  2087. if (II->isStr("push")) {
  2088. // #pragma vtordisp(push, mode)
  2089. PP.Lex(Tok);
  2090. if (Tok.isNot(tok::comma)) {
  2091. PP.Diag(VtorDispLoc, diag::warn_pragma_expected_punc) << "vtordisp";
  2092. return;
  2093. }
  2094. PP.Lex(Tok);
  2095. Action = Sema::PSK_Push_Set;
  2096. // not push, could be on/off
  2097. } else if (II->isStr("pop")) {
  2098. // #pragma vtordisp(pop)
  2099. PP.Lex(Tok);
  2100. Action = Sema::PSK_Pop;
  2101. }
  2102. // not push or pop, could be on/off
  2103. } else {
  2104. if (Tok.is(tok::r_paren)) {
  2105. // #pragma vtordisp()
  2106. Action = Sema::PSK_Reset;
  2107. }
  2108. }
  2109. uint64_t Value = 0;
  2110. if (Action & Sema::PSK_Push || Action & Sema::PSK_Set) {
  2111. const IdentifierInfo *II = Tok.getIdentifierInfo();
  2112. if (II && II->isStr("off")) {
  2113. PP.Lex(Tok);
  2114. Value = 0;
  2115. } else if (II && II->isStr("on")) {
  2116. PP.Lex(Tok);
  2117. Value = 1;
  2118. } else if (Tok.is(tok::numeric_constant) &&
  2119. PP.parseSimpleIntegerLiteral(Tok, Value)) {
  2120. if (Value > 2) {
  2121. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_integer)
  2122. << 0 << 2 << "vtordisp";
  2123. return;
  2124. }
  2125. } else {
  2126. PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action)
  2127. << "vtordisp";
  2128. return;
  2129. }
  2130. }
  2131. // Finish the pragma: ')' $
  2132. if (Tok.isNot(tok::r_paren)) {
  2133. PP.Diag(VtorDispLoc, diag::warn_pragma_expected_rparen) << "vtordisp";
  2134. return;
  2135. }
  2136. SourceLocation EndLoc = Tok.getLocation();
  2137. PP.Lex(Tok);
  2138. if (Tok.isNot(tok::eod)) {
  2139. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2140. << "vtordisp";
  2141. return;
  2142. }
  2143. // Enter the annotation.
  2144. Token AnnotTok;
  2145. AnnotTok.startToken();
  2146. AnnotTok.setKind(tok::annot_pragma_ms_vtordisp);
  2147. AnnotTok.setLocation(VtorDispLoc);
  2148. AnnotTok.setAnnotationEndLoc(EndLoc);
  2149. AnnotTok.setAnnotationValue(reinterpret_cast<void *>(
  2150. static_cast<uintptr_t>((Action << 16) | (Value & 0xFFFF))));
  2151. PP.EnterToken(AnnotTok, /*IsReinject=*/false);
  2152. }
  2153. /// Handle all MS pragmas. Simply forwards the tokens after inserting
  2154. /// an annotation token.
  2155. void PragmaMSPragma::HandlePragma(Preprocessor &PP,
  2156. PragmaIntroducer Introducer, Token &Tok) {
  2157. Token EoF, AnnotTok;
  2158. EoF.startToken();
  2159. EoF.setKind(tok::eof);
  2160. AnnotTok.startToken();
  2161. AnnotTok.setKind(tok::annot_pragma_ms_pragma);
  2162. AnnotTok.setLocation(Tok.getLocation());
  2163. AnnotTok.setAnnotationEndLoc(Tok.getLocation());
  2164. SmallVector<Token, 8> TokenVector;
  2165. // Suck up all of the tokens before the eod.
  2166. for (; Tok.isNot(tok::eod); PP.Lex(Tok)) {
  2167. TokenVector.push_back(Tok);
  2168. AnnotTok.setAnnotationEndLoc(Tok.getLocation());
  2169. }
  2170. // Add a sentinel EoF token to the end of the list.
  2171. TokenVector.push_back(EoF);
  2172. // We must allocate this array with new because EnterTokenStream is going to
  2173. // delete it later.
  2174. auto TokenArray = std::make_unique<Token[]>(TokenVector.size());
  2175. std::copy(TokenVector.begin(), TokenVector.end(), TokenArray.get());
  2176. auto Value = new (PP.getPreprocessorAllocator())
  2177. std::pair<std::unique_ptr<Token[]>, size_t>(std::move(TokenArray),
  2178. TokenVector.size());
  2179. AnnotTok.setAnnotationValue(Value);
  2180. PP.EnterToken(AnnotTok, /*IsReinject*/ false);
  2181. }
  2182. /// Handle the Microsoft \#pragma detect_mismatch extension.
  2183. ///
  2184. /// The syntax is:
  2185. /// \code
  2186. /// #pragma detect_mismatch("name", "value")
  2187. /// \endcode
  2188. /// Where 'name' and 'value' are quoted strings. The values are embedded in
  2189. /// the object file and passed along to the linker. If the linker detects a
  2190. /// mismatch in the object file's values for the given name, a LNK2038 error
  2191. /// is emitted. See MSDN for more details.
  2192. void PragmaDetectMismatchHandler::HandlePragma(Preprocessor &PP,
  2193. PragmaIntroducer Introducer,
  2194. Token &Tok) {
  2195. SourceLocation DetectMismatchLoc = Tok.getLocation();
  2196. PP.Lex(Tok);
  2197. if (Tok.isNot(tok::l_paren)) {
  2198. PP.Diag(DetectMismatchLoc, diag::err_expected) << tok::l_paren;
  2199. return;
  2200. }
  2201. // Read the name to embed, which must be a string literal.
  2202. std::string NameString;
  2203. if (!PP.LexStringLiteral(Tok, NameString,
  2204. "pragma detect_mismatch",
  2205. /*AllowMacroExpansion=*/true))
  2206. return;
  2207. // Read the comma followed by a second string literal.
  2208. std::string ValueString;
  2209. if (Tok.isNot(tok::comma)) {
  2210. PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
  2211. return;
  2212. }
  2213. if (!PP.LexStringLiteral(Tok, ValueString, "pragma detect_mismatch",
  2214. /*AllowMacroExpansion=*/true))
  2215. return;
  2216. if (Tok.isNot(tok::r_paren)) {
  2217. PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
  2218. return;
  2219. }
  2220. PP.Lex(Tok); // Eat the r_paren.
  2221. if (Tok.isNot(tok::eod)) {
  2222. PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
  2223. return;
  2224. }
  2225. // If the pragma is lexically sound, notify any interested PPCallbacks.
  2226. if (PP.getPPCallbacks())
  2227. PP.getPPCallbacks()->PragmaDetectMismatch(DetectMismatchLoc, NameString,
  2228. ValueString);
  2229. Actions.ActOnPragmaDetectMismatch(DetectMismatchLoc, NameString, ValueString);
  2230. }
  2231. /// Handle the microsoft \#pragma comment extension.
  2232. ///
  2233. /// The syntax is:
  2234. /// \code
  2235. /// #pragma comment(linker, "foo")
  2236. /// \endcode
  2237. /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
  2238. /// "foo" is a string, which is fully macro expanded, and permits string
  2239. /// concatenation, embedded escape characters etc. See MSDN for more details.
  2240. void PragmaCommentHandler::HandlePragma(Preprocessor &PP,
  2241. PragmaIntroducer Introducer,
  2242. Token &Tok) {
  2243. SourceLocation CommentLoc = Tok.getLocation();
  2244. PP.Lex(Tok);
  2245. if (Tok.isNot(tok::l_paren)) {
  2246. PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
  2247. return;
  2248. }
  2249. // Read the identifier.
  2250. PP.Lex(Tok);
  2251. if (Tok.isNot(tok::identifier)) {
  2252. PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
  2253. return;
  2254. }
  2255. // Verify that this is one of the 5 whitelisted options.
  2256. IdentifierInfo *II = Tok.getIdentifierInfo();
  2257. PragmaMSCommentKind Kind =
  2258. llvm::StringSwitch<PragmaMSCommentKind>(II->getName())
  2259. .Case("linker", PCK_Linker)
  2260. .Case("lib", PCK_Lib)
  2261. .Case("compiler", PCK_Compiler)
  2262. .Case("exestr", PCK_ExeStr)
  2263. .Case("user", PCK_User)
  2264. .Default(PCK_Unknown);
  2265. if (Kind == PCK_Unknown) {
  2266. PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
  2267. return;
  2268. }
  2269. if (PP.getTargetInfo().getTriple().isOSBinFormatELF() && Kind != PCK_Lib) {
  2270. PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
  2271. << II->getName();
  2272. return;
  2273. }
  2274. // On PS4, issue a warning about any pragma comments other than
  2275. // #pragma comment lib.
  2276. if (PP.getTargetInfo().getTriple().isPS4() && Kind != PCK_Lib) {
  2277. PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
  2278. << II->getName();
  2279. return;
  2280. }
  2281. // Read the optional string if present.
  2282. PP.Lex(Tok);
  2283. std::string ArgumentString;
  2284. if (Tok.is(tok::comma) && !PP.LexStringLiteral(Tok, ArgumentString,
  2285. "pragma comment",
  2286. /*AllowMacroExpansion=*/true))
  2287. return;
  2288. // FIXME: warn that 'exestr' is deprecated.
  2289. // FIXME: If the kind is "compiler" warn if the string is present (it is
  2290. // ignored).
  2291. // The MSDN docs say that "lib" and "linker" require a string and have a short
  2292. // whitelist of linker options they support, but in practice MSVC doesn't
  2293. // issue a diagnostic. Therefore neither does clang.
  2294. if (Tok.isNot(tok::r_paren)) {
  2295. PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
  2296. return;
  2297. }
  2298. PP.Lex(Tok); // eat the r_paren.
  2299. if (Tok.isNot(tok::eod)) {
  2300. PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
  2301. return;
  2302. }
  2303. // If the pragma is lexically sound, notify any interested PPCallbacks.
  2304. if (PP.getPPCallbacks())
  2305. PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString);
  2306. Actions.ActOnPragmaMSComment(CommentLoc, Kind, ArgumentString);
  2307. }
  2308. // #pragma clang optimize off
  2309. // #pragma clang optimize on
  2310. void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP,
  2311. PragmaIntroducer Introducer,
  2312. Token &FirstToken) {
  2313. Token Tok;
  2314. PP.Lex(Tok);
  2315. if (Tok.is(tok::eod)) {
  2316. PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
  2317. << "clang optimize" << /*Expected=*/true << "'on' or 'off'";
  2318. return;
  2319. }
  2320. if (Tok.isNot(tok::identifier)) {
  2321. PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
  2322. << PP.getSpelling(Tok);
  2323. return;
  2324. }
  2325. const IdentifierInfo *II = Tok.getIdentifierInfo();
  2326. // The only accepted values are 'on' or 'off'.
  2327. bool IsOn = false;
  2328. if (II->isStr("on")) {
  2329. IsOn = true;
  2330. } else if (!II->isStr("off")) {
  2331. PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
  2332. << PP.getSpelling(Tok);
  2333. return;
  2334. }
  2335. PP.Lex(Tok);
  2336. if (Tok.isNot(tok::eod)) {
  2337. PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument)
  2338. << PP.getSpelling(Tok);
  2339. return;
  2340. }
  2341. Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());
  2342. }
  2343. namespace {
  2344. /// Used as the annotation value for tok::annot_pragma_fp.
  2345. struct TokFPAnnotValue {
  2346. enum FlagKinds { Contract };
  2347. enum FlagValues { On, Off, Fast };
  2348. FlagKinds FlagKind;
  2349. FlagValues FlagValue;
  2350. };
  2351. } // end anonymous namespace
  2352. void PragmaFPHandler::HandlePragma(Preprocessor &PP,
  2353. PragmaIntroducer Introducer, Token &Tok) {
  2354. // fp
  2355. Token PragmaName = Tok;
  2356. SmallVector<Token, 1> TokenList;
  2357. PP.Lex(Tok);
  2358. if (Tok.isNot(tok::identifier)) {
  2359. PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
  2360. << /*MissingOption=*/true << "";
  2361. return;
  2362. }
  2363. while (Tok.is(tok::identifier)) {
  2364. IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
  2365. auto FlagKind =
  2366. llvm::StringSwitch<llvm::Optional<TokFPAnnotValue::FlagKinds>>(
  2367. OptionInfo->getName())
  2368. .Case("contract", TokFPAnnotValue::Contract)
  2369. .Default(None);
  2370. if (!FlagKind) {
  2371. PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
  2372. << /*MissingOption=*/false << OptionInfo;
  2373. return;
  2374. }
  2375. PP.Lex(Tok);
  2376. // Read '('
  2377. if (Tok.isNot(tok::l_paren)) {
  2378. PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
  2379. return;
  2380. }
  2381. PP.Lex(Tok);
  2382. if (Tok.isNot(tok::identifier)) {
  2383. PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
  2384. << PP.getSpelling(Tok) << OptionInfo->getName();
  2385. return;
  2386. }
  2387. const IdentifierInfo *II = Tok.getIdentifierInfo();
  2388. auto FlagValue =
  2389. llvm::StringSwitch<llvm::Optional<TokFPAnnotValue::FlagValues>>(
  2390. II->getName())
  2391. .Case("on", TokFPAnnotValue::On)
  2392. .Case("off", TokFPAnnotValue::Off)
  2393. .Case("fast", TokFPAnnotValue::Fast)
  2394. .Default(llvm::None);
  2395. if (!FlagValue) {
  2396. PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
  2397. << PP.getSpelling(Tok) << OptionInfo->getName();
  2398. return;
  2399. }
  2400. PP.Lex(Tok);
  2401. // Read ')'
  2402. if (Tok.isNot(tok::r_paren)) {
  2403. PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
  2404. return;
  2405. }
  2406. PP.Lex(Tok);
  2407. auto *AnnotValue = new (PP.getPreprocessorAllocator())
  2408. TokFPAnnotValue{*FlagKind, *FlagValue};
  2409. // Generate the loop hint token.
  2410. Token FPTok;
  2411. FPTok.startToken();
  2412. FPTok.setKind(tok::annot_pragma_fp);
  2413. FPTok.setLocation(PragmaName.getLocation());
  2414. FPTok.setAnnotationEndLoc(PragmaName.getLocation());
  2415. FPTok.setAnnotationValue(reinterpret_cast<void *>(AnnotValue));
  2416. TokenList.push_back(FPTok);
  2417. }
  2418. if (Tok.isNot(tok::eod)) {
  2419. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2420. << "clang fp";
  2421. return;
  2422. }
  2423. auto TokenArray = std::make_unique<Token[]>(TokenList.size());
  2424. std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
  2425. PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
  2426. /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
  2427. }
  2428. void Parser::HandlePragmaFP() {
  2429. assert(Tok.is(tok::annot_pragma_fp));
  2430. auto *AnnotValue =
  2431. reinterpret_cast<TokFPAnnotValue *>(Tok.getAnnotationValue());
  2432. LangOptions::FPContractModeKind FPC;
  2433. switch (AnnotValue->FlagValue) {
  2434. case TokFPAnnotValue::On:
  2435. FPC = LangOptions::FPC_On;
  2436. break;
  2437. case TokFPAnnotValue::Fast:
  2438. FPC = LangOptions::FPC_Fast;
  2439. break;
  2440. case TokFPAnnotValue::Off:
  2441. FPC = LangOptions::FPC_Off;
  2442. break;
  2443. }
  2444. Actions.ActOnPragmaFPContract(FPC);
  2445. ConsumeAnnotationToken();
  2446. }
  2447. /// Parses loop or unroll pragma hint value and fills in Info.
  2448. static bool ParseLoopHintValue(Preprocessor &PP, Token &Tok, Token PragmaName,
  2449. Token Option, bool ValueInParens,
  2450. PragmaLoopHintInfo &Info) {
  2451. SmallVector<Token, 1> ValueList;
  2452. int OpenParens = ValueInParens ? 1 : 0;
  2453. // Read constant expression.
  2454. while (Tok.isNot(tok::eod)) {
  2455. if (Tok.is(tok::l_paren))
  2456. OpenParens++;
  2457. else if (Tok.is(tok::r_paren)) {
  2458. OpenParens--;
  2459. if (OpenParens == 0 && ValueInParens)
  2460. break;
  2461. }
  2462. ValueList.push_back(Tok);
  2463. PP.Lex(Tok);
  2464. }
  2465. if (ValueInParens) {
  2466. // Read ')'
  2467. if (Tok.isNot(tok::r_paren)) {
  2468. PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
  2469. return true;
  2470. }
  2471. PP.Lex(Tok);
  2472. }
  2473. Token EOFTok;
  2474. EOFTok.startToken();
  2475. EOFTok.setKind(tok::eof);
  2476. EOFTok.setLocation(Tok.getLocation());
  2477. ValueList.push_back(EOFTok); // Terminates expression for parsing.
  2478. Info.Toks = llvm::makeArrayRef(ValueList).copy(PP.getPreprocessorAllocator());
  2479. Info.PragmaName = PragmaName;
  2480. Info.Option = Option;
  2481. return false;
  2482. }
  2483. /// Handle the \#pragma clang loop directive.
  2484. /// #pragma clang 'loop' loop-hints
  2485. ///
  2486. /// loop-hints:
  2487. /// loop-hint loop-hints[opt]
  2488. ///
  2489. /// loop-hint:
  2490. /// 'vectorize' '(' loop-hint-keyword ')'
  2491. /// 'interleave' '(' loop-hint-keyword ')'
  2492. /// 'unroll' '(' unroll-hint-keyword ')'
  2493. /// 'vectorize_predicate' '(' loop-hint-keyword ')'
  2494. /// 'vectorize_width' '(' loop-hint-value ')'
  2495. /// 'interleave_count' '(' loop-hint-value ')'
  2496. /// 'unroll_count' '(' loop-hint-value ')'
  2497. /// 'pipeline' '(' disable ')'
  2498. /// 'pipeline_initiation_interval' '(' loop-hint-value ')'
  2499. ///
  2500. /// loop-hint-keyword:
  2501. /// 'enable'
  2502. /// 'disable'
  2503. /// 'assume_safety'
  2504. ///
  2505. /// unroll-hint-keyword:
  2506. /// 'enable'
  2507. /// 'disable'
  2508. /// 'full'
  2509. ///
  2510. /// loop-hint-value:
  2511. /// constant-expression
  2512. ///
  2513. /// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to
  2514. /// try vectorizing the instructions of the loop it precedes. Specifying
  2515. /// interleave(enable) or interleave_count(_value_) instructs llvm to try
  2516. /// interleaving multiple iterations of the loop it precedes. The width of the
  2517. /// vector instructions is specified by vectorize_width() and the number of
  2518. /// interleaved loop iterations is specified by interleave_count(). Specifying a
  2519. /// value of 1 effectively disables vectorization/interleaving, even if it is
  2520. /// possible and profitable, and 0 is invalid. The loop vectorizer currently
  2521. /// only works on inner loops.
  2522. ///
  2523. /// The unroll and unroll_count directives control the concatenation
  2524. /// unroller. Specifying unroll(enable) instructs llvm to unroll the loop
  2525. /// completely if the trip count is known at compile time and unroll partially
  2526. /// if the trip count is not known. Specifying unroll(full) is similar to
  2527. /// unroll(enable) but will unroll the loop only if the trip count is known at
  2528. /// compile time. Specifying unroll(disable) disables unrolling for the
  2529. /// loop. Specifying unroll_count(_value_) instructs llvm to try to unroll the
  2530. /// loop the number of times indicated by the value.
  2531. void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP,
  2532. PragmaIntroducer Introducer,
  2533. Token &Tok) {
  2534. // Incoming token is "loop" from "#pragma clang loop".
  2535. Token PragmaName = Tok;
  2536. SmallVector<Token, 1> TokenList;
  2537. // Lex the optimization option and verify it is an identifier.
  2538. PP.Lex(Tok);
  2539. if (Tok.isNot(tok::identifier)) {
  2540. PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
  2541. << /*MissingOption=*/true << "";
  2542. return;
  2543. }
  2544. while (Tok.is(tok::identifier)) {
  2545. Token Option = Tok;
  2546. IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
  2547. bool OptionValid = llvm::StringSwitch<bool>(OptionInfo->getName())
  2548. .Case("vectorize", true)
  2549. .Case("interleave", true)
  2550. .Case("unroll", true)
  2551. .Case("distribute", true)
  2552. .Case("vectorize_predicate", true)
  2553. .Case("vectorize_width", true)
  2554. .Case("interleave_count", true)
  2555. .Case("unroll_count", true)
  2556. .Case("pipeline", true)
  2557. .Case("pipeline_initiation_interval", true)
  2558. .Default(false);
  2559. if (!OptionValid) {
  2560. PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
  2561. << /*MissingOption=*/false << OptionInfo;
  2562. return;
  2563. }
  2564. PP.Lex(Tok);
  2565. // Read '('
  2566. if (Tok.isNot(tok::l_paren)) {
  2567. PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
  2568. return;
  2569. }
  2570. PP.Lex(Tok);
  2571. auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
  2572. if (ParseLoopHintValue(PP, Tok, PragmaName, Option, /*ValueInParens=*/true,
  2573. *Info))
  2574. return;
  2575. // Generate the loop hint token.
  2576. Token LoopHintTok;
  2577. LoopHintTok.startToken();
  2578. LoopHintTok.setKind(tok::annot_pragma_loop_hint);
  2579. LoopHintTok.setLocation(PragmaName.getLocation());
  2580. LoopHintTok.setAnnotationEndLoc(PragmaName.getLocation());
  2581. LoopHintTok.setAnnotationValue(static_cast<void *>(Info));
  2582. TokenList.push_back(LoopHintTok);
  2583. }
  2584. if (Tok.isNot(tok::eod)) {
  2585. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2586. << "clang loop";
  2587. return;
  2588. }
  2589. auto TokenArray = std::make_unique<Token[]>(TokenList.size());
  2590. std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
  2591. PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
  2592. /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
  2593. }
  2594. /// Handle the loop unroll optimization pragmas.
  2595. /// #pragma unroll
  2596. /// #pragma unroll unroll-hint-value
  2597. /// #pragma unroll '(' unroll-hint-value ')'
  2598. /// #pragma nounroll
  2599. /// #pragma unroll_and_jam
  2600. /// #pragma unroll_and_jam unroll-hint-value
  2601. /// #pragma unroll_and_jam '(' unroll-hint-value ')'
  2602. /// #pragma nounroll_and_jam
  2603. ///
  2604. /// unroll-hint-value:
  2605. /// constant-expression
  2606. ///
  2607. /// Loop unrolling hints can be specified with '#pragma unroll' or
  2608. /// '#pragma nounroll'. '#pragma unroll' can take a numeric argument optionally
  2609. /// contained in parentheses. With no argument the directive instructs llvm to
  2610. /// try to unroll the loop completely. A positive integer argument can be
  2611. /// specified to indicate the number of times the loop should be unrolled. To
  2612. /// maximize compatibility with other compilers the unroll count argument can be
  2613. /// specified with or without parentheses. Specifying, '#pragma nounroll'
  2614. /// disables unrolling of the loop.
  2615. void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP,
  2616. PragmaIntroducer Introducer,
  2617. Token &Tok) {
  2618. // Incoming token is "unroll" for "#pragma unroll", or "nounroll" for
  2619. // "#pragma nounroll".
  2620. Token PragmaName = Tok;
  2621. PP.Lex(Tok);
  2622. auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
  2623. if (Tok.is(tok::eod)) {
  2624. // nounroll or unroll pragma without an argument.
  2625. Info->PragmaName = PragmaName;
  2626. Info->Option.startToken();
  2627. } else if (PragmaName.getIdentifierInfo()->getName() == "nounroll" ||
  2628. PragmaName.getIdentifierInfo()->getName() == "nounroll_and_jam") {
  2629. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2630. << PragmaName.getIdentifierInfo()->getName();
  2631. return;
  2632. } else {
  2633. // Unroll pragma with an argument: "#pragma unroll N" or
  2634. // "#pragma unroll(N)".
  2635. // Read '(' if it exists.
  2636. bool ValueInParens = Tok.is(tok::l_paren);
  2637. if (ValueInParens)
  2638. PP.Lex(Tok);
  2639. Token Option;
  2640. Option.startToken();
  2641. if (ParseLoopHintValue(PP, Tok, PragmaName, Option, ValueInParens, *Info))
  2642. return;
  2643. // In CUDA, the argument to '#pragma unroll' should not be contained in
  2644. // parentheses.
  2645. if (PP.getLangOpts().CUDA && ValueInParens)
  2646. PP.Diag(Info->Toks[0].getLocation(),
  2647. diag::warn_pragma_unroll_cuda_value_in_parens);
  2648. if (Tok.isNot(tok::eod)) {
  2649. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2650. << "unroll";
  2651. return;
  2652. }
  2653. }
  2654. // Generate the hint token.
  2655. auto TokenArray = std::make_unique<Token[]>(1);
  2656. TokenArray[0].startToken();
  2657. TokenArray[0].setKind(tok::annot_pragma_loop_hint);
  2658. TokenArray[0].setLocation(PragmaName.getLocation());
  2659. TokenArray[0].setAnnotationEndLoc(PragmaName.getLocation());
  2660. TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
  2661. PP.EnterTokenStream(std::move(TokenArray), 1,
  2662. /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
  2663. }
  2664. /// Handle the Microsoft \#pragma intrinsic extension.
  2665. ///
  2666. /// The syntax is:
  2667. /// \code
  2668. /// #pragma intrinsic(memset)
  2669. /// #pragma intrinsic(strlen, memcpy)
  2670. /// \endcode
  2671. ///
  2672. /// Pragma intrisic tells the compiler to use a builtin version of the
  2673. /// function. Clang does it anyway, so the pragma doesn't really do anything.
  2674. /// Anyway, we emit a warning if the function specified in \#pragma intrinsic
  2675. /// isn't an intrinsic in clang and suggest to include intrin.h.
  2676. void PragmaMSIntrinsicHandler::HandlePragma(Preprocessor &PP,
  2677. PragmaIntroducer Introducer,
  2678. Token &Tok) {
  2679. PP.Lex(Tok);
  2680. if (Tok.isNot(tok::l_paren)) {
  2681. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
  2682. << "intrinsic";
  2683. return;
  2684. }
  2685. PP.Lex(Tok);
  2686. bool SuggestIntrinH = !PP.isMacroDefined("__INTRIN_H");
  2687. while (Tok.is(tok::identifier)) {
  2688. IdentifierInfo *II = Tok.getIdentifierInfo();
  2689. if (!II->getBuiltinID())
  2690. PP.Diag(Tok.getLocation(), diag::warn_pragma_intrinsic_builtin)
  2691. << II << SuggestIntrinH;
  2692. PP.Lex(Tok);
  2693. if (Tok.isNot(tok::comma))
  2694. break;
  2695. PP.Lex(Tok);
  2696. }
  2697. if (Tok.isNot(tok::r_paren)) {
  2698. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
  2699. << "intrinsic";
  2700. return;
  2701. }
  2702. PP.Lex(Tok);
  2703. if (Tok.isNot(tok::eod))
  2704. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2705. << "intrinsic";
  2706. }
  2707. // #pragma optimize("gsty", on|off)
  2708. void PragmaMSOptimizeHandler::HandlePragma(Preprocessor &PP,
  2709. PragmaIntroducer Introducer,
  2710. Token &Tok) {
  2711. SourceLocation StartLoc = Tok.getLocation();
  2712. PP.Lex(Tok);
  2713. if (Tok.isNot(tok::l_paren)) {
  2714. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "optimize";
  2715. return;
  2716. }
  2717. PP.Lex(Tok);
  2718. if (Tok.isNot(tok::string_literal)) {
  2719. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_string) << "optimize";
  2720. return;
  2721. }
  2722. // We could syntax check the string but it's probably not worth the effort.
  2723. PP.Lex(Tok);
  2724. if (Tok.isNot(tok::comma)) {
  2725. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_comma) << "optimize";
  2726. return;
  2727. }
  2728. PP.Lex(Tok);
  2729. if (Tok.is(tok::eod) || Tok.is(tok::r_paren)) {
  2730. PP.Diag(Tok.getLocation(), diag::warn_pragma_missing_argument)
  2731. << "optimize" << /*Expected=*/true << "'on' or 'off'";
  2732. return;
  2733. }
  2734. IdentifierInfo *II = Tok.getIdentifierInfo();
  2735. if (!II || (!II->isStr("on") && !II->isStr("off"))) {
  2736. PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_argument)
  2737. << PP.getSpelling(Tok) << "optimize" << /*Expected=*/true
  2738. << "'on' or 'off'";
  2739. return;
  2740. }
  2741. PP.Lex(Tok);
  2742. if (Tok.isNot(tok::r_paren)) {
  2743. PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "optimize";
  2744. return;
  2745. }
  2746. PP.Lex(Tok);
  2747. if (Tok.isNot(tok::eod)) {
  2748. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2749. << "optimize";
  2750. return;
  2751. }
  2752. PP.Diag(StartLoc, diag::warn_pragma_optimize);
  2753. }
  2754. void PragmaForceCUDAHostDeviceHandler::HandlePragma(
  2755. Preprocessor &PP, PragmaIntroducer Introducer, Token &Tok) {
  2756. Token FirstTok = Tok;
  2757. PP.Lex(Tok);
  2758. IdentifierInfo *Info = Tok.getIdentifierInfo();
  2759. if (!Info || (!Info->isStr("begin") && !Info->isStr("end"))) {
  2760. PP.Diag(FirstTok.getLocation(),
  2761. diag::warn_pragma_force_cuda_host_device_bad_arg);
  2762. return;
  2763. }
  2764. if (Info->isStr("begin"))
  2765. Actions.PushForceCUDAHostDevice();
  2766. else if (!Actions.PopForceCUDAHostDevice())
  2767. PP.Diag(FirstTok.getLocation(),
  2768. diag::err_pragma_cannot_end_force_cuda_host_device);
  2769. PP.Lex(Tok);
  2770. if (!Tok.is(tok::eod))
  2771. PP.Diag(FirstTok.getLocation(),
  2772. diag::warn_pragma_force_cuda_host_device_bad_arg);
  2773. }
  2774. /// Handle the #pragma clang attribute directive.
  2775. ///
  2776. /// The syntax is:
  2777. /// \code
  2778. /// #pragma clang attribute push (attribute, subject-set)
  2779. /// #pragma clang attribute push
  2780. /// #pragma clang attribute (attribute, subject-set)
  2781. /// #pragma clang attribute pop
  2782. /// \endcode
  2783. ///
  2784. /// There are also 'namespace' variants of push and pop directives. The bare
  2785. /// '#pragma clang attribute (attribute, subject-set)' version doesn't require a
  2786. /// namespace, since it always applies attributes to the most recently pushed
  2787. /// group, regardless of namespace.
  2788. /// \code
  2789. /// #pragma clang attribute namespace.push (attribute, subject-set)
  2790. /// #pragma clang attribute namespace.push
  2791. /// #pragma clang attribute namespace.pop
  2792. /// \endcode
  2793. ///
  2794. /// The subject-set clause defines the set of declarations which receive the
  2795. /// attribute. Its exact syntax is described in the LanguageExtensions document
  2796. /// in Clang's documentation.
  2797. ///
  2798. /// This directive instructs the compiler to begin/finish applying the specified
  2799. /// attribute to the set of attribute-specific declarations in the active range
  2800. /// of the pragma.
  2801. void PragmaAttributeHandler::HandlePragma(Preprocessor &PP,
  2802. PragmaIntroducer Introducer,
  2803. Token &FirstToken) {
  2804. Token Tok;
  2805. PP.Lex(Tok);
  2806. auto *Info = new (PP.getPreprocessorAllocator())
  2807. PragmaAttributeInfo(AttributesForPragmaAttribute);
  2808. // Parse the optional namespace followed by a period.
  2809. if (Tok.is(tok::identifier)) {
  2810. IdentifierInfo *II = Tok.getIdentifierInfo();
  2811. if (!II->isStr("push") && !II->isStr("pop")) {
  2812. Info->Namespace = II;
  2813. PP.Lex(Tok);
  2814. if (!Tok.is(tok::period)) {
  2815. PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_expected_period)
  2816. << II;
  2817. return;
  2818. }
  2819. PP.Lex(Tok);
  2820. }
  2821. }
  2822. if (!Tok.isOneOf(tok::identifier, tok::l_paren)) {
  2823. PP.Diag(Tok.getLocation(),
  2824. diag::err_pragma_attribute_expected_push_pop_paren);
  2825. return;
  2826. }
  2827. // Determine what action this pragma clang attribute represents.
  2828. if (Tok.is(tok::l_paren)) {
  2829. if (Info->Namespace) {
  2830. PP.Diag(Tok.getLocation(),
  2831. diag::err_pragma_attribute_namespace_on_attribute);
  2832. PP.Diag(Tok.getLocation(),
  2833. diag::note_pragma_attribute_namespace_on_attribute);
  2834. return;
  2835. }
  2836. Info->Action = PragmaAttributeInfo::Attribute;
  2837. } else {
  2838. const IdentifierInfo *II = Tok.getIdentifierInfo();
  2839. if (II->isStr("push"))
  2840. Info->Action = PragmaAttributeInfo::Push;
  2841. else if (II->isStr("pop"))
  2842. Info->Action = PragmaAttributeInfo::Pop;
  2843. else {
  2844. PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_invalid_argument)
  2845. << PP.getSpelling(Tok);
  2846. return;
  2847. }
  2848. PP.Lex(Tok);
  2849. }
  2850. // Parse the actual attribute.
  2851. if ((Info->Action == PragmaAttributeInfo::Push && Tok.isNot(tok::eod)) ||
  2852. Info->Action == PragmaAttributeInfo::Attribute) {
  2853. if (Tok.isNot(tok::l_paren)) {
  2854. PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
  2855. return;
  2856. }
  2857. PP.Lex(Tok);
  2858. // Lex the attribute tokens.
  2859. SmallVector<Token, 16> AttributeTokens;
  2860. int OpenParens = 1;
  2861. while (Tok.isNot(tok::eod)) {
  2862. if (Tok.is(tok::l_paren))
  2863. OpenParens++;
  2864. else if (Tok.is(tok::r_paren)) {
  2865. OpenParens--;
  2866. if (OpenParens == 0)
  2867. break;
  2868. }
  2869. AttributeTokens.push_back(Tok);
  2870. PP.Lex(Tok);
  2871. }
  2872. if (AttributeTokens.empty()) {
  2873. PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_expected_attribute);
  2874. return;
  2875. }
  2876. if (Tok.isNot(tok::r_paren)) {
  2877. PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
  2878. return;
  2879. }
  2880. SourceLocation EndLoc = Tok.getLocation();
  2881. PP.Lex(Tok);
  2882. // Terminate the attribute for parsing.
  2883. Token EOFTok;
  2884. EOFTok.startToken();
  2885. EOFTok.setKind(tok::eof);
  2886. EOFTok.setLocation(EndLoc);
  2887. AttributeTokens.push_back(EOFTok);
  2888. Info->Tokens =
  2889. llvm::makeArrayRef(AttributeTokens).copy(PP.getPreprocessorAllocator());
  2890. }
  2891. if (Tok.isNot(tok::eod))
  2892. PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
  2893. << "clang attribute";
  2894. // Generate the annotated pragma token.
  2895. auto TokenArray = std::make_unique<Token[]>(1);
  2896. TokenArray[0].startToken();
  2897. TokenArray[0].setKind(tok::annot_pragma_attribute);
  2898. TokenArray[0].setLocation(FirstToken.getLocation());
  2899. TokenArray[0].setAnnotationEndLoc(FirstToken.getLocation());
  2900. TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
  2901. PP.EnterTokenStream(std::move(TokenArray), 1,
  2902. /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
  2903. }