ParseOpenMP.cpp 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720
  1. //===--- ParseOpenMP.cpp - OpenMP directives 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. /// \file
  9. /// This file implements parsing of all OpenMP directives and clauses.
  10. ///
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/OpenMPClause.h"
  14. #include "clang/AST/StmtOpenMP.h"
  15. #include "clang/Basic/OpenMPKinds.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Basic/TokenKinds.h"
  18. #include "clang/Parse/ParseDiagnostic.h"
  19. #include "clang/Parse/Parser.h"
  20. #include "clang/Parse/RAIIObjectsForParser.h"
  21. #include "clang/Sema/Scope.h"
  22. #include "llvm/ADT/PointerIntPair.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. #include "llvm/ADT/UniqueVector.h"
  25. #include "llvm/Frontend/OpenMP/OMPAssume.h"
  26. #include "llvm/Frontend/OpenMP/OMPContext.h"
  27. #include <optional>
  28. using namespace clang;
  29. using namespace llvm::omp;
  30. //===----------------------------------------------------------------------===//
  31. // OpenMP declarative directives.
  32. //===----------------------------------------------------------------------===//
  33. namespace {
  34. enum OpenMPDirectiveKindEx {
  35. OMPD_cancellation = llvm::omp::Directive_enumSize + 1,
  36. OMPD_data,
  37. OMPD_declare,
  38. OMPD_end,
  39. OMPD_end_declare,
  40. OMPD_enter,
  41. OMPD_exit,
  42. OMPD_point,
  43. OMPD_reduction,
  44. OMPD_target_enter,
  45. OMPD_target_exit,
  46. OMPD_update,
  47. OMPD_distribute_parallel,
  48. OMPD_teams_distribute_parallel,
  49. OMPD_target_teams_distribute_parallel,
  50. OMPD_mapper,
  51. OMPD_variant,
  52. OMPD_begin,
  53. OMPD_begin_declare,
  54. };
  55. // Helper to unify the enum class OpenMPDirectiveKind with its extension
  56. // the OpenMPDirectiveKindEx enum which allows to use them together as if they
  57. // are unsigned values.
  58. struct OpenMPDirectiveKindExWrapper {
  59. OpenMPDirectiveKindExWrapper(unsigned Value) : Value(Value) {}
  60. OpenMPDirectiveKindExWrapper(OpenMPDirectiveKind DK) : Value(unsigned(DK)) {}
  61. bool operator==(OpenMPDirectiveKindExWrapper V) const {
  62. return Value == V.Value;
  63. }
  64. bool operator!=(OpenMPDirectiveKindExWrapper V) const {
  65. return Value != V.Value;
  66. }
  67. bool operator==(OpenMPDirectiveKind V) const { return Value == unsigned(V); }
  68. bool operator!=(OpenMPDirectiveKind V) const { return Value != unsigned(V); }
  69. bool operator<(OpenMPDirectiveKind V) const { return Value < unsigned(V); }
  70. operator unsigned() const { return Value; }
  71. operator OpenMPDirectiveKind() const { return OpenMPDirectiveKind(Value); }
  72. unsigned Value;
  73. };
  74. class DeclDirectiveListParserHelper final {
  75. SmallVector<Expr *, 4> Identifiers;
  76. Parser *P;
  77. OpenMPDirectiveKind Kind;
  78. public:
  79. DeclDirectiveListParserHelper(Parser *P, OpenMPDirectiveKind Kind)
  80. : P(P), Kind(Kind) {}
  81. void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
  82. ExprResult Res = P->getActions().ActOnOpenMPIdExpression(
  83. P->getCurScope(), SS, NameInfo, Kind);
  84. if (Res.isUsable())
  85. Identifiers.push_back(Res.get());
  86. }
  87. llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
  88. };
  89. } // namespace
  90. // Map token string to extended OMP token kind that are
  91. // OpenMPDirectiveKind + OpenMPDirectiveKindEx.
  92. static unsigned getOpenMPDirectiveKindEx(StringRef S) {
  93. OpenMPDirectiveKindExWrapper DKind = getOpenMPDirectiveKind(S);
  94. if (DKind != OMPD_unknown)
  95. return DKind;
  96. return llvm::StringSwitch<OpenMPDirectiveKindExWrapper>(S)
  97. .Case("cancellation", OMPD_cancellation)
  98. .Case("data", OMPD_data)
  99. .Case("declare", OMPD_declare)
  100. .Case("end", OMPD_end)
  101. .Case("enter", OMPD_enter)
  102. .Case("exit", OMPD_exit)
  103. .Case("point", OMPD_point)
  104. .Case("reduction", OMPD_reduction)
  105. .Case("update", OMPD_update)
  106. .Case("mapper", OMPD_mapper)
  107. .Case("variant", OMPD_variant)
  108. .Case("begin", OMPD_begin)
  109. .Default(OMPD_unknown);
  110. }
  111. static OpenMPDirectiveKindExWrapper parseOpenMPDirectiveKind(Parser &P) {
  112. // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
  113. // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
  114. // TODO: add other combined directives in topological order.
  115. static const OpenMPDirectiveKindExWrapper F[][3] = {
  116. {OMPD_begin, OMPD_declare, OMPD_begin_declare},
  117. {OMPD_begin, OMPD_assumes, OMPD_begin_assumes},
  118. {OMPD_end, OMPD_declare, OMPD_end_declare},
  119. {OMPD_end, OMPD_assumes, OMPD_end_assumes},
  120. {OMPD_cancellation, OMPD_point, OMPD_cancellation_point},
  121. {OMPD_declare, OMPD_reduction, OMPD_declare_reduction},
  122. {OMPD_declare, OMPD_mapper, OMPD_declare_mapper},
  123. {OMPD_declare, OMPD_simd, OMPD_declare_simd},
  124. {OMPD_declare, OMPD_target, OMPD_declare_target},
  125. {OMPD_declare, OMPD_variant, OMPD_declare_variant},
  126. {OMPD_begin_declare, OMPD_target, OMPD_begin_declare_target},
  127. {OMPD_begin_declare, OMPD_variant, OMPD_begin_declare_variant},
  128. {OMPD_end_declare, OMPD_variant, OMPD_end_declare_variant},
  129. {OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel},
  130. {OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for},
  131. {OMPD_distribute_parallel_for, OMPD_simd,
  132. OMPD_distribute_parallel_for_simd},
  133. {OMPD_distribute, OMPD_simd, OMPD_distribute_simd},
  134. {OMPD_end_declare, OMPD_target, OMPD_end_declare_target},
  135. {OMPD_target, OMPD_data, OMPD_target_data},
  136. {OMPD_target, OMPD_enter, OMPD_target_enter},
  137. {OMPD_target, OMPD_exit, OMPD_target_exit},
  138. {OMPD_target, OMPD_update, OMPD_target_update},
  139. {OMPD_target_enter, OMPD_data, OMPD_target_enter_data},
  140. {OMPD_target_exit, OMPD_data, OMPD_target_exit_data},
  141. {OMPD_for, OMPD_simd, OMPD_for_simd},
  142. {OMPD_parallel, OMPD_for, OMPD_parallel_for},
  143. {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd},
  144. {OMPD_parallel, OMPD_loop, OMPD_parallel_loop},
  145. {OMPD_parallel, OMPD_sections, OMPD_parallel_sections},
  146. {OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd},
  147. {OMPD_target, OMPD_parallel, OMPD_target_parallel},
  148. {OMPD_target, OMPD_simd, OMPD_target_simd},
  149. {OMPD_target_parallel, OMPD_loop, OMPD_target_parallel_loop},
  150. {OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for},
  151. {OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd},
  152. {OMPD_teams, OMPD_distribute, OMPD_teams_distribute},
  153. {OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd},
  154. {OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel},
  155. {OMPD_teams_distribute_parallel, OMPD_for,
  156. OMPD_teams_distribute_parallel_for},
  157. {OMPD_teams_distribute_parallel_for, OMPD_simd,
  158. OMPD_teams_distribute_parallel_for_simd},
  159. {OMPD_teams, OMPD_loop, OMPD_teams_loop},
  160. {OMPD_target, OMPD_teams, OMPD_target_teams},
  161. {OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute},
  162. {OMPD_target_teams, OMPD_loop, OMPD_target_teams_loop},
  163. {OMPD_target_teams_distribute, OMPD_parallel,
  164. OMPD_target_teams_distribute_parallel},
  165. {OMPD_target_teams_distribute, OMPD_simd,
  166. OMPD_target_teams_distribute_simd},
  167. {OMPD_target_teams_distribute_parallel, OMPD_for,
  168. OMPD_target_teams_distribute_parallel_for},
  169. {OMPD_target_teams_distribute_parallel_for, OMPD_simd,
  170. OMPD_target_teams_distribute_parallel_for_simd},
  171. {OMPD_master, OMPD_taskloop, OMPD_master_taskloop},
  172. {OMPD_masked, OMPD_taskloop, OMPD_masked_taskloop},
  173. {OMPD_master_taskloop, OMPD_simd, OMPD_master_taskloop_simd},
  174. {OMPD_masked_taskloop, OMPD_simd, OMPD_masked_taskloop_simd},
  175. {OMPD_parallel, OMPD_master, OMPD_parallel_master},
  176. {OMPD_parallel, OMPD_masked, OMPD_parallel_masked},
  177. {OMPD_parallel_master, OMPD_taskloop, OMPD_parallel_master_taskloop},
  178. {OMPD_parallel_masked, OMPD_taskloop, OMPD_parallel_masked_taskloop},
  179. {OMPD_parallel_master_taskloop, OMPD_simd,
  180. OMPD_parallel_master_taskloop_simd},
  181. {OMPD_parallel_masked_taskloop, OMPD_simd,
  182. OMPD_parallel_masked_taskloop_simd}};
  183. enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
  184. Token Tok = P.getCurToken();
  185. OpenMPDirectiveKindExWrapper DKind =
  186. Tok.isAnnotation()
  187. ? static_cast<unsigned>(OMPD_unknown)
  188. : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
  189. if (DKind == OMPD_unknown)
  190. return OMPD_unknown;
  191. for (const auto &I : F) {
  192. if (DKind != I[0])
  193. continue;
  194. Tok = P.getPreprocessor().LookAhead(0);
  195. OpenMPDirectiveKindExWrapper SDKind =
  196. Tok.isAnnotation()
  197. ? static_cast<unsigned>(OMPD_unknown)
  198. : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
  199. if (SDKind == OMPD_unknown)
  200. continue;
  201. if (SDKind == I[1]) {
  202. P.ConsumeToken();
  203. DKind = I[2];
  204. }
  205. }
  206. return unsigned(DKind) < llvm::omp::Directive_enumSize
  207. ? static_cast<OpenMPDirectiveKind>(DKind)
  208. : OMPD_unknown;
  209. }
  210. static DeclarationName parseOpenMPReductionId(Parser &P) {
  211. Token Tok = P.getCurToken();
  212. Sema &Actions = P.getActions();
  213. OverloadedOperatorKind OOK = OO_None;
  214. // Allow to use 'operator' keyword for C++ operators
  215. bool WithOperator = false;
  216. if (Tok.is(tok::kw_operator)) {
  217. P.ConsumeToken();
  218. Tok = P.getCurToken();
  219. WithOperator = true;
  220. }
  221. switch (Tok.getKind()) {
  222. case tok::plus: // '+'
  223. OOK = OO_Plus;
  224. break;
  225. case tok::minus: // '-'
  226. OOK = OO_Minus;
  227. break;
  228. case tok::star: // '*'
  229. OOK = OO_Star;
  230. break;
  231. case tok::amp: // '&'
  232. OOK = OO_Amp;
  233. break;
  234. case tok::pipe: // '|'
  235. OOK = OO_Pipe;
  236. break;
  237. case tok::caret: // '^'
  238. OOK = OO_Caret;
  239. break;
  240. case tok::ampamp: // '&&'
  241. OOK = OO_AmpAmp;
  242. break;
  243. case tok::pipepipe: // '||'
  244. OOK = OO_PipePipe;
  245. break;
  246. case tok::identifier: // identifier
  247. if (!WithOperator)
  248. break;
  249. [[fallthrough]];
  250. default:
  251. P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
  252. P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
  253. Parser::StopBeforeMatch);
  254. return DeclarationName();
  255. }
  256. P.ConsumeToken();
  257. auto &DeclNames = Actions.getASTContext().DeclarationNames;
  258. return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
  259. : DeclNames.getCXXOperatorName(OOK);
  260. }
  261. /// Parse 'omp declare reduction' construct.
  262. ///
  263. /// declare-reduction-directive:
  264. /// annot_pragma_openmp 'declare' 'reduction'
  265. /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
  266. /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
  267. /// annot_pragma_openmp_end
  268. /// <reduction_id> is either a base language identifier or one of the following
  269. /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
  270. ///
  271. Parser::DeclGroupPtrTy
  272. Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
  273. // Parse '('.
  274. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  275. if (T.expectAndConsume(
  276. diag::err_expected_lparen_after,
  277. getOpenMPDirectiveName(OMPD_declare_reduction).data())) {
  278. SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
  279. return DeclGroupPtrTy();
  280. }
  281. DeclarationName Name = parseOpenMPReductionId(*this);
  282. if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
  283. return DeclGroupPtrTy();
  284. // Consume ':'.
  285. bool IsCorrect = !ExpectAndConsume(tok::colon);
  286. if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
  287. return DeclGroupPtrTy();
  288. IsCorrect = IsCorrect && !Name.isEmpty();
  289. if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
  290. Diag(Tok.getLocation(), diag::err_expected_type);
  291. IsCorrect = false;
  292. }
  293. if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
  294. return DeclGroupPtrTy();
  295. SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
  296. // Parse list of types until ':' token.
  297. do {
  298. ColonProtectionRAIIObject ColonRAII(*this);
  299. SourceRange Range;
  300. TypeResult TR = ParseTypeName(&Range, DeclaratorContext::Prototype, AS);
  301. if (TR.isUsable()) {
  302. QualType ReductionType =
  303. Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
  304. if (!ReductionType.isNull()) {
  305. ReductionTypes.push_back(
  306. std::make_pair(ReductionType, Range.getBegin()));
  307. }
  308. } else {
  309. SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
  310. StopBeforeMatch);
  311. }
  312. if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
  313. break;
  314. // Consume ','.
  315. if (ExpectAndConsume(tok::comma)) {
  316. IsCorrect = false;
  317. if (Tok.is(tok::annot_pragma_openmp_end)) {
  318. Diag(Tok.getLocation(), diag::err_expected_type);
  319. return DeclGroupPtrTy();
  320. }
  321. }
  322. } while (Tok.isNot(tok::annot_pragma_openmp_end));
  323. if (ReductionTypes.empty()) {
  324. SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
  325. return DeclGroupPtrTy();
  326. }
  327. if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
  328. return DeclGroupPtrTy();
  329. // Consume ':'.
  330. if (ExpectAndConsume(tok::colon))
  331. IsCorrect = false;
  332. if (Tok.is(tok::annot_pragma_openmp_end)) {
  333. Diag(Tok.getLocation(), diag::err_expected_expression);
  334. return DeclGroupPtrTy();
  335. }
  336. DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
  337. getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
  338. // Parse <combiner> expression and then parse initializer if any for each
  339. // correct type.
  340. unsigned I = 0, E = ReductionTypes.size();
  341. for (Decl *D : DRD.get()) {
  342. TentativeParsingAction TPA(*this);
  343. ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
  344. Scope::CompoundStmtScope |
  345. Scope::OpenMPDirectiveScope);
  346. // Parse <combiner> expression.
  347. Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
  348. ExprResult CombinerResult = Actions.ActOnFinishFullExpr(
  349. ParseExpression().get(), D->getLocation(), /*DiscardedValue*/ false);
  350. Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
  351. if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
  352. Tok.isNot(tok::annot_pragma_openmp_end)) {
  353. TPA.Commit();
  354. IsCorrect = false;
  355. break;
  356. }
  357. IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
  358. ExprResult InitializerResult;
  359. if (Tok.isNot(tok::annot_pragma_openmp_end)) {
  360. // Parse <initializer> expression.
  361. if (Tok.is(tok::identifier) &&
  362. Tok.getIdentifierInfo()->isStr("initializer")) {
  363. ConsumeToken();
  364. } else {
  365. Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
  366. TPA.Commit();
  367. IsCorrect = false;
  368. break;
  369. }
  370. // Parse '('.
  371. BalancedDelimiterTracker T(*this, tok::l_paren,
  372. tok::annot_pragma_openmp_end);
  373. IsCorrect =
  374. !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
  375. IsCorrect;
  376. if (Tok.isNot(tok::annot_pragma_openmp_end)) {
  377. ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
  378. Scope::CompoundStmtScope |
  379. Scope::OpenMPDirectiveScope);
  380. // Parse expression.
  381. VarDecl *OmpPrivParm =
  382. Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(),
  383. D);
  384. // Check if initializer is omp_priv <init_expr> or something else.
  385. if (Tok.is(tok::identifier) &&
  386. Tok.getIdentifierInfo()->isStr("omp_priv")) {
  387. ConsumeToken();
  388. ParseOpenMPReductionInitializerForDecl(OmpPrivParm);
  389. } else {
  390. InitializerResult = Actions.ActOnFinishFullExpr(
  391. ParseAssignmentExpression().get(), D->getLocation(),
  392. /*DiscardedValue*/ false);
  393. }
  394. Actions.ActOnOpenMPDeclareReductionInitializerEnd(
  395. D, InitializerResult.get(), OmpPrivParm);
  396. if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
  397. Tok.isNot(tok::annot_pragma_openmp_end)) {
  398. TPA.Commit();
  399. IsCorrect = false;
  400. break;
  401. }
  402. IsCorrect =
  403. !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
  404. }
  405. }
  406. ++I;
  407. // Revert parsing if not the last type, otherwise accept it, we're done with
  408. // parsing.
  409. if (I != E)
  410. TPA.Revert();
  411. else
  412. TPA.Commit();
  413. }
  414. return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
  415. IsCorrect);
  416. }
  417. void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) {
  418. // Parse declarator '=' initializer.
  419. // If a '==' or '+=' is found, suggest a fixit to '='.
  420. if (isTokenEqualOrEqualTypo()) {
  421. ConsumeToken();
  422. if (Tok.is(tok::code_completion)) {
  423. cutOffParsing();
  424. Actions.CodeCompleteInitializer(getCurScope(), OmpPrivParm);
  425. Actions.FinalizeDeclaration(OmpPrivParm);
  426. return;
  427. }
  428. PreferredType.enterVariableInit(Tok.getLocation(), OmpPrivParm);
  429. ExprResult Init = ParseInitializer();
  430. if (Init.isInvalid()) {
  431. SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
  432. Actions.ActOnInitializerError(OmpPrivParm);
  433. } else {
  434. Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
  435. /*DirectInit=*/false);
  436. }
  437. } else if (Tok.is(tok::l_paren)) {
  438. // Parse C++ direct initializer: '(' expression-list ')'
  439. BalancedDelimiterTracker T(*this, tok::l_paren);
  440. T.consumeOpen();
  441. ExprVector Exprs;
  442. SourceLocation LParLoc = T.getOpenLocation();
  443. auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() {
  444. QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
  445. OmpPrivParm->getType()->getCanonicalTypeInternal(),
  446. OmpPrivParm->getLocation(), Exprs, LParLoc, /*Braced=*/false);
  447. CalledSignatureHelp = true;
  448. return PreferredType;
  449. };
  450. if (ParseExpressionList(Exprs, [&] {
  451. PreferredType.enterFunctionArgument(Tok.getLocation(),
  452. RunSignatureHelp);
  453. })) {
  454. if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
  455. RunSignatureHelp();
  456. Actions.ActOnInitializerError(OmpPrivParm);
  457. SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
  458. } else {
  459. // Match the ')'.
  460. SourceLocation RLoc = Tok.getLocation();
  461. if (!T.consumeClose())
  462. RLoc = T.getCloseLocation();
  463. ExprResult Initializer =
  464. Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs);
  465. Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(),
  466. /*DirectInit=*/true);
  467. }
  468. } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  469. // Parse C++0x braced-init-list.
  470. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  471. ExprResult Init(ParseBraceInitializer());
  472. if (Init.isInvalid()) {
  473. Actions.ActOnInitializerError(OmpPrivParm);
  474. } else {
  475. Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
  476. /*DirectInit=*/true);
  477. }
  478. } else {
  479. Actions.ActOnUninitializedDecl(OmpPrivParm);
  480. }
  481. }
  482. /// Parses 'omp declare mapper' directive.
  483. ///
  484. /// declare-mapper-directive:
  485. /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':']
  486. /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
  487. /// annot_pragma_openmp_end
  488. /// <mapper-identifier> and <var> are base language identifiers.
  489. ///
  490. Parser::DeclGroupPtrTy
  491. Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) {
  492. bool IsCorrect = true;
  493. // Parse '('
  494. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  495. if (T.expectAndConsume(diag::err_expected_lparen_after,
  496. getOpenMPDirectiveName(OMPD_declare_mapper).data())) {
  497. SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
  498. return DeclGroupPtrTy();
  499. }
  500. // Parse <mapper-identifier>
  501. auto &DeclNames = Actions.getASTContext().DeclarationNames;
  502. DeclarationName MapperId;
  503. if (PP.LookAhead(0).is(tok::colon)) {
  504. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
  505. Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
  506. IsCorrect = false;
  507. } else {
  508. MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo());
  509. }
  510. ConsumeToken();
  511. // Consume ':'.
  512. ExpectAndConsume(tok::colon);
  513. } else {
  514. // If no mapper identifier is provided, its name is "default" by default
  515. MapperId =
  516. DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default"));
  517. }
  518. if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
  519. return DeclGroupPtrTy();
  520. // Parse <type> <var>
  521. DeclarationName VName;
  522. QualType MapperType;
  523. SourceRange Range;
  524. TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS);
  525. if (ParsedType.isUsable())
  526. MapperType =
  527. Actions.ActOnOpenMPDeclareMapperType(Range.getBegin(), ParsedType);
  528. if (MapperType.isNull())
  529. IsCorrect = false;
  530. if (!IsCorrect) {
  531. SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
  532. return DeclGroupPtrTy();
  533. }
  534. // Consume ')'.
  535. IsCorrect &= !T.consumeClose();
  536. if (!IsCorrect) {
  537. SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
  538. return DeclGroupPtrTy();
  539. }
  540. // Enter scope.
  541. DeclarationNameInfo DirName;
  542. SourceLocation Loc = Tok.getLocation();
  543. unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
  544. Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
  545. ParseScope OMPDirectiveScope(this, ScopeFlags);
  546. Actions.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, getCurScope(), Loc);
  547. // Add the mapper variable declaration.
  548. ExprResult MapperVarRef = Actions.ActOnOpenMPDeclareMapperDirectiveVarDecl(
  549. getCurScope(), MapperType, Range.getBegin(), VName);
  550. // Parse map clauses.
  551. SmallVector<OMPClause *, 6> Clauses;
  552. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  553. OpenMPClauseKind CKind = Tok.isAnnotation()
  554. ? OMPC_unknown
  555. : getOpenMPClauseKind(PP.getSpelling(Tok));
  556. Actions.StartOpenMPClause(CKind);
  557. OMPClause *Clause =
  558. ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.empty());
  559. if (Clause)
  560. Clauses.push_back(Clause);
  561. else
  562. IsCorrect = false;
  563. // Skip ',' if any.
  564. if (Tok.is(tok::comma))
  565. ConsumeToken();
  566. Actions.EndOpenMPClause();
  567. }
  568. if (Clauses.empty()) {
  569. Diag(Tok, diag::err_omp_expected_clause)
  570. << getOpenMPDirectiveName(OMPD_declare_mapper);
  571. IsCorrect = false;
  572. }
  573. // Exit scope.
  574. Actions.EndOpenMPDSABlock(nullptr);
  575. OMPDirectiveScope.Exit();
  576. DeclGroupPtrTy DG = Actions.ActOnOpenMPDeclareMapperDirective(
  577. getCurScope(), Actions.getCurLexicalContext(), MapperId, MapperType,
  578. Range.getBegin(), VName, AS, MapperVarRef.get(), Clauses);
  579. if (!IsCorrect)
  580. return DeclGroupPtrTy();
  581. return DG;
  582. }
  583. TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
  584. DeclarationName &Name,
  585. AccessSpecifier AS) {
  586. // Parse the common declaration-specifiers piece.
  587. Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier;
  588. DeclSpec DS(AttrFactory);
  589. ParseSpecifierQualifierList(DS, AS, DSC);
  590. // Parse the declarator.
  591. DeclaratorContext Context = DeclaratorContext::Prototype;
  592. Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
  593. ParseDeclarator(DeclaratorInfo);
  594. Range = DeclaratorInfo.getSourceRange();
  595. if (DeclaratorInfo.getIdentifier() == nullptr) {
  596. Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator);
  597. return true;
  598. }
  599. Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName();
  600. return Actions.ActOnOpenMPDeclareMapperVarDecl(getCurScope(), DeclaratorInfo);
  601. }
  602. namespace {
  603. /// RAII that recreates function context for correct parsing of clauses of
  604. /// 'declare simd' construct.
  605. /// OpenMP, 2.8.2 declare simd Construct
  606. /// The expressions appearing in the clauses of this directive are evaluated in
  607. /// the scope of the arguments of the function declaration or definition.
  608. class FNContextRAII final {
  609. Parser &P;
  610. Sema::CXXThisScopeRAII *ThisScope;
  611. Parser::MultiParseScope Scopes;
  612. bool HasFunScope = false;
  613. FNContextRAII() = delete;
  614. FNContextRAII(const FNContextRAII &) = delete;
  615. FNContextRAII &operator=(const FNContextRAII &) = delete;
  616. public:
  617. FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P), Scopes(P) {
  618. Decl *D = *Ptr.get().begin();
  619. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  620. RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
  621. Sema &Actions = P.getActions();
  622. // Allow 'this' within late-parsed attributes.
  623. ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(),
  624. ND && ND->isCXXInstanceMember());
  625. // If the Decl is templatized, add template parameters to scope.
  626. // FIXME: Track CurTemplateDepth?
  627. P.ReenterTemplateScopes(Scopes, D);
  628. // If the Decl is on a function, add function parameters to the scope.
  629. if (D->isFunctionOrFunctionTemplate()) {
  630. HasFunScope = true;
  631. Scopes.Enter(Scope::FnScope | Scope::DeclScope |
  632. Scope::CompoundStmtScope);
  633. Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
  634. }
  635. }
  636. ~FNContextRAII() {
  637. if (HasFunScope)
  638. P.getActions().ActOnExitFunctionContext();
  639. delete ThisScope;
  640. }
  641. };
  642. } // namespace
  643. /// Parses clauses for 'declare simd' directive.
  644. /// clause:
  645. /// 'inbranch' | 'notinbranch'
  646. /// 'simdlen' '(' <expr> ')'
  647. /// { 'uniform' '(' <argument_list> ')' }
  648. /// { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
  649. /// { 'linear '(' <argument_list> [ ':' <step> ] ')' }
  650. static bool parseDeclareSimdClauses(
  651. Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
  652. SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
  653. SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
  654. SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
  655. SourceRange BSRange;
  656. const Token &Tok = P.getCurToken();
  657. bool IsError = false;
  658. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  659. if (Tok.isNot(tok::identifier))
  660. break;
  661. OMPDeclareSimdDeclAttr::BranchStateTy Out;
  662. IdentifierInfo *II = Tok.getIdentifierInfo();
  663. StringRef ClauseName = II->getName();
  664. // Parse 'inranch|notinbranch' clauses.
  665. if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
  666. if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
  667. P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
  668. << ClauseName
  669. << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
  670. IsError = true;
  671. }
  672. BS = Out;
  673. BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
  674. P.ConsumeToken();
  675. } else if (ClauseName.equals("simdlen")) {
  676. if (SimdLen.isUsable()) {
  677. P.Diag(Tok, diag::err_omp_more_one_clause)
  678. << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
  679. IsError = true;
  680. }
  681. P.ConsumeToken();
  682. SourceLocation RLoc;
  683. SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
  684. if (SimdLen.isInvalid())
  685. IsError = true;
  686. } else {
  687. OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
  688. if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
  689. CKind == OMPC_linear) {
  690. Sema::OpenMPVarListDataTy Data;
  691. SmallVectorImpl<Expr *> *Vars = &Uniforms;
  692. if (CKind == OMPC_aligned) {
  693. Vars = &Aligneds;
  694. } else if (CKind == OMPC_linear) {
  695. Data.ExtraModifier = OMPC_LINEAR_val;
  696. Vars = &Linears;
  697. }
  698. P.ConsumeToken();
  699. if (P.ParseOpenMPVarList(OMPD_declare_simd,
  700. getOpenMPClauseKind(ClauseName), *Vars, Data))
  701. IsError = true;
  702. if (CKind == OMPC_aligned) {
  703. Alignments.append(Aligneds.size() - Alignments.size(),
  704. Data.DepModOrTailExpr);
  705. } else if (CKind == OMPC_linear) {
  706. assert(0 <= Data.ExtraModifier &&
  707. Data.ExtraModifier <= OMPC_LINEAR_unknown &&
  708. "Unexpected linear modifier.");
  709. if (P.getActions().CheckOpenMPLinearModifier(
  710. static_cast<OpenMPLinearClauseKind>(Data.ExtraModifier),
  711. Data.ExtraModifierLoc))
  712. Data.ExtraModifier = OMPC_LINEAR_val;
  713. LinModifiers.append(Linears.size() - LinModifiers.size(),
  714. Data.ExtraModifier);
  715. Steps.append(Linears.size() - Steps.size(), Data.DepModOrTailExpr);
  716. }
  717. } else
  718. // TODO: add parsing of other clauses.
  719. break;
  720. }
  721. // Skip ',' if any.
  722. if (Tok.is(tok::comma))
  723. P.ConsumeToken();
  724. }
  725. return IsError;
  726. }
  727. /// Parse clauses for '#pragma omp declare simd'.
  728. Parser::DeclGroupPtrTy
  729. Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
  730. CachedTokens &Toks, SourceLocation Loc) {
  731. PP.EnterToken(Tok, /*IsReinject*/ true);
  732. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  733. /*IsReinject*/ true);
  734. // Consume the previously pushed token.
  735. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  736. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  737. FNContextRAII FnContext(*this, Ptr);
  738. OMPDeclareSimdDeclAttr::BranchStateTy BS =
  739. OMPDeclareSimdDeclAttr::BS_Undefined;
  740. ExprResult Simdlen;
  741. SmallVector<Expr *, 4> Uniforms;
  742. SmallVector<Expr *, 4> Aligneds;
  743. SmallVector<Expr *, 4> Alignments;
  744. SmallVector<Expr *, 4> Linears;
  745. SmallVector<unsigned, 4> LinModifiers;
  746. SmallVector<Expr *, 4> Steps;
  747. bool IsError =
  748. parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
  749. Alignments, Linears, LinModifiers, Steps);
  750. skipUntilPragmaOpenMPEnd(OMPD_declare_simd);
  751. // Skip the last annot_pragma_openmp_end.
  752. SourceLocation EndLoc = ConsumeAnnotationToken();
  753. if (IsError)
  754. return Ptr;
  755. return Actions.ActOnOpenMPDeclareSimdDirective(
  756. Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
  757. LinModifiers, Steps, SourceRange(Loc, EndLoc));
  758. }
  759. namespace {
  760. /// Constant used in the diagnostics to distinguish the levels in an OpenMP
  761. /// contexts: selector-set={selector(trait, ...), ...}, ....
  762. enum OMPContextLvl {
  763. CONTEXT_SELECTOR_SET_LVL = 0,
  764. CONTEXT_SELECTOR_LVL = 1,
  765. CONTEXT_TRAIT_LVL = 2,
  766. };
  767. static StringRef stringLiteralParser(Parser &P) {
  768. ExprResult Res = P.ParseStringLiteralExpression(true);
  769. return Res.isUsable() ? Res.getAs<StringLiteral>()->getString() : "";
  770. }
  771. static StringRef getNameFromIdOrString(Parser &P, Token &Tok,
  772. OMPContextLvl Lvl) {
  773. if (Tok.is(tok::identifier) || Tok.is(tok::kw_for)) {
  774. llvm::SmallString<16> Buffer;
  775. StringRef Name = P.getPreprocessor().getSpelling(Tok, Buffer);
  776. (void)P.ConsumeToken();
  777. return Name;
  778. }
  779. if (tok::isStringLiteral(Tok.getKind()))
  780. return stringLiteralParser(P);
  781. P.Diag(Tok.getLocation(),
  782. diag::warn_omp_declare_variant_string_literal_or_identifier)
  783. << Lvl;
  784. return "";
  785. }
  786. static bool checkForDuplicates(Parser &P, StringRef Name,
  787. SourceLocation NameLoc,
  788. llvm::StringMap<SourceLocation> &Seen,
  789. OMPContextLvl Lvl) {
  790. auto Res = Seen.try_emplace(Name, NameLoc);
  791. if (Res.second)
  792. return false;
  793. // Each trait-set-selector-name, trait-selector-name and trait-name can
  794. // only be specified once.
  795. P.Diag(NameLoc, diag::warn_omp_declare_variant_ctx_mutiple_use)
  796. << Lvl << Name;
  797. P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here)
  798. << Lvl << Name;
  799. return true;
  800. }
  801. } // namespace
  802. void Parser::parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
  803. llvm::omp::TraitSet Set,
  804. llvm::omp::TraitSelector Selector,
  805. llvm::StringMap<SourceLocation> &Seen) {
  806. TIProperty.Kind = TraitProperty::invalid;
  807. SourceLocation NameLoc = Tok.getLocation();
  808. StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL);
  809. if (Name.empty()) {
  810. Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
  811. << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
  812. return;
  813. }
  814. TIProperty.RawString = Name;
  815. TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Selector, Name);
  816. if (TIProperty.Kind != TraitProperty::invalid) {
  817. if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_TRAIT_LVL))
  818. TIProperty.Kind = TraitProperty::invalid;
  819. return;
  820. }
  821. // It follows diagnosis and helping notes.
  822. // FIXME: We should move the diagnosis string generation into libFrontend.
  823. Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_property)
  824. << Name << getOpenMPContextTraitSelectorName(Selector)
  825. << getOpenMPContextTraitSetName(Set);
  826. TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
  827. if (SetForName != TraitSet::invalid) {
  828. Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
  829. << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_TRAIT_LVL;
  830. Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
  831. << Name << "<selector-name>"
  832. << "(<property-name>)";
  833. return;
  834. }
  835. TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
  836. if (SelectorForName != TraitSelector::invalid) {
  837. Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
  838. << Name << CONTEXT_SELECTOR_LVL << CONTEXT_TRAIT_LVL;
  839. bool AllowsTraitScore = false;
  840. bool RequiresProperty = false;
  841. isValidTraitSelectorForTraitSet(
  842. SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
  843. AllowsTraitScore, RequiresProperty);
  844. Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
  845. << getOpenMPContextTraitSetName(
  846. getOpenMPContextTraitSetForSelector(SelectorForName))
  847. << Name << (RequiresProperty ? "(<property-name>)" : "");
  848. return;
  849. }
  850. for (const auto &PotentialSet :
  851. {TraitSet::construct, TraitSet::user, TraitSet::implementation,
  852. TraitSet::device}) {
  853. TraitProperty PropertyForName =
  854. getOpenMPContextTraitPropertyKind(PotentialSet, Selector, Name);
  855. if (PropertyForName == TraitProperty::invalid)
  856. continue;
  857. Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
  858. << getOpenMPContextTraitSetName(
  859. getOpenMPContextTraitSetForProperty(PropertyForName))
  860. << getOpenMPContextTraitSelectorName(
  861. getOpenMPContextTraitSelectorForProperty(PropertyForName))
  862. << ("(" + Name + ")").str();
  863. return;
  864. }
  865. Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
  866. << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
  867. }
  868. static bool checkExtensionProperty(Parser &P, SourceLocation Loc,
  869. OMPTraitProperty &TIProperty,
  870. OMPTraitSelector &TISelector,
  871. llvm::StringMap<SourceLocation> &Seen) {
  872. assert(TISelector.Kind ==
  873. llvm::omp::TraitSelector::implementation_extension &&
  874. "Only for extension properties, e.g., "
  875. "`implementation={extension(PROPERTY)}`");
  876. if (TIProperty.Kind == TraitProperty::invalid)
  877. return false;
  878. if (TIProperty.Kind ==
  879. TraitProperty::implementation_extension_disable_implicit_base)
  880. return true;
  881. if (TIProperty.Kind ==
  882. TraitProperty::implementation_extension_allow_templates)
  883. return true;
  884. if (TIProperty.Kind ==
  885. TraitProperty::implementation_extension_bind_to_declaration)
  886. return true;
  887. auto IsMatchExtension = [](OMPTraitProperty &TP) {
  888. return (TP.Kind ==
  889. llvm::omp::TraitProperty::implementation_extension_match_all ||
  890. TP.Kind ==
  891. llvm::omp::TraitProperty::implementation_extension_match_any ||
  892. TP.Kind ==
  893. llvm::omp::TraitProperty::implementation_extension_match_none);
  894. };
  895. if (IsMatchExtension(TIProperty)) {
  896. for (OMPTraitProperty &SeenProp : TISelector.Properties)
  897. if (IsMatchExtension(SeenProp)) {
  898. P.Diag(Loc, diag::err_omp_variant_ctx_second_match_extension);
  899. StringRef SeenName = llvm::omp::getOpenMPContextTraitPropertyName(
  900. SeenProp.Kind, SeenProp.RawString);
  901. SourceLocation SeenLoc = Seen[SeenName];
  902. P.Diag(SeenLoc, diag::note_omp_declare_variant_ctx_used_here)
  903. << CONTEXT_TRAIT_LVL << SeenName;
  904. return false;
  905. }
  906. return true;
  907. }
  908. llvm_unreachable("Unknown extension property!");
  909. }
  910. void Parser::parseOMPContextProperty(OMPTraitSelector &TISelector,
  911. llvm::omp::TraitSet Set,
  912. llvm::StringMap<SourceLocation> &Seen) {
  913. assert(TISelector.Kind != TraitSelector::user_condition &&
  914. "User conditions are special properties not handled here!");
  915. SourceLocation PropertyLoc = Tok.getLocation();
  916. OMPTraitProperty TIProperty;
  917. parseOMPTraitPropertyKind(TIProperty, Set, TISelector.Kind, Seen);
  918. if (TISelector.Kind == llvm::omp::TraitSelector::implementation_extension)
  919. if (!checkExtensionProperty(*this, Tok.getLocation(), TIProperty,
  920. TISelector, Seen))
  921. TIProperty.Kind = TraitProperty::invalid;
  922. // If we have an invalid property here we already issued a warning.
  923. if (TIProperty.Kind == TraitProperty::invalid) {
  924. if (PropertyLoc != Tok.getLocation())
  925. Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
  926. << CONTEXT_TRAIT_LVL;
  927. return;
  928. }
  929. if (isValidTraitPropertyForTraitSetAndSelector(TIProperty.Kind,
  930. TISelector.Kind, Set)) {
  931. // If we make it here the property, selector, set, score, condition, ... are
  932. // all valid (or have been corrected). Thus we can record the property.
  933. TISelector.Properties.push_back(TIProperty);
  934. return;
  935. }
  936. Diag(PropertyLoc, diag::warn_omp_ctx_incompatible_property_for_selector)
  937. << getOpenMPContextTraitPropertyName(TIProperty.Kind,
  938. TIProperty.RawString)
  939. << getOpenMPContextTraitSelectorName(TISelector.Kind)
  940. << getOpenMPContextTraitSetName(Set);
  941. Diag(PropertyLoc, diag::note_omp_ctx_compatible_set_and_selector_for_property)
  942. << getOpenMPContextTraitPropertyName(TIProperty.Kind,
  943. TIProperty.RawString)
  944. << getOpenMPContextTraitSelectorName(
  945. getOpenMPContextTraitSelectorForProperty(TIProperty.Kind))
  946. << getOpenMPContextTraitSetName(
  947. getOpenMPContextTraitSetForProperty(TIProperty.Kind));
  948. Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
  949. << CONTEXT_TRAIT_LVL;
  950. }
  951. void Parser::parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
  952. llvm::omp::TraitSet Set,
  953. llvm::StringMap<SourceLocation> &Seen) {
  954. TISelector.Kind = TraitSelector::invalid;
  955. SourceLocation NameLoc = Tok.getLocation();
  956. StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_LVL);
  957. if (Name.empty()) {
  958. Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
  959. << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
  960. return;
  961. }
  962. TISelector.Kind = getOpenMPContextTraitSelectorKind(Name);
  963. if (TISelector.Kind != TraitSelector::invalid) {
  964. if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_SELECTOR_LVL))
  965. TISelector.Kind = TraitSelector::invalid;
  966. return;
  967. }
  968. // It follows diagnosis and helping notes.
  969. Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_selector)
  970. << Name << getOpenMPContextTraitSetName(Set);
  971. TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
  972. if (SetForName != TraitSet::invalid) {
  973. Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
  974. << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_SELECTOR_LVL;
  975. Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
  976. << Name << "<selector-name>"
  977. << "<property-name>";
  978. return;
  979. }
  980. for (const auto &PotentialSet :
  981. {TraitSet::construct, TraitSet::user, TraitSet::implementation,
  982. TraitSet::device}) {
  983. TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind(
  984. PotentialSet, TraitSelector::invalid, Name);
  985. if (PropertyForName == TraitProperty::invalid)
  986. continue;
  987. Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
  988. << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_LVL;
  989. Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
  990. << getOpenMPContextTraitSetName(
  991. getOpenMPContextTraitSetForProperty(PropertyForName))
  992. << getOpenMPContextTraitSelectorName(
  993. getOpenMPContextTraitSelectorForProperty(PropertyForName))
  994. << ("(" + Name + ")").str();
  995. return;
  996. }
  997. Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
  998. << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
  999. }
  1000. /// Parse optional 'score' '(' <expr> ')' ':'.
  1001. static ExprResult parseContextScore(Parser &P) {
  1002. ExprResult ScoreExpr;
  1003. llvm::SmallString<16> Buffer;
  1004. StringRef SelectorName =
  1005. P.getPreprocessor().getSpelling(P.getCurToken(), Buffer);
  1006. if (!SelectorName.equals("score"))
  1007. return ScoreExpr;
  1008. (void)P.ConsumeToken();
  1009. SourceLocation RLoc;
  1010. ScoreExpr = P.ParseOpenMPParensExpr(SelectorName, RLoc);
  1011. // Parse ':'
  1012. if (P.getCurToken().is(tok::colon))
  1013. (void)P.ConsumeAnyToken();
  1014. else
  1015. P.Diag(P.getCurToken(), diag::warn_omp_declare_variant_expected)
  1016. << "':'"
  1017. << "score expression";
  1018. return ScoreExpr;
  1019. }
  1020. /// Parses an OpenMP context selector.
  1021. ///
  1022. /// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')']
  1023. void Parser::parseOMPContextSelector(
  1024. OMPTraitSelector &TISelector, llvm::omp::TraitSet Set,
  1025. llvm::StringMap<SourceLocation> &SeenSelectors) {
  1026. unsigned short OuterPC = ParenCount;
  1027. // If anything went wrong we issue an error or warning and then skip the rest
  1028. // of the selector. However, commas are ambiguous so we look for the nesting
  1029. // of parentheses here as well.
  1030. auto FinishSelector = [OuterPC, this]() -> void {
  1031. bool Done = false;
  1032. while (!Done) {
  1033. while (!SkipUntil({tok::r_brace, tok::r_paren, tok::comma,
  1034. tok::annot_pragma_openmp_end},
  1035. StopBeforeMatch))
  1036. ;
  1037. if (Tok.is(tok::r_paren) && OuterPC > ParenCount)
  1038. (void)ConsumeParen();
  1039. if (OuterPC <= ParenCount) {
  1040. Done = true;
  1041. break;
  1042. }
  1043. if (!Tok.is(tok::comma) && !Tok.is(tok::r_paren)) {
  1044. Done = true;
  1045. break;
  1046. }
  1047. (void)ConsumeAnyToken();
  1048. }
  1049. Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
  1050. << CONTEXT_SELECTOR_LVL;
  1051. };
  1052. SourceLocation SelectorLoc = Tok.getLocation();
  1053. parseOMPTraitSelectorKind(TISelector, Set, SeenSelectors);
  1054. if (TISelector.Kind == TraitSelector::invalid)
  1055. return FinishSelector();
  1056. bool AllowsTraitScore = false;
  1057. bool RequiresProperty = false;
  1058. if (!isValidTraitSelectorForTraitSet(TISelector.Kind, Set, AllowsTraitScore,
  1059. RequiresProperty)) {
  1060. Diag(SelectorLoc, diag::warn_omp_ctx_incompatible_selector_for_set)
  1061. << getOpenMPContextTraitSelectorName(TISelector.Kind)
  1062. << getOpenMPContextTraitSetName(Set);
  1063. Diag(SelectorLoc, diag::note_omp_ctx_compatible_set_for_selector)
  1064. << getOpenMPContextTraitSelectorName(TISelector.Kind)
  1065. << getOpenMPContextTraitSetName(
  1066. getOpenMPContextTraitSetForSelector(TISelector.Kind))
  1067. << RequiresProperty;
  1068. return FinishSelector();
  1069. }
  1070. if (!RequiresProperty) {
  1071. TISelector.Properties.push_back(
  1072. {getOpenMPContextTraitPropertyForSelector(TISelector.Kind),
  1073. getOpenMPContextTraitSelectorName(TISelector.Kind)});
  1074. return;
  1075. }
  1076. if (!Tok.is(tok::l_paren)) {
  1077. Diag(SelectorLoc, diag::warn_omp_ctx_selector_without_properties)
  1078. << getOpenMPContextTraitSelectorName(TISelector.Kind)
  1079. << getOpenMPContextTraitSetName(Set);
  1080. return FinishSelector();
  1081. }
  1082. if (TISelector.Kind == TraitSelector::user_condition) {
  1083. SourceLocation RLoc;
  1084. ExprResult Condition = ParseOpenMPParensExpr("user condition", RLoc);
  1085. if (!Condition.isUsable())
  1086. return FinishSelector();
  1087. TISelector.ScoreOrCondition = Condition.get();
  1088. TISelector.Properties.push_back(
  1089. {TraitProperty::user_condition_unknown, "<condition>"});
  1090. return;
  1091. }
  1092. BalancedDelimiterTracker BDT(*this, tok::l_paren,
  1093. tok::annot_pragma_openmp_end);
  1094. // Parse '('.
  1095. (void)BDT.consumeOpen();
  1096. SourceLocation ScoreLoc = Tok.getLocation();
  1097. ExprResult Score = parseContextScore(*this);
  1098. if (!AllowsTraitScore && !Score.isUnset()) {
  1099. if (Score.isUsable()) {
  1100. Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
  1101. << getOpenMPContextTraitSelectorName(TISelector.Kind)
  1102. << getOpenMPContextTraitSetName(Set) << Score.get();
  1103. } else {
  1104. Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
  1105. << getOpenMPContextTraitSelectorName(TISelector.Kind)
  1106. << getOpenMPContextTraitSetName(Set) << "<invalid>";
  1107. }
  1108. Score = ExprResult();
  1109. }
  1110. if (Score.isUsable())
  1111. TISelector.ScoreOrCondition = Score.get();
  1112. llvm::StringMap<SourceLocation> SeenProperties;
  1113. do {
  1114. parseOMPContextProperty(TISelector, Set, SeenProperties);
  1115. } while (TryConsumeToken(tok::comma));
  1116. // Parse ')'.
  1117. BDT.consumeClose();
  1118. }
  1119. void Parser::parseOMPTraitSetKind(OMPTraitSet &TISet,
  1120. llvm::StringMap<SourceLocation> &Seen) {
  1121. TISet.Kind = TraitSet::invalid;
  1122. SourceLocation NameLoc = Tok.getLocation();
  1123. StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_SET_LVL);
  1124. if (Name.empty()) {
  1125. Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
  1126. << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
  1127. return;
  1128. }
  1129. TISet.Kind = getOpenMPContextTraitSetKind(Name);
  1130. if (TISet.Kind != TraitSet::invalid) {
  1131. if (checkForDuplicates(*this, Name, NameLoc, Seen,
  1132. CONTEXT_SELECTOR_SET_LVL))
  1133. TISet.Kind = TraitSet::invalid;
  1134. return;
  1135. }
  1136. // It follows diagnosis and helping notes.
  1137. Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_set) << Name;
  1138. TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
  1139. if (SelectorForName != TraitSelector::invalid) {
  1140. Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
  1141. << Name << CONTEXT_SELECTOR_LVL << CONTEXT_SELECTOR_SET_LVL;
  1142. bool AllowsTraitScore = false;
  1143. bool RequiresProperty = false;
  1144. isValidTraitSelectorForTraitSet(
  1145. SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
  1146. AllowsTraitScore, RequiresProperty);
  1147. Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
  1148. << getOpenMPContextTraitSetName(
  1149. getOpenMPContextTraitSetForSelector(SelectorForName))
  1150. << Name << (RequiresProperty ? "(<property-name>)" : "");
  1151. return;
  1152. }
  1153. for (const auto &PotentialSet :
  1154. {TraitSet::construct, TraitSet::user, TraitSet::implementation,
  1155. TraitSet::device}) {
  1156. TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind(
  1157. PotentialSet, TraitSelector::invalid, Name);
  1158. if (PropertyForName == TraitProperty::invalid)
  1159. continue;
  1160. Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
  1161. << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_SET_LVL;
  1162. Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
  1163. << getOpenMPContextTraitSetName(
  1164. getOpenMPContextTraitSetForProperty(PropertyForName))
  1165. << getOpenMPContextTraitSelectorName(
  1166. getOpenMPContextTraitSelectorForProperty(PropertyForName))
  1167. << ("(" + Name + ")").str();
  1168. return;
  1169. }
  1170. Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
  1171. << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
  1172. }
  1173. /// Parses an OpenMP context selector set.
  1174. ///
  1175. /// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}'
  1176. void Parser::parseOMPContextSelectorSet(
  1177. OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets) {
  1178. auto OuterBC = BraceCount;
  1179. // If anything went wrong we issue an error or warning and then skip the rest
  1180. // of the set. However, commas are ambiguous so we look for the nesting
  1181. // of braces here as well.
  1182. auto FinishSelectorSet = [this, OuterBC]() -> void {
  1183. bool Done = false;
  1184. while (!Done) {
  1185. while (!SkipUntil({tok::comma, tok::r_brace, tok::r_paren,
  1186. tok::annot_pragma_openmp_end},
  1187. StopBeforeMatch))
  1188. ;
  1189. if (Tok.is(tok::r_brace) && OuterBC > BraceCount)
  1190. (void)ConsumeBrace();
  1191. if (OuterBC <= BraceCount) {
  1192. Done = true;
  1193. break;
  1194. }
  1195. if (!Tok.is(tok::comma) && !Tok.is(tok::r_brace)) {
  1196. Done = true;
  1197. break;
  1198. }
  1199. (void)ConsumeAnyToken();
  1200. }
  1201. Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
  1202. << CONTEXT_SELECTOR_SET_LVL;
  1203. };
  1204. parseOMPTraitSetKind(TISet, SeenSets);
  1205. if (TISet.Kind == TraitSet::invalid)
  1206. return FinishSelectorSet();
  1207. // Parse '='.
  1208. if (!TryConsumeToken(tok::equal))
  1209. Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
  1210. << "="
  1211. << ("context set name \"" + getOpenMPContextTraitSetName(TISet.Kind) +
  1212. "\"")
  1213. .str();
  1214. // Parse '{'.
  1215. if (Tok.is(tok::l_brace)) {
  1216. (void)ConsumeBrace();
  1217. } else {
  1218. Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
  1219. << "{"
  1220. << ("'=' that follows the context set name \"" +
  1221. getOpenMPContextTraitSetName(TISet.Kind) + "\"")
  1222. .str();
  1223. }
  1224. llvm::StringMap<SourceLocation> SeenSelectors;
  1225. do {
  1226. OMPTraitSelector TISelector;
  1227. parseOMPContextSelector(TISelector, TISet.Kind, SeenSelectors);
  1228. if (TISelector.Kind != TraitSelector::invalid &&
  1229. !TISelector.Properties.empty())
  1230. TISet.Selectors.push_back(TISelector);
  1231. } while (TryConsumeToken(tok::comma));
  1232. // Parse '}'.
  1233. if (Tok.is(tok::r_brace)) {
  1234. (void)ConsumeBrace();
  1235. } else {
  1236. Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
  1237. << "}"
  1238. << ("context selectors for the context set \"" +
  1239. getOpenMPContextTraitSetName(TISet.Kind) + "\"")
  1240. .str();
  1241. }
  1242. }
  1243. /// Parse OpenMP context selectors:
  1244. ///
  1245. /// <trait-set-selector> [, <trait-set-selector>]*
  1246. bool Parser::parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI) {
  1247. llvm::StringMap<SourceLocation> SeenSets;
  1248. do {
  1249. OMPTraitSet TISet;
  1250. parseOMPContextSelectorSet(TISet, SeenSets);
  1251. if (TISet.Kind != TraitSet::invalid && !TISet.Selectors.empty())
  1252. TI.Sets.push_back(TISet);
  1253. } while (TryConsumeToken(tok::comma));
  1254. return false;
  1255. }
  1256. /// Parse clauses for '#pragma omp declare variant ( variant-func-id ) clause'.
  1257. void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr,
  1258. CachedTokens &Toks,
  1259. SourceLocation Loc) {
  1260. PP.EnterToken(Tok, /*IsReinject*/ true);
  1261. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  1262. /*IsReinject*/ true);
  1263. // Consume the previously pushed token.
  1264. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  1265. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  1266. FNContextRAII FnContext(*this, Ptr);
  1267. // Parse function declaration id.
  1268. SourceLocation RLoc;
  1269. // Parse with IsAddressOfOperand set to true to parse methods as DeclRefExprs
  1270. // instead of MemberExprs.
  1271. ExprResult AssociatedFunction;
  1272. {
  1273. // Do not mark function as is used to prevent its emission if this is the
  1274. // only place where it is used.
  1275. EnterExpressionEvaluationContext Unevaluated(
  1276. Actions, Sema::ExpressionEvaluationContext::Unevaluated);
  1277. AssociatedFunction = ParseOpenMPParensExpr(
  1278. getOpenMPDirectiveName(OMPD_declare_variant), RLoc,
  1279. /*IsAddressOfOperand=*/true);
  1280. }
  1281. if (!AssociatedFunction.isUsable()) {
  1282. if (!Tok.is(tok::annot_pragma_openmp_end))
  1283. while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
  1284. ;
  1285. // Skip the last annot_pragma_openmp_end.
  1286. (void)ConsumeAnnotationToken();
  1287. return;
  1288. }
  1289. OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope();
  1290. ASTContext &ASTCtx = Actions.getASTContext();
  1291. OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo();
  1292. SmallVector<Expr *, 6> AdjustNothing;
  1293. SmallVector<Expr *, 6> AdjustNeedDevicePtr;
  1294. SmallVector<OMPInteropInfo, 3> AppendArgs;
  1295. SourceLocation AdjustArgsLoc, AppendArgsLoc;
  1296. // At least one clause is required.
  1297. if (Tok.is(tok::annot_pragma_openmp_end)) {
  1298. Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
  1299. << (getLangOpts().OpenMP < 51 ? 0 : 1);
  1300. }
  1301. bool IsError = false;
  1302. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  1303. OpenMPClauseKind CKind = Tok.isAnnotation()
  1304. ? OMPC_unknown
  1305. : getOpenMPClauseKind(PP.getSpelling(Tok));
  1306. if (!isAllowedClauseForDirective(OMPD_declare_variant, CKind,
  1307. getLangOpts().OpenMP)) {
  1308. Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
  1309. << (getLangOpts().OpenMP < 51 ? 0 : 1);
  1310. IsError = true;
  1311. }
  1312. if (!IsError) {
  1313. switch (CKind) {
  1314. case OMPC_match:
  1315. IsError = parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI);
  1316. break;
  1317. case OMPC_adjust_args: {
  1318. AdjustArgsLoc = Tok.getLocation();
  1319. ConsumeToken();
  1320. Sema::OpenMPVarListDataTy Data;
  1321. SmallVector<Expr *> Vars;
  1322. IsError = ParseOpenMPVarList(OMPD_declare_variant, OMPC_adjust_args,
  1323. Vars, Data);
  1324. if (!IsError)
  1325. llvm::append_range(Data.ExtraModifier == OMPC_ADJUST_ARGS_nothing
  1326. ? AdjustNothing
  1327. : AdjustNeedDevicePtr,
  1328. Vars);
  1329. break;
  1330. }
  1331. case OMPC_append_args:
  1332. if (!AppendArgs.empty()) {
  1333. Diag(AppendArgsLoc, diag::err_omp_more_one_clause)
  1334. << getOpenMPDirectiveName(OMPD_declare_variant)
  1335. << getOpenMPClauseName(CKind) << 0;
  1336. IsError = true;
  1337. }
  1338. if (!IsError) {
  1339. AppendArgsLoc = Tok.getLocation();
  1340. ConsumeToken();
  1341. IsError = parseOpenMPAppendArgs(AppendArgs);
  1342. }
  1343. break;
  1344. default:
  1345. llvm_unreachable("Unexpected clause for declare variant.");
  1346. }
  1347. }
  1348. if (IsError) {
  1349. while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
  1350. ;
  1351. // Skip the last annot_pragma_openmp_end.
  1352. (void)ConsumeAnnotationToken();
  1353. return;
  1354. }
  1355. // Skip ',' if any.
  1356. if (Tok.is(tok::comma))
  1357. ConsumeToken();
  1358. }
  1359. std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
  1360. Actions.checkOpenMPDeclareVariantFunction(
  1361. Ptr, AssociatedFunction.get(), TI, AppendArgs.size(),
  1362. SourceRange(Loc, Tok.getLocation()));
  1363. if (DeclVarData && !TI.Sets.empty())
  1364. Actions.ActOnOpenMPDeclareVariantDirective(
  1365. DeclVarData->first, DeclVarData->second, TI, AdjustNothing,
  1366. AdjustNeedDevicePtr, AppendArgs, AdjustArgsLoc, AppendArgsLoc,
  1367. SourceRange(Loc, Tok.getLocation()));
  1368. // Skip the last annot_pragma_openmp_end.
  1369. (void)ConsumeAnnotationToken();
  1370. }
  1371. bool Parser::parseOpenMPAppendArgs(
  1372. SmallVectorImpl<OMPInteropInfo> &InteropInfos) {
  1373. bool HasError = false;
  1374. // Parse '('.
  1375. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  1376. if (T.expectAndConsume(diag::err_expected_lparen_after,
  1377. getOpenMPClauseName(OMPC_append_args).data()))
  1378. return true;
  1379. // Parse the list of append-ops, each is;
  1380. // interop(interop-type[,interop-type]...)
  1381. while (Tok.is(tok::identifier) && Tok.getIdentifierInfo()->isStr("interop")) {
  1382. ConsumeToken();
  1383. BalancedDelimiterTracker IT(*this, tok::l_paren,
  1384. tok::annot_pragma_openmp_end);
  1385. if (IT.expectAndConsume(diag::err_expected_lparen_after, "interop"))
  1386. return true;
  1387. OMPInteropInfo InteropInfo;
  1388. if (ParseOMPInteropInfo(InteropInfo, OMPC_append_args))
  1389. HasError = true;
  1390. else
  1391. InteropInfos.push_back(InteropInfo);
  1392. IT.consumeClose();
  1393. if (Tok.is(tok::comma))
  1394. ConsumeToken();
  1395. }
  1396. if (!HasError && InteropInfos.empty()) {
  1397. HasError = true;
  1398. Diag(Tok.getLocation(), diag::err_omp_unexpected_append_op);
  1399. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  1400. StopBeforeMatch);
  1401. }
  1402. HasError = T.consumeClose() || HasError;
  1403. return HasError;
  1404. }
  1405. bool Parser::parseOMPDeclareVariantMatchClause(SourceLocation Loc,
  1406. OMPTraitInfo &TI,
  1407. OMPTraitInfo *ParentTI) {
  1408. // Parse 'match'.
  1409. OpenMPClauseKind CKind = Tok.isAnnotation()
  1410. ? OMPC_unknown
  1411. : getOpenMPClauseKind(PP.getSpelling(Tok));
  1412. if (CKind != OMPC_match) {
  1413. Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
  1414. << (getLangOpts().OpenMP < 51 ? 0 : 1);
  1415. return true;
  1416. }
  1417. (void)ConsumeToken();
  1418. // Parse '('.
  1419. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  1420. if (T.expectAndConsume(diag::err_expected_lparen_after,
  1421. getOpenMPClauseName(OMPC_match).data()))
  1422. return true;
  1423. // Parse inner context selectors.
  1424. parseOMPContextSelectors(Loc, TI);
  1425. // Parse ')'
  1426. (void)T.consumeClose();
  1427. if (!ParentTI)
  1428. return false;
  1429. // Merge the parent/outer trait info into the one we just parsed and diagnose
  1430. // problems.
  1431. // TODO: Keep some source location in the TI to provide better diagnostics.
  1432. // TODO: Perform some kind of equivalence check on the condition and score
  1433. // expressions.
  1434. for (const OMPTraitSet &ParentSet : ParentTI->Sets) {
  1435. bool MergedSet = false;
  1436. for (OMPTraitSet &Set : TI.Sets) {
  1437. if (Set.Kind != ParentSet.Kind)
  1438. continue;
  1439. MergedSet = true;
  1440. for (const OMPTraitSelector &ParentSelector : ParentSet.Selectors) {
  1441. bool MergedSelector = false;
  1442. for (OMPTraitSelector &Selector : Set.Selectors) {
  1443. if (Selector.Kind != ParentSelector.Kind)
  1444. continue;
  1445. MergedSelector = true;
  1446. for (const OMPTraitProperty &ParentProperty :
  1447. ParentSelector.Properties) {
  1448. bool MergedProperty = false;
  1449. for (OMPTraitProperty &Property : Selector.Properties) {
  1450. // Ignore "equivalent" properties.
  1451. if (Property.Kind != ParentProperty.Kind)
  1452. continue;
  1453. // If the kind is the same but the raw string not, we don't want
  1454. // to skip out on the property.
  1455. MergedProperty |= Property.RawString == ParentProperty.RawString;
  1456. if (Property.RawString == ParentProperty.RawString &&
  1457. Selector.ScoreOrCondition == ParentSelector.ScoreOrCondition)
  1458. continue;
  1459. if (Selector.Kind == llvm::omp::TraitSelector::user_condition) {
  1460. Diag(Loc, diag::err_omp_declare_variant_nested_user_condition);
  1461. } else if (Selector.ScoreOrCondition !=
  1462. ParentSelector.ScoreOrCondition) {
  1463. Diag(Loc, diag::err_omp_declare_variant_duplicate_nested_trait)
  1464. << getOpenMPContextTraitPropertyName(
  1465. ParentProperty.Kind, ParentProperty.RawString)
  1466. << getOpenMPContextTraitSelectorName(ParentSelector.Kind)
  1467. << getOpenMPContextTraitSetName(ParentSet.Kind);
  1468. }
  1469. }
  1470. if (!MergedProperty)
  1471. Selector.Properties.push_back(ParentProperty);
  1472. }
  1473. }
  1474. if (!MergedSelector)
  1475. Set.Selectors.push_back(ParentSelector);
  1476. }
  1477. }
  1478. if (!MergedSet)
  1479. TI.Sets.push_back(ParentSet);
  1480. }
  1481. return false;
  1482. }
  1483. /// <clause> [clause[ [,] clause] ... ]
  1484. ///
  1485. /// clauses: for error directive
  1486. /// 'at' '(' compilation | execution ')'
  1487. /// 'severity' '(' fatal | warning ')'
  1488. /// 'message' '(' msg-string ')'
  1489. /// ....
  1490. void Parser::ParseOpenMPClauses(OpenMPDirectiveKind DKind,
  1491. SmallVectorImpl<OMPClause *> &Clauses,
  1492. SourceLocation Loc) {
  1493. SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
  1494. llvm::omp::Clause_enumSize + 1>
  1495. FirstClauses(llvm::omp::Clause_enumSize + 1);
  1496. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  1497. OpenMPClauseKind CKind = Tok.isAnnotation()
  1498. ? OMPC_unknown
  1499. : getOpenMPClauseKind(PP.getSpelling(Tok));
  1500. Actions.StartOpenMPClause(CKind);
  1501. OMPClause *Clause = ParseOpenMPClause(
  1502. DKind, CKind, !FirstClauses[unsigned(CKind)].getInt());
  1503. SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
  1504. StopBeforeMatch);
  1505. FirstClauses[unsigned(CKind)].setInt(true);
  1506. if (Clause != nullptr)
  1507. Clauses.push_back(Clause);
  1508. if (Tok.is(tok::annot_pragma_openmp_end)) {
  1509. Actions.EndOpenMPClause();
  1510. break;
  1511. }
  1512. // Skip ',' if any.
  1513. if (Tok.is(tok::comma))
  1514. ConsumeToken();
  1515. Actions.EndOpenMPClause();
  1516. }
  1517. }
  1518. /// `omp assumes` or `omp begin/end assumes` <clause> [[,]<clause>]...
  1519. /// where
  1520. ///
  1521. /// clause:
  1522. /// 'ext_IMPL_DEFINED'
  1523. /// 'absent' '(' directive-name [, directive-name]* ')'
  1524. /// 'contains' '(' directive-name [, directive-name]* ')'
  1525. /// 'holds' '(' scalar-expression ')'
  1526. /// 'no_openmp'
  1527. /// 'no_openmp_routines'
  1528. /// 'no_parallelism'
  1529. ///
  1530. void Parser::ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
  1531. SourceLocation Loc) {
  1532. SmallVector<std::string, 4> Assumptions;
  1533. bool SkippedClauses = false;
  1534. auto SkipBraces = [&](llvm::StringRef Spelling, bool IssueNote) {
  1535. BalancedDelimiterTracker T(*this, tok::l_paren,
  1536. tok::annot_pragma_openmp_end);
  1537. if (T.expectAndConsume(diag::err_expected_lparen_after, Spelling.data()))
  1538. return;
  1539. T.skipToEnd();
  1540. if (IssueNote && T.getCloseLocation().isValid())
  1541. Diag(T.getCloseLocation(),
  1542. diag::note_omp_assumption_clause_continue_here);
  1543. };
  1544. /// Helper to determine which AssumptionClauseMapping (ACM) in the
  1545. /// AssumptionClauseMappings table matches \p RawString. The return value is
  1546. /// the index of the matching ACM into the table or -1 if there was no match.
  1547. auto MatchACMClause = [&](StringRef RawString) {
  1548. llvm::StringSwitch<int> SS(RawString);
  1549. unsigned ACMIdx = 0;
  1550. for (const AssumptionClauseMappingInfo &ACMI : AssumptionClauseMappings) {
  1551. if (ACMI.StartsWith)
  1552. SS.StartsWith(ACMI.Identifier, ACMIdx++);
  1553. else
  1554. SS.Case(ACMI.Identifier, ACMIdx++);
  1555. }
  1556. return SS.Default(-1);
  1557. };
  1558. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  1559. IdentifierInfo *II = nullptr;
  1560. SourceLocation StartLoc = Tok.getLocation();
  1561. int Idx = -1;
  1562. if (Tok.isAnyIdentifier()) {
  1563. II = Tok.getIdentifierInfo();
  1564. Idx = MatchACMClause(II->getName());
  1565. }
  1566. ConsumeAnyToken();
  1567. bool NextIsLPar = Tok.is(tok::l_paren);
  1568. // Handle unknown clauses by skipping them.
  1569. if (Idx == -1) {
  1570. Diag(StartLoc, diag::warn_omp_unknown_assumption_clause_missing_id)
  1571. << llvm::omp::getOpenMPDirectiveName(DKind)
  1572. << llvm::omp::getAllAssumeClauseOptions() << NextIsLPar;
  1573. if (NextIsLPar)
  1574. SkipBraces(II ? II->getName() : "", /* IssueNote */ true);
  1575. SkippedClauses = true;
  1576. continue;
  1577. }
  1578. const AssumptionClauseMappingInfo &ACMI = AssumptionClauseMappings[Idx];
  1579. if (ACMI.HasDirectiveList || ACMI.HasExpression) {
  1580. // TODO: We ignore absent, contains, and holds assumptions for now. We
  1581. // also do not verify the content in the parenthesis at all.
  1582. SkippedClauses = true;
  1583. SkipBraces(II->getName(), /* IssueNote */ false);
  1584. continue;
  1585. }
  1586. if (NextIsLPar) {
  1587. Diag(Tok.getLocation(),
  1588. diag::warn_omp_unknown_assumption_clause_without_args)
  1589. << II;
  1590. SkipBraces(II->getName(), /* IssueNote */ true);
  1591. }
  1592. assert(II && "Expected an identifier clause!");
  1593. std::string Assumption = II->getName().str();
  1594. if (ACMI.StartsWith)
  1595. Assumption = "ompx_" + Assumption.substr(ACMI.Identifier.size());
  1596. else
  1597. Assumption = "omp_" + Assumption;
  1598. Assumptions.push_back(Assumption);
  1599. }
  1600. Actions.ActOnOpenMPAssumesDirective(Loc, DKind, Assumptions, SkippedClauses);
  1601. }
  1602. void Parser::ParseOpenMPEndAssumesDirective(SourceLocation Loc) {
  1603. if (Actions.isInOpenMPAssumeScope())
  1604. Actions.ActOnOpenMPEndAssumesDirective();
  1605. else
  1606. Diag(Loc, diag::err_expected_begin_assumes);
  1607. }
  1608. /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
  1609. ///
  1610. /// default-clause:
  1611. /// 'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')
  1612. ///
  1613. /// proc_bind-clause:
  1614. /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')
  1615. ///
  1616. /// device_type-clause:
  1617. /// 'device_type' '(' 'host' | 'nohost' | 'any' )'
  1618. namespace {
  1619. struct SimpleClauseData {
  1620. unsigned Type;
  1621. SourceLocation Loc;
  1622. SourceLocation LOpen;
  1623. SourceLocation TypeLoc;
  1624. SourceLocation RLoc;
  1625. SimpleClauseData(unsigned Type, SourceLocation Loc, SourceLocation LOpen,
  1626. SourceLocation TypeLoc, SourceLocation RLoc)
  1627. : Type(Type), Loc(Loc), LOpen(LOpen), TypeLoc(TypeLoc), RLoc(RLoc) {}
  1628. };
  1629. } // anonymous namespace
  1630. static std::optional<SimpleClauseData>
  1631. parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind) {
  1632. const Token &Tok = P.getCurToken();
  1633. SourceLocation Loc = Tok.getLocation();
  1634. SourceLocation LOpen = P.ConsumeToken();
  1635. // Parse '('.
  1636. BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end);
  1637. if (T.expectAndConsume(diag::err_expected_lparen_after,
  1638. getOpenMPClauseName(Kind).data()))
  1639. return std::nullopt;
  1640. unsigned Type = getOpenMPSimpleClauseType(
  1641. Kind, Tok.isAnnotation() ? "" : P.getPreprocessor().getSpelling(Tok),
  1642. P.getLangOpts());
  1643. SourceLocation TypeLoc = Tok.getLocation();
  1644. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  1645. Tok.isNot(tok::annot_pragma_openmp_end))
  1646. P.ConsumeAnyToken();
  1647. // Parse ')'.
  1648. SourceLocation RLoc = Tok.getLocation();
  1649. if (!T.consumeClose())
  1650. RLoc = T.getCloseLocation();
  1651. return SimpleClauseData(Type, Loc, LOpen, TypeLoc, RLoc);
  1652. }
  1653. void Parser::ParseOMPDeclareTargetClauses(
  1654. Sema::DeclareTargetContextInfo &DTCI) {
  1655. SourceLocation DeviceTypeLoc;
  1656. bool RequiresToOrLinkOrIndirectClause = false;
  1657. bool HasToOrLinkOrIndirectClause = false;
  1658. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  1659. OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To;
  1660. bool HasIdentifier = Tok.is(tok::identifier);
  1661. if (HasIdentifier) {
  1662. // If we see any clause we need a to or link clause.
  1663. RequiresToOrLinkOrIndirectClause = true;
  1664. IdentifierInfo *II = Tok.getIdentifierInfo();
  1665. StringRef ClauseName = II->getName();
  1666. bool IsDeviceTypeClause =
  1667. getLangOpts().OpenMP >= 50 &&
  1668. getOpenMPClauseKind(ClauseName) == OMPC_device_type;
  1669. bool IsIndirectClause = getLangOpts().OpenMP >= 51 &&
  1670. getOpenMPClauseKind(ClauseName) == OMPC_indirect;
  1671. if (DTCI.Indirect && IsIndirectClause) {
  1672. Diag(Tok, diag::err_omp_more_one_clause)
  1673. << getOpenMPDirectiveName(OMPD_declare_target)
  1674. << getOpenMPClauseName(OMPC_indirect) << 0;
  1675. break;
  1676. }
  1677. bool IsToEnterOrLinkClause =
  1678. OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT);
  1679. assert((!IsDeviceTypeClause || !IsToEnterOrLinkClause) &&
  1680. "Cannot be both!");
  1681. // Starting with OpenMP 5.2 the `to` clause has been replaced by the
  1682. // `enter` clause.
  1683. if (getLangOpts().OpenMP >= 52 && ClauseName == "to") {
  1684. Diag(Tok, diag::err_omp_declare_target_unexpected_to_clause);
  1685. break;
  1686. }
  1687. if (getLangOpts().OpenMP <= 51 && ClauseName == "enter") {
  1688. Diag(Tok, diag::err_omp_declare_target_unexpected_enter_clause);
  1689. break;
  1690. }
  1691. if (!IsDeviceTypeClause && !IsIndirectClause &&
  1692. DTCI.Kind == OMPD_begin_declare_target) {
  1693. Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
  1694. << ClauseName << (getLangOpts().OpenMP >= 51 ? 3 : 0);
  1695. break;
  1696. }
  1697. if (!IsDeviceTypeClause && !IsToEnterOrLinkClause && !IsIndirectClause) {
  1698. Diag(Tok, getLangOpts().OpenMP >= 52
  1699. ? diag::err_omp_declare_target_unexpected_clause_52
  1700. : diag::err_omp_declare_target_unexpected_clause)
  1701. << ClauseName
  1702. << (getLangOpts().OpenMP >= 51
  1703. ? 4
  1704. : getLangOpts().OpenMP >= 50 ? 2 : 1);
  1705. break;
  1706. }
  1707. if (IsToEnterOrLinkClause || IsIndirectClause)
  1708. HasToOrLinkOrIndirectClause = true;
  1709. if (IsIndirectClause) {
  1710. if (!ParseOpenMPIndirectClause(DTCI, /*ParseOnly*/ false))
  1711. break;
  1712. continue;
  1713. }
  1714. // Parse 'device_type' clause and go to next clause if any.
  1715. if (IsDeviceTypeClause) {
  1716. std::optional<SimpleClauseData> DevTypeData =
  1717. parseOpenMPSimpleClause(*this, OMPC_device_type);
  1718. if (DevTypeData) {
  1719. if (DeviceTypeLoc.isValid()) {
  1720. // We already saw another device_type clause, diagnose it.
  1721. Diag(DevTypeData->Loc,
  1722. diag::warn_omp_more_one_device_type_clause);
  1723. break;
  1724. }
  1725. switch (static_cast<OpenMPDeviceType>(DevTypeData->Type)) {
  1726. case OMPC_DEVICE_TYPE_any:
  1727. DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any;
  1728. break;
  1729. case OMPC_DEVICE_TYPE_host:
  1730. DTCI.DT = OMPDeclareTargetDeclAttr::DT_Host;
  1731. break;
  1732. case OMPC_DEVICE_TYPE_nohost:
  1733. DTCI.DT = OMPDeclareTargetDeclAttr::DT_NoHost;
  1734. break;
  1735. case OMPC_DEVICE_TYPE_unknown:
  1736. llvm_unreachable("Unexpected device_type");
  1737. }
  1738. DeviceTypeLoc = DevTypeData->Loc;
  1739. }
  1740. continue;
  1741. }
  1742. ConsumeToken();
  1743. }
  1744. if (DTCI.Kind == OMPD_declare_target || HasIdentifier) {
  1745. auto &&Callback = [this, MT, &DTCI](CXXScopeSpec &SS,
  1746. DeclarationNameInfo NameInfo) {
  1747. NamedDecl *ND =
  1748. Actions.lookupOpenMPDeclareTargetName(getCurScope(), SS, NameInfo);
  1749. if (!ND)
  1750. return;
  1751. Sema::DeclareTargetContextInfo::MapInfo MI{MT, NameInfo.getLoc()};
  1752. bool FirstMapping = DTCI.ExplicitlyMapped.try_emplace(ND, MI).second;
  1753. if (!FirstMapping)
  1754. Diag(NameInfo.getLoc(), diag::err_omp_declare_target_multiple)
  1755. << NameInfo.getName();
  1756. };
  1757. if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback,
  1758. /*AllowScopeSpecifier=*/true))
  1759. break;
  1760. }
  1761. if (Tok.is(tok::l_paren)) {
  1762. Diag(Tok,
  1763. diag::err_omp_begin_declare_target_unexpected_implicit_to_clause);
  1764. break;
  1765. }
  1766. if (!HasIdentifier && Tok.isNot(tok::annot_pragma_openmp_end)) {
  1767. Diag(Tok,
  1768. getLangOpts().OpenMP >= 52
  1769. ? diag::err_omp_declare_target_wrong_clause_after_implicit_enter
  1770. : diag::err_omp_declare_target_wrong_clause_after_implicit_to);
  1771. break;
  1772. }
  1773. // Consume optional ','.
  1774. if (Tok.is(tok::comma))
  1775. ConsumeToken();
  1776. }
  1777. if (DTCI.Indirect && DTCI.DT != OMPDeclareTargetDeclAttr::DT_Any)
  1778. Diag(DeviceTypeLoc, diag::err_omp_declare_target_indirect_device_type);
  1779. // For declare target require at least 'to' or 'link' to be present.
  1780. if (DTCI.Kind == OMPD_declare_target && RequiresToOrLinkOrIndirectClause &&
  1781. !HasToOrLinkOrIndirectClause)
  1782. Diag(DTCI.Loc,
  1783. getLangOpts().OpenMP >= 52
  1784. ? diag::err_omp_declare_target_missing_enter_or_link_clause
  1785. : diag::err_omp_declare_target_missing_to_or_link_clause)
  1786. << (getLangOpts().OpenMP >= 51 ? 1 : 0);
  1787. SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
  1788. }
  1789. void Parser::skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind) {
  1790. // The last seen token is annot_pragma_openmp_end - need to check for
  1791. // extra tokens.
  1792. if (Tok.is(tok::annot_pragma_openmp_end))
  1793. return;
  1794. Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
  1795. << getOpenMPDirectiveName(DKind);
  1796. while (Tok.isNot(tok::annot_pragma_openmp_end))
  1797. ConsumeAnyToken();
  1798. }
  1799. void Parser::parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
  1800. OpenMPDirectiveKind ExpectedKind,
  1801. OpenMPDirectiveKind FoundKind,
  1802. SourceLocation BeginLoc,
  1803. SourceLocation FoundLoc,
  1804. bool SkipUntilOpenMPEnd) {
  1805. int DiagSelection = ExpectedKind == OMPD_end_declare_target ? 0 : 1;
  1806. if (FoundKind == ExpectedKind) {
  1807. ConsumeAnyToken();
  1808. skipUntilPragmaOpenMPEnd(ExpectedKind);
  1809. return;
  1810. }
  1811. Diag(FoundLoc, diag::err_expected_end_declare_target_or_variant)
  1812. << DiagSelection;
  1813. Diag(BeginLoc, diag::note_matching)
  1814. << ("'#pragma omp " + getOpenMPDirectiveName(BeginKind) + "'").str();
  1815. if (SkipUntilOpenMPEnd)
  1816. SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
  1817. }
  1818. void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
  1819. OpenMPDirectiveKind EndDKind,
  1820. SourceLocation DKLoc) {
  1821. parseOMPEndDirective(BeginDKind, OMPD_end_declare_target, EndDKind, DKLoc,
  1822. Tok.getLocation(),
  1823. /* SkipUntilOpenMPEnd */ false);
  1824. // Skip the last annot_pragma_openmp_end.
  1825. if (Tok.is(tok::annot_pragma_openmp_end))
  1826. ConsumeAnnotationToken();
  1827. }
  1828. /// Parsing of declarative OpenMP directives.
  1829. ///
  1830. /// threadprivate-directive:
  1831. /// annot_pragma_openmp 'threadprivate' simple-variable-list
  1832. /// annot_pragma_openmp_end
  1833. ///
  1834. /// allocate-directive:
  1835. /// annot_pragma_openmp 'allocate' simple-variable-list [<clause>]
  1836. /// annot_pragma_openmp_end
  1837. ///
  1838. /// declare-reduction-directive:
  1839. /// annot_pragma_openmp 'declare' 'reduction' [...]
  1840. /// annot_pragma_openmp_end
  1841. ///
  1842. /// declare-mapper-directive:
  1843. /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
  1844. /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
  1845. /// annot_pragma_openmp_end
  1846. ///
  1847. /// declare-simd-directive:
  1848. /// annot_pragma_openmp 'declare simd' {<clause> [,]}
  1849. /// annot_pragma_openmp_end
  1850. /// <function declaration/definition>
  1851. ///
  1852. /// requires directive:
  1853. /// annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ]
  1854. /// annot_pragma_openmp_end
  1855. ///
  1856. /// assumes directive:
  1857. /// annot_pragma_openmp 'assumes' <clause> [[[,] <clause>] ... ]
  1858. /// annot_pragma_openmp_end
  1859. /// or
  1860. /// annot_pragma_openmp 'begin assumes' <clause> [[[,] <clause>] ... ]
  1861. /// annot_pragma_openmp 'end assumes'
  1862. /// annot_pragma_openmp_end
  1863. ///
  1864. Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
  1865. AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed,
  1866. DeclSpec::TST TagType, Decl *Tag) {
  1867. assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) &&
  1868. "Not an OpenMP directive!");
  1869. ParsingOpenMPDirectiveRAII DirScope(*this);
  1870. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  1871. SourceLocation Loc;
  1872. OpenMPDirectiveKind DKind;
  1873. if (Delayed) {
  1874. TentativeParsingAction TPA(*this);
  1875. Loc = ConsumeAnnotationToken();
  1876. DKind = parseOpenMPDirectiveKind(*this);
  1877. if (DKind == OMPD_declare_reduction || DKind == OMPD_declare_mapper) {
  1878. // Need to delay parsing until completion of the parent class.
  1879. TPA.Revert();
  1880. CachedTokens Toks;
  1881. unsigned Cnt = 1;
  1882. Toks.push_back(Tok);
  1883. while (Cnt && Tok.isNot(tok::eof)) {
  1884. (void)ConsumeAnyToken();
  1885. if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp))
  1886. ++Cnt;
  1887. else if (Tok.is(tok::annot_pragma_openmp_end))
  1888. --Cnt;
  1889. Toks.push_back(Tok);
  1890. }
  1891. // Skip last annot_pragma_openmp_end.
  1892. if (Cnt == 0)
  1893. (void)ConsumeAnyToken();
  1894. auto *LP = new LateParsedPragma(this, AS);
  1895. LP->takeToks(Toks);
  1896. getCurrentClass().LateParsedDeclarations.push_back(LP);
  1897. return nullptr;
  1898. }
  1899. TPA.Commit();
  1900. } else {
  1901. Loc = ConsumeAnnotationToken();
  1902. DKind = parseOpenMPDirectiveKind(*this);
  1903. }
  1904. switch (DKind) {
  1905. case OMPD_threadprivate: {
  1906. ConsumeToken();
  1907. DeclDirectiveListParserHelper Helper(this, DKind);
  1908. if (!ParseOpenMPSimpleVarList(DKind, Helper,
  1909. /*AllowScopeSpecifier=*/true)) {
  1910. skipUntilPragmaOpenMPEnd(DKind);
  1911. // Skip the last annot_pragma_openmp_end.
  1912. ConsumeAnnotationToken();
  1913. return Actions.ActOnOpenMPThreadprivateDirective(Loc,
  1914. Helper.getIdentifiers());
  1915. }
  1916. break;
  1917. }
  1918. case OMPD_allocate: {
  1919. ConsumeToken();
  1920. DeclDirectiveListParserHelper Helper(this, DKind);
  1921. if (!ParseOpenMPSimpleVarList(DKind, Helper,
  1922. /*AllowScopeSpecifier=*/true)) {
  1923. SmallVector<OMPClause *, 1> Clauses;
  1924. if (Tok.isNot(tok::annot_pragma_openmp_end)) {
  1925. SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
  1926. llvm::omp::Clause_enumSize + 1>
  1927. FirstClauses(llvm::omp::Clause_enumSize + 1);
  1928. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  1929. OpenMPClauseKind CKind =
  1930. Tok.isAnnotation() ? OMPC_unknown
  1931. : getOpenMPClauseKind(PP.getSpelling(Tok));
  1932. Actions.StartOpenMPClause(CKind);
  1933. OMPClause *Clause = ParseOpenMPClause(
  1934. OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
  1935. SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
  1936. StopBeforeMatch);
  1937. FirstClauses[unsigned(CKind)].setInt(true);
  1938. if (Clause != nullptr)
  1939. Clauses.push_back(Clause);
  1940. if (Tok.is(tok::annot_pragma_openmp_end)) {
  1941. Actions.EndOpenMPClause();
  1942. break;
  1943. }
  1944. // Skip ',' if any.
  1945. if (Tok.is(tok::comma))
  1946. ConsumeToken();
  1947. Actions.EndOpenMPClause();
  1948. }
  1949. skipUntilPragmaOpenMPEnd(DKind);
  1950. }
  1951. // Skip the last annot_pragma_openmp_end.
  1952. ConsumeAnnotationToken();
  1953. return Actions.ActOnOpenMPAllocateDirective(Loc, Helper.getIdentifiers(),
  1954. Clauses);
  1955. }
  1956. break;
  1957. }
  1958. case OMPD_requires: {
  1959. SourceLocation StartLoc = ConsumeToken();
  1960. SmallVector<OMPClause *, 5> Clauses;
  1961. SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
  1962. llvm::omp::Clause_enumSize + 1>
  1963. FirstClauses(llvm::omp::Clause_enumSize + 1);
  1964. if (Tok.is(tok::annot_pragma_openmp_end)) {
  1965. Diag(Tok, diag::err_omp_expected_clause)
  1966. << getOpenMPDirectiveName(OMPD_requires);
  1967. break;
  1968. }
  1969. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  1970. OpenMPClauseKind CKind = Tok.isAnnotation()
  1971. ? OMPC_unknown
  1972. : getOpenMPClauseKind(PP.getSpelling(Tok));
  1973. Actions.StartOpenMPClause(CKind);
  1974. OMPClause *Clause = ParseOpenMPClause(
  1975. OMPD_requires, CKind, !FirstClauses[unsigned(CKind)].getInt());
  1976. SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
  1977. StopBeforeMatch);
  1978. FirstClauses[unsigned(CKind)].setInt(true);
  1979. if (Clause != nullptr)
  1980. Clauses.push_back(Clause);
  1981. if (Tok.is(tok::annot_pragma_openmp_end)) {
  1982. Actions.EndOpenMPClause();
  1983. break;
  1984. }
  1985. // Skip ',' if any.
  1986. if (Tok.is(tok::comma))
  1987. ConsumeToken();
  1988. Actions.EndOpenMPClause();
  1989. }
  1990. // Consume final annot_pragma_openmp_end
  1991. if (Clauses.empty()) {
  1992. Diag(Tok, diag::err_omp_expected_clause)
  1993. << getOpenMPDirectiveName(OMPD_requires);
  1994. ConsumeAnnotationToken();
  1995. return nullptr;
  1996. }
  1997. ConsumeAnnotationToken();
  1998. return Actions.ActOnOpenMPRequiresDirective(StartLoc, Clauses);
  1999. }
  2000. case OMPD_error: {
  2001. SmallVector<OMPClause *, 1> Clauses;
  2002. SourceLocation StartLoc = ConsumeToken();
  2003. ParseOpenMPClauses(DKind, Clauses, StartLoc);
  2004. Actions.ActOnOpenMPErrorDirective(Clauses, StartLoc, SourceLocation(),
  2005. /*InExContext = */ false);
  2006. break;
  2007. }
  2008. case OMPD_assumes:
  2009. case OMPD_begin_assumes:
  2010. ParseOpenMPAssumesDirective(DKind, ConsumeToken());
  2011. break;
  2012. case OMPD_end_assumes:
  2013. ParseOpenMPEndAssumesDirective(ConsumeToken());
  2014. break;
  2015. case OMPD_declare_reduction:
  2016. ConsumeToken();
  2017. if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) {
  2018. skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
  2019. // Skip the last annot_pragma_openmp_end.
  2020. ConsumeAnnotationToken();
  2021. return Res;
  2022. }
  2023. break;
  2024. case OMPD_declare_mapper: {
  2025. ConsumeToken();
  2026. if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) {
  2027. // Skip the last annot_pragma_openmp_end.
  2028. ConsumeAnnotationToken();
  2029. return Res;
  2030. }
  2031. break;
  2032. }
  2033. case OMPD_begin_declare_variant: {
  2034. // The syntax is:
  2035. // { #pragma omp begin declare variant clause }
  2036. // <function-declaration-or-definition-sequence>
  2037. // { #pragma omp end declare variant }
  2038. //
  2039. ConsumeToken();
  2040. OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope();
  2041. ASTContext &ASTCtx = Actions.getASTContext();
  2042. OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo();
  2043. if (parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI)) {
  2044. while (!SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch))
  2045. ;
  2046. // Skip the last annot_pragma_openmp_end.
  2047. (void)ConsumeAnnotationToken();
  2048. break;
  2049. }
  2050. // Skip last tokens.
  2051. skipUntilPragmaOpenMPEnd(OMPD_begin_declare_variant);
  2052. ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
  2053. VariantMatchInfo VMI;
  2054. TI.getAsVariantMatchInfo(ASTCtx, VMI);
  2055. std::function<void(StringRef)> DiagUnknownTrait =
  2056. [this, Loc](StringRef ISATrait) {
  2057. // TODO Track the selector locations in a way that is accessible here
  2058. // to improve the diagnostic location.
  2059. Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
  2060. };
  2061. TargetOMPContext OMPCtx(
  2062. ASTCtx, std::move(DiagUnknownTrait),
  2063. /* CurrentFunctionDecl */ nullptr,
  2064. /* ConstructTraits */ ArrayRef<llvm::omp::TraitProperty>());
  2065. if (isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ true)) {
  2066. Actions.ActOnOpenMPBeginDeclareVariant(Loc, TI);
  2067. break;
  2068. }
  2069. // Elide all the code till the matching end declare variant was found.
  2070. unsigned Nesting = 1;
  2071. SourceLocation DKLoc;
  2072. OpenMPDirectiveKind DK = OMPD_unknown;
  2073. do {
  2074. DKLoc = Tok.getLocation();
  2075. DK = parseOpenMPDirectiveKind(*this);
  2076. if (DK == OMPD_end_declare_variant)
  2077. --Nesting;
  2078. else if (DK == OMPD_begin_declare_variant)
  2079. ++Nesting;
  2080. if (!Nesting || isEofOrEom())
  2081. break;
  2082. ConsumeAnyToken();
  2083. } while (true);
  2084. parseOMPEndDirective(OMPD_begin_declare_variant, OMPD_end_declare_variant,
  2085. DK, Loc, DKLoc, /* SkipUntilOpenMPEnd */ true);
  2086. if (isEofOrEom())
  2087. return nullptr;
  2088. break;
  2089. }
  2090. case OMPD_end_declare_variant: {
  2091. if (Actions.isInOpenMPDeclareVariantScope())
  2092. Actions.ActOnOpenMPEndDeclareVariant();
  2093. else
  2094. Diag(Loc, diag::err_expected_begin_declare_variant);
  2095. ConsumeToken();
  2096. break;
  2097. }
  2098. case OMPD_declare_variant:
  2099. case OMPD_declare_simd: {
  2100. // The syntax is:
  2101. // { #pragma omp declare {simd|variant} }
  2102. // <function-declaration-or-definition>
  2103. //
  2104. CachedTokens Toks;
  2105. Toks.push_back(Tok);
  2106. ConsumeToken();
  2107. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  2108. Toks.push_back(Tok);
  2109. ConsumeAnyToken();
  2110. }
  2111. Toks.push_back(Tok);
  2112. ConsumeAnyToken();
  2113. DeclGroupPtrTy Ptr;
  2114. if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
  2115. Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, Delayed,
  2116. TagType, Tag);
  2117. } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  2118. // Here we expect to see some function declaration.
  2119. if (AS == AS_none) {
  2120. assert(TagType == DeclSpec::TST_unspecified);
  2121. ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
  2122. MaybeParseCXX11Attributes(Attrs);
  2123. ParsingDeclSpec PDS(*this);
  2124. Ptr = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs, &PDS);
  2125. } else {
  2126. Ptr =
  2127. ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
  2128. }
  2129. }
  2130. if (!Ptr) {
  2131. Diag(Loc, diag::err_omp_decl_in_declare_simd_variant)
  2132. << (DKind == OMPD_declare_simd ? 0 : 1);
  2133. return DeclGroupPtrTy();
  2134. }
  2135. if (DKind == OMPD_declare_simd)
  2136. return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
  2137. assert(DKind == OMPD_declare_variant &&
  2138. "Expected declare variant directive only");
  2139. ParseOMPDeclareVariantClauses(Ptr, Toks, Loc);
  2140. return Ptr;
  2141. }
  2142. case OMPD_begin_declare_target:
  2143. case OMPD_declare_target: {
  2144. SourceLocation DTLoc = ConsumeAnyToken();
  2145. bool HasClauses = Tok.isNot(tok::annot_pragma_openmp_end);
  2146. Sema::DeclareTargetContextInfo DTCI(DKind, DTLoc);
  2147. if (HasClauses)
  2148. ParseOMPDeclareTargetClauses(DTCI);
  2149. bool HasImplicitMappings = DKind == OMPD_begin_declare_target ||
  2150. !HasClauses ||
  2151. (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect);
  2152. // Skip the last annot_pragma_openmp_end.
  2153. ConsumeAnyToken();
  2154. if (HasImplicitMappings) {
  2155. Actions.ActOnStartOpenMPDeclareTargetContext(DTCI);
  2156. return nullptr;
  2157. }
  2158. Actions.ActOnFinishedOpenMPDeclareTargetContext(DTCI);
  2159. llvm::SmallVector<Decl *, 4> Decls;
  2160. for (auto &It : DTCI.ExplicitlyMapped)
  2161. Decls.push_back(It.first);
  2162. return Actions.BuildDeclaratorGroup(Decls);
  2163. }
  2164. case OMPD_end_declare_target: {
  2165. if (!Actions.isInOpenMPDeclareTargetContext()) {
  2166. Diag(Tok, diag::err_omp_unexpected_directive)
  2167. << 1 << getOpenMPDirectiveName(DKind);
  2168. break;
  2169. }
  2170. const Sema::DeclareTargetContextInfo &DTCI =
  2171. Actions.ActOnOpenMPEndDeclareTargetDirective();
  2172. ParseOMPEndDeclareTargetDirective(DTCI.Kind, DKind, DTCI.Loc);
  2173. return nullptr;
  2174. }
  2175. case OMPD_unknown:
  2176. Diag(Tok, diag::err_omp_unknown_directive);
  2177. break;
  2178. case OMPD_parallel:
  2179. case OMPD_simd:
  2180. case OMPD_tile:
  2181. case OMPD_unroll:
  2182. case OMPD_task:
  2183. case OMPD_taskyield:
  2184. case OMPD_barrier:
  2185. case OMPD_taskwait:
  2186. case OMPD_taskgroup:
  2187. case OMPD_flush:
  2188. case OMPD_depobj:
  2189. case OMPD_scan:
  2190. case OMPD_for:
  2191. case OMPD_for_simd:
  2192. case OMPD_sections:
  2193. case OMPD_section:
  2194. case OMPD_single:
  2195. case OMPD_master:
  2196. case OMPD_ordered:
  2197. case OMPD_critical:
  2198. case OMPD_parallel_for:
  2199. case OMPD_parallel_for_simd:
  2200. case OMPD_parallel_sections:
  2201. case OMPD_parallel_master:
  2202. case OMPD_parallel_masked:
  2203. case OMPD_atomic:
  2204. case OMPD_target:
  2205. case OMPD_teams:
  2206. case OMPD_cancellation_point:
  2207. case OMPD_cancel:
  2208. case OMPD_target_data:
  2209. case OMPD_target_enter_data:
  2210. case OMPD_target_exit_data:
  2211. case OMPD_target_parallel:
  2212. case OMPD_target_parallel_for:
  2213. case OMPD_taskloop:
  2214. case OMPD_taskloop_simd:
  2215. case OMPD_master_taskloop:
  2216. case OMPD_master_taskloop_simd:
  2217. case OMPD_parallel_master_taskloop:
  2218. case OMPD_parallel_master_taskloop_simd:
  2219. case OMPD_masked_taskloop:
  2220. case OMPD_masked_taskloop_simd:
  2221. case OMPD_parallel_masked_taskloop:
  2222. case OMPD_parallel_masked_taskloop_simd:
  2223. case OMPD_distribute:
  2224. case OMPD_target_update:
  2225. case OMPD_distribute_parallel_for:
  2226. case OMPD_distribute_parallel_for_simd:
  2227. case OMPD_distribute_simd:
  2228. case OMPD_target_parallel_for_simd:
  2229. case OMPD_target_simd:
  2230. case OMPD_teams_distribute:
  2231. case OMPD_teams_distribute_simd:
  2232. case OMPD_teams_distribute_parallel_for_simd:
  2233. case OMPD_teams_distribute_parallel_for:
  2234. case OMPD_target_teams:
  2235. case OMPD_target_teams_distribute:
  2236. case OMPD_target_teams_distribute_parallel_for:
  2237. case OMPD_target_teams_distribute_parallel_for_simd:
  2238. case OMPD_target_teams_distribute_simd:
  2239. case OMPD_dispatch:
  2240. case OMPD_masked:
  2241. case OMPD_metadirective:
  2242. case OMPD_loop:
  2243. case OMPD_teams_loop:
  2244. case OMPD_target_teams_loop:
  2245. case OMPD_parallel_loop:
  2246. case OMPD_target_parallel_loop:
  2247. Diag(Tok, diag::err_omp_unexpected_directive)
  2248. << 1 << getOpenMPDirectiveName(DKind);
  2249. break;
  2250. default:
  2251. break;
  2252. }
  2253. while (Tok.isNot(tok::annot_pragma_openmp_end))
  2254. ConsumeAnyToken();
  2255. ConsumeAnyToken();
  2256. return nullptr;
  2257. }
  2258. /// Parsing of declarative or executable OpenMP directives.
  2259. ///
  2260. /// threadprivate-directive:
  2261. /// annot_pragma_openmp 'threadprivate' simple-variable-list
  2262. /// annot_pragma_openmp_end
  2263. ///
  2264. /// allocate-directive:
  2265. /// annot_pragma_openmp 'allocate' simple-variable-list
  2266. /// annot_pragma_openmp_end
  2267. ///
  2268. /// declare-reduction-directive:
  2269. /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
  2270. /// <type> {',' <type>} ':' <expression> ')' ['initializer' '('
  2271. /// ('omp_priv' '=' <expression>|<function_call>) ')']
  2272. /// annot_pragma_openmp_end
  2273. ///
  2274. /// declare-mapper-directive:
  2275. /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
  2276. /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
  2277. /// annot_pragma_openmp_end
  2278. ///
  2279. /// executable-directive:
  2280. /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
  2281. /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
  2282. /// 'parallel for' | 'parallel sections' | 'parallel master' | 'task' |
  2283. /// 'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' | 'error'
  2284. /// | 'atomic' | 'for simd' | 'parallel for simd' | 'target' | 'target
  2285. /// data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
  2286. /// 'master taskloop' | 'master taskloop simd' | 'parallel master
  2287. /// taskloop' | 'parallel master taskloop simd' | 'distribute' | 'target
  2288. /// enter data' | 'target exit data' | 'target parallel' | 'target
  2289. /// parallel for' | 'target update' | 'distribute parallel for' |
  2290. /// 'distribute paralle for simd' | 'distribute simd' | 'target parallel
  2291. /// for simd' | 'target simd' | 'teams distribute' | 'teams distribute
  2292. /// simd' | 'teams distribute parallel for simd' | 'teams distribute
  2293. /// parallel for' | 'target teams' | 'target teams distribute' | 'target
  2294. /// teams distribute parallel for' | 'target teams distribute parallel
  2295. /// for simd' | 'target teams distribute simd' | 'masked' {clause}
  2296. /// annot_pragma_openmp_end
  2297. ///
  2298. StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
  2299. ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective) {
  2300. if (!ReadDirectiveWithinMetadirective)
  2301. assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) &&
  2302. "Not an OpenMP directive!");
  2303. ParsingOpenMPDirectiveRAII DirScope(*this);
  2304. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  2305. SmallVector<OMPClause *, 5> Clauses;
  2306. SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
  2307. llvm::omp::Clause_enumSize + 1>
  2308. FirstClauses(llvm::omp::Clause_enumSize + 1);
  2309. unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
  2310. Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
  2311. SourceLocation Loc = ReadDirectiveWithinMetadirective
  2312. ? Tok.getLocation()
  2313. : ConsumeAnnotationToken(),
  2314. EndLoc;
  2315. OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this);
  2316. if (ReadDirectiveWithinMetadirective && DKind == OMPD_unknown) {
  2317. Diag(Tok, diag::err_omp_unknown_directive);
  2318. return StmtError();
  2319. }
  2320. OpenMPDirectiveKind CancelRegion = OMPD_unknown;
  2321. // Name of critical directive.
  2322. DeclarationNameInfo DirName;
  2323. StmtResult Directive = StmtError();
  2324. bool HasAssociatedStatement = true;
  2325. switch (DKind) {
  2326. case OMPD_nothing:
  2327. if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
  2328. ParsedStmtContext())
  2329. Diag(Tok, diag::err_omp_immediate_directive)
  2330. << getOpenMPDirectiveName(DKind) << 0;
  2331. ConsumeToken();
  2332. skipUntilPragmaOpenMPEnd(DKind);
  2333. if (Tok.is(tok::annot_pragma_openmp_end))
  2334. ConsumeAnnotationToken();
  2335. break;
  2336. case OMPD_metadirective: {
  2337. ConsumeToken();
  2338. SmallVector<VariantMatchInfo, 4> VMIs;
  2339. // First iteration of parsing all clauses of metadirective.
  2340. // This iteration only parses and collects all context selector ignoring the
  2341. // associated directives.
  2342. TentativeParsingAction TPA(*this);
  2343. ASTContext &ASTContext = Actions.getASTContext();
  2344. BalancedDelimiterTracker T(*this, tok::l_paren,
  2345. tok::annot_pragma_openmp_end);
  2346. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  2347. OpenMPClauseKind CKind = Tok.isAnnotation()
  2348. ? OMPC_unknown
  2349. : getOpenMPClauseKind(PP.getSpelling(Tok));
  2350. SourceLocation Loc = ConsumeToken();
  2351. // Parse '('.
  2352. if (T.expectAndConsume(diag::err_expected_lparen_after,
  2353. getOpenMPClauseName(CKind).data()))
  2354. return Directive;
  2355. OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
  2356. if (CKind == OMPC_when) {
  2357. // parse and get OMPTraitInfo to pass to the When clause
  2358. parseOMPContextSelectors(Loc, TI);
  2359. if (TI.Sets.size() == 0) {
  2360. Diag(Tok, diag::err_omp_expected_context_selector) << "when clause";
  2361. TPA.Commit();
  2362. return Directive;
  2363. }
  2364. // Parse ':'
  2365. if (Tok.is(tok::colon))
  2366. ConsumeAnyToken();
  2367. else {
  2368. Diag(Tok, diag::err_omp_expected_colon) << "when clause";
  2369. TPA.Commit();
  2370. return Directive;
  2371. }
  2372. }
  2373. // Skip Directive for now. We will parse directive in the second iteration
  2374. int paren = 0;
  2375. while (Tok.isNot(tok::r_paren) || paren != 0) {
  2376. if (Tok.is(tok::l_paren))
  2377. paren++;
  2378. if (Tok.is(tok::r_paren))
  2379. paren--;
  2380. if (Tok.is(tok::annot_pragma_openmp_end)) {
  2381. Diag(Tok, diag::err_omp_expected_punc)
  2382. << getOpenMPClauseName(CKind) << 0;
  2383. TPA.Commit();
  2384. return Directive;
  2385. }
  2386. ConsumeAnyToken();
  2387. }
  2388. // Parse ')'
  2389. if (Tok.is(tok::r_paren))
  2390. T.consumeClose();
  2391. VariantMatchInfo VMI;
  2392. TI.getAsVariantMatchInfo(ASTContext, VMI);
  2393. VMIs.push_back(VMI);
  2394. }
  2395. TPA.Revert();
  2396. // End of the first iteration. Parser is reset to the start of metadirective
  2397. std::function<void(StringRef)> DiagUnknownTrait =
  2398. [this, Loc](StringRef ISATrait) {
  2399. // TODO Track the selector locations in a way that is accessible here
  2400. // to improve the diagnostic location.
  2401. Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
  2402. };
  2403. TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait),
  2404. /* CurrentFunctionDecl */ nullptr,
  2405. ArrayRef<llvm::omp::TraitProperty>());
  2406. // A single match is returned for OpenMP 5.0
  2407. int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
  2408. int Idx = 0;
  2409. // In OpenMP 5.0 metadirective is either replaced by another directive or
  2410. // ignored.
  2411. // TODO: In OpenMP 5.1 generate multiple directives based upon the matches
  2412. // found by getBestWhenMatchForContext.
  2413. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  2414. // OpenMP 5.0 implementation - Skip to the best index found.
  2415. if (Idx++ != BestIdx) {
  2416. ConsumeToken(); // Consume clause name
  2417. T.consumeOpen(); // Consume '('
  2418. int paren = 0;
  2419. // Skip everything inside the clause
  2420. while (Tok.isNot(tok::r_paren) || paren != 0) {
  2421. if (Tok.is(tok::l_paren))
  2422. paren++;
  2423. if (Tok.is(tok::r_paren))
  2424. paren--;
  2425. ConsumeAnyToken();
  2426. }
  2427. // Parse ')'
  2428. if (Tok.is(tok::r_paren))
  2429. T.consumeClose();
  2430. continue;
  2431. }
  2432. OpenMPClauseKind CKind = Tok.isAnnotation()
  2433. ? OMPC_unknown
  2434. : getOpenMPClauseKind(PP.getSpelling(Tok));
  2435. SourceLocation Loc = ConsumeToken();
  2436. // Parse '('.
  2437. T.consumeOpen();
  2438. // Skip ContextSelectors for when clause
  2439. if (CKind == OMPC_when) {
  2440. OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
  2441. // parse and skip the ContextSelectors
  2442. parseOMPContextSelectors(Loc, TI);
  2443. // Parse ':'
  2444. ConsumeAnyToken();
  2445. }
  2446. // If no directive is passed, skip in OpenMP 5.0.
  2447. // TODO: Generate nothing directive from OpenMP 5.1.
  2448. if (Tok.is(tok::r_paren)) {
  2449. SkipUntil(tok::annot_pragma_openmp_end);
  2450. break;
  2451. }
  2452. // Parse Directive
  2453. Directive = ParseOpenMPDeclarativeOrExecutableDirective(
  2454. StmtCtx,
  2455. /*ReadDirectiveWithinMetadirective=*/true);
  2456. break;
  2457. }
  2458. break;
  2459. }
  2460. case OMPD_threadprivate: {
  2461. // FIXME: Should this be permitted in C++?
  2462. if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
  2463. ParsedStmtContext()) {
  2464. Diag(Tok, diag::err_omp_immediate_directive)
  2465. << getOpenMPDirectiveName(DKind) << 0;
  2466. }
  2467. ConsumeToken();
  2468. DeclDirectiveListParserHelper Helper(this, DKind);
  2469. if (!ParseOpenMPSimpleVarList(DKind, Helper,
  2470. /*AllowScopeSpecifier=*/false)) {
  2471. skipUntilPragmaOpenMPEnd(DKind);
  2472. DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
  2473. Loc, Helper.getIdentifiers());
  2474. Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
  2475. }
  2476. SkipUntil(tok::annot_pragma_openmp_end);
  2477. break;
  2478. }
  2479. case OMPD_allocate: {
  2480. // FIXME: Should this be permitted in C++?
  2481. if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
  2482. ParsedStmtContext()) {
  2483. Diag(Tok, diag::err_omp_immediate_directive)
  2484. << getOpenMPDirectiveName(DKind) << 0;
  2485. }
  2486. ConsumeToken();
  2487. DeclDirectiveListParserHelper Helper(this, DKind);
  2488. if (!ParseOpenMPSimpleVarList(DKind, Helper,
  2489. /*AllowScopeSpecifier=*/false)) {
  2490. SmallVector<OMPClause *, 1> Clauses;
  2491. if (Tok.isNot(tok::annot_pragma_openmp_end)) {
  2492. SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
  2493. llvm::omp::Clause_enumSize + 1>
  2494. FirstClauses(llvm::omp::Clause_enumSize + 1);
  2495. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  2496. OpenMPClauseKind CKind =
  2497. Tok.isAnnotation() ? OMPC_unknown
  2498. : getOpenMPClauseKind(PP.getSpelling(Tok));
  2499. Actions.StartOpenMPClause(CKind);
  2500. OMPClause *Clause = ParseOpenMPClause(
  2501. OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
  2502. SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
  2503. StopBeforeMatch);
  2504. FirstClauses[unsigned(CKind)].setInt(true);
  2505. if (Clause != nullptr)
  2506. Clauses.push_back(Clause);
  2507. if (Tok.is(tok::annot_pragma_openmp_end)) {
  2508. Actions.EndOpenMPClause();
  2509. break;
  2510. }
  2511. // Skip ',' if any.
  2512. if (Tok.is(tok::comma))
  2513. ConsumeToken();
  2514. Actions.EndOpenMPClause();
  2515. }
  2516. skipUntilPragmaOpenMPEnd(DKind);
  2517. }
  2518. DeclGroupPtrTy Res = Actions.ActOnOpenMPAllocateDirective(
  2519. Loc, Helper.getIdentifiers(), Clauses);
  2520. Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
  2521. }
  2522. SkipUntil(tok::annot_pragma_openmp_end);
  2523. break;
  2524. }
  2525. case OMPD_declare_reduction:
  2526. ConsumeToken();
  2527. if (DeclGroupPtrTy Res =
  2528. ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
  2529. skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
  2530. ConsumeAnyToken();
  2531. Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
  2532. } else {
  2533. SkipUntil(tok::annot_pragma_openmp_end);
  2534. }
  2535. break;
  2536. case OMPD_declare_mapper: {
  2537. ConsumeToken();
  2538. if (DeclGroupPtrTy Res =
  2539. ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) {
  2540. // Skip the last annot_pragma_openmp_end.
  2541. ConsumeAnnotationToken();
  2542. Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
  2543. } else {
  2544. SkipUntil(tok::annot_pragma_openmp_end);
  2545. }
  2546. break;
  2547. }
  2548. case OMPD_flush:
  2549. case OMPD_depobj:
  2550. case OMPD_scan:
  2551. case OMPD_taskyield:
  2552. case OMPD_error:
  2553. case OMPD_barrier:
  2554. case OMPD_taskwait:
  2555. case OMPD_cancellation_point:
  2556. case OMPD_cancel:
  2557. case OMPD_target_enter_data:
  2558. case OMPD_target_exit_data:
  2559. case OMPD_target_update:
  2560. case OMPD_interop:
  2561. if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
  2562. ParsedStmtContext()) {
  2563. Diag(Tok, diag::err_omp_immediate_directive)
  2564. << getOpenMPDirectiveName(DKind) << 0;
  2565. if (DKind == OMPD_error) {
  2566. SkipUntil(tok::annot_pragma_openmp_end);
  2567. break;
  2568. }
  2569. }
  2570. HasAssociatedStatement = false;
  2571. // Fall through for further analysis.
  2572. [[fallthrough]];
  2573. case OMPD_parallel:
  2574. case OMPD_simd:
  2575. case OMPD_tile:
  2576. case OMPD_unroll:
  2577. case OMPD_for:
  2578. case OMPD_for_simd:
  2579. case OMPD_sections:
  2580. case OMPD_single:
  2581. case OMPD_section:
  2582. case OMPD_master:
  2583. case OMPD_critical:
  2584. case OMPD_parallel_for:
  2585. case OMPD_parallel_for_simd:
  2586. case OMPD_parallel_sections:
  2587. case OMPD_parallel_master:
  2588. case OMPD_parallel_masked:
  2589. case OMPD_task:
  2590. case OMPD_ordered:
  2591. case OMPD_atomic:
  2592. case OMPD_target:
  2593. case OMPD_teams:
  2594. case OMPD_taskgroup:
  2595. case OMPD_target_data:
  2596. case OMPD_target_parallel:
  2597. case OMPD_target_parallel_for:
  2598. case OMPD_loop:
  2599. case OMPD_teams_loop:
  2600. case OMPD_target_teams_loop:
  2601. case OMPD_parallel_loop:
  2602. case OMPD_target_parallel_loop:
  2603. case OMPD_taskloop:
  2604. case OMPD_taskloop_simd:
  2605. case OMPD_master_taskloop:
  2606. case OMPD_masked_taskloop:
  2607. case OMPD_master_taskloop_simd:
  2608. case OMPD_masked_taskloop_simd:
  2609. case OMPD_parallel_master_taskloop:
  2610. case OMPD_parallel_masked_taskloop:
  2611. case OMPD_parallel_master_taskloop_simd:
  2612. case OMPD_parallel_masked_taskloop_simd:
  2613. case OMPD_distribute:
  2614. case OMPD_distribute_parallel_for:
  2615. case OMPD_distribute_parallel_for_simd:
  2616. case OMPD_distribute_simd:
  2617. case OMPD_target_parallel_for_simd:
  2618. case OMPD_target_simd:
  2619. case OMPD_teams_distribute:
  2620. case OMPD_teams_distribute_simd:
  2621. case OMPD_teams_distribute_parallel_for_simd:
  2622. case OMPD_teams_distribute_parallel_for:
  2623. case OMPD_target_teams:
  2624. case OMPD_target_teams_distribute:
  2625. case OMPD_target_teams_distribute_parallel_for:
  2626. case OMPD_target_teams_distribute_parallel_for_simd:
  2627. case OMPD_target_teams_distribute_simd:
  2628. case OMPD_dispatch:
  2629. case OMPD_masked: {
  2630. // Special processing for flush and depobj clauses.
  2631. Token ImplicitTok;
  2632. bool ImplicitClauseAllowed = false;
  2633. if (DKind == OMPD_flush || DKind == OMPD_depobj) {
  2634. ImplicitTok = Tok;
  2635. ImplicitClauseAllowed = true;
  2636. }
  2637. ConsumeToken();
  2638. // Parse directive name of the 'critical' directive if any.
  2639. if (DKind == OMPD_critical) {
  2640. BalancedDelimiterTracker T(*this, tok::l_paren,
  2641. tok::annot_pragma_openmp_end);
  2642. if (!T.consumeOpen()) {
  2643. if (Tok.isAnyIdentifier()) {
  2644. DirName =
  2645. DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
  2646. ConsumeAnyToken();
  2647. } else {
  2648. Diag(Tok, diag::err_omp_expected_identifier_for_critical);
  2649. }
  2650. T.consumeClose();
  2651. }
  2652. } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
  2653. CancelRegion = parseOpenMPDirectiveKind(*this);
  2654. if (Tok.isNot(tok::annot_pragma_openmp_end))
  2655. ConsumeToken();
  2656. }
  2657. if (isOpenMPLoopDirective(DKind))
  2658. ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
  2659. if (isOpenMPSimdDirective(DKind))
  2660. ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
  2661. ParseScope OMPDirectiveScope(this, ScopeFlags);
  2662. Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
  2663. while (Tok.isNot(tok::annot_pragma_openmp_end)) {
  2664. // If we are parsing for a directive within a metadirective, the directive
  2665. // ends with a ')'.
  2666. if (ReadDirectiveWithinMetadirective && Tok.is(tok::r_paren)) {
  2667. while (Tok.isNot(tok::annot_pragma_openmp_end))
  2668. ConsumeAnyToken();
  2669. break;
  2670. }
  2671. bool HasImplicitClause = false;
  2672. if (ImplicitClauseAllowed && Tok.is(tok::l_paren)) {
  2673. HasImplicitClause = true;
  2674. // Push copy of the current token back to stream to properly parse
  2675. // pseudo-clause OMPFlushClause or OMPDepobjClause.
  2676. PP.EnterToken(Tok, /*IsReinject*/ true);
  2677. PP.EnterToken(ImplicitTok, /*IsReinject*/ true);
  2678. ConsumeAnyToken();
  2679. }
  2680. OpenMPClauseKind CKind = Tok.isAnnotation()
  2681. ? OMPC_unknown
  2682. : getOpenMPClauseKind(PP.getSpelling(Tok));
  2683. if (HasImplicitClause) {
  2684. assert(CKind == OMPC_unknown && "Must be unknown implicit clause.");
  2685. if (DKind == OMPD_flush) {
  2686. CKind = OMPC_flush;
  2687. } else {
  2688. assert(DKind == OMPD_depobj &&
  2689. "Expected flush or depobj directives.");
  2690. CKind = OMPC_depobj;
  2691. }
  2692. }
  2693. // No more implicit clauses allowed.
  2694. ImplicitClauseAllowed = false;
  2695. Actions.StartOpenMPClause(CKind);
  2696. HasImplicitClause = false;
  2697. OMPClause *Clause = ParseOpenMPClause(
  2698. DKind, CKind, !FirstClauses[unsigned(CKind)].getInt());
  2699. FirstClauses[unsigned(CKind)].setInt(true);
  2700. if (Clause) {
  2701. FirstClauses[unsigned(CKind)].setPointer(Clause);
  2702. Clauses.push_back(Clause);
  2703. }
  2704. // Skip ',' if any.
  2705. if (Tok.is(tok::comma))
  2706. ConsumeToken();
  2707. Actions.EndOpenMPClause();
  2708. }
  2709. // End location of the directive.
  2710. EndLoc = Tok.getLocation();
  2711. // Consume final annot_pragma_openmp_end.
  2712. ConsumeAnnotationToken();
  2713. // OpenMP [2.13.8, ordered Construct, Syntax]
  2714. // If the depend clause is specified, the ordered construct is a stand-alone
  2715. // directive.
  2716. if (DKind == OMPD_ordered && FirstClauses[unsigned(OMPC_depend)].getInt()) {
  2717. if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
  2718. ParsedStmtContext()) {
  2719. Diag(Loc, diag::err_omp_immediate_directive)
  2720. << getOpenMPDirectiveName(DKind) << 1
  2721. << getOpenMPClauseName(OMPC_depend);
  2722. }
  2723. HasAssociatedStatement = false;
  2724. }
  2725. if (DKind == OMPD_tile && !FirstClauses[unsigned(OMPC_sizes)].getInt()) {
  2726. Diag(Loc, diag::err_omp_required_clause)
  2727. << getOpenMPDirectiveName(OMPD_tile) << "sizes";
  2728. }
  2729. StmtResult AssociatedStmt;
  2730. if (HasAssociatedStatement) {
  2731. // The body is a block scope like in Lambdas and Blocks.
  2732. Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
  2733. // FIXME: We create a bogus CompoundStmt scope to hold the contents of
  2734. // the captured region. Code elsewhere assumes that any FunctionScopeInfo
  2735. // should have at least one compound statement scope within it.
  2736. ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
  2737. {
  2738. Sema::CompoundScopeRAII Scope(Actions);
  2739. AssociatedStmt = ParseStatement();
  2740. if (AssociatedStmt.isUsable() && isOpenMPLoopDirective(DKind) &&
  2741. getLangOpts().OpenMPIRBuilder)
  2742. AssociatedStmt = Actions.ActOnOpenMPLoopnest(AssociatedStmt.get());
  2743. }
  2744. AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
  2745. } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data ||
  2746. DKind == OMPD_target_exit_data) {
  2747. Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
  2748. AssociatedStmt = (Sema::CompoundScopeRAII(Actions),
  2749. Actions.ActOnCompoundStmt(Loc, Loc, std::nullopt,
  2750. /*isStmtExpr=*/false));
  2751. AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
  2752. }
  2753. Directive = Actions.ActOnOpenMPExecutableDirective(
  2754. DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
  2755. EndLoc);
  2756. // Exit scope.
  2757. Actions.EndOpenMPDSABlock(Directive.get());
  2758. OMPDirectiveScope.Exit();
  2759. break;
  2760. }
  2761. case OMPD_declare_simd:
  2762. case OMPD_declare_target:
  2763. case OMPD_begin_declare_target:
  2764. case OMPD_end_declare_target:
  2765. case OMPD_requires:
  2766. case OMPD_begin_declare_variant:
  2767. case OMPD_end_declare_variant:
  2768. case OMPD_declare_variant:
  2769. Diag(Tok, diag::err_omp_unexpected_directive)
  2770. << 1 << getOpenMPDirectiveName(DKind);
  2771. SkipUntil(tok::annot_pragma_openmp_end);
  2772. break;
  2773. case OMPD_unknown:
  2774. default:
  2775. Diag(Tok, diag::err_omp_unknown_directive);
  2776. SkipUntil(tok::annot_pragma_openmp_end);
  2777. break;
  2778. }
  2779. return Directive;
  2780. }
  2781. // Parses simple list:
  2782. // simple-variable-list:
  2783. // '(' id-expression {, id-expression} ')'
  2784. //
  2785. bool Parser::ParseOpenMPSimpleVarList(
  2786. OpenMPDirectiveKind Kind,
  2787. const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)>
  2788. &Callback,
  2789. bool AllowScopeSpecifier) {
  2790. // Parse '('.
  2791. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  2792. if (T.expectAndConsume(diag::err_expected_lparen_after,
  2793. getOpenMPDirectiveName(Kind).data()))
  2794. return true;
  2795. bool IsCorrect = true;
  2796. bool NoIdentIsFound = true;
  2797. // Read tokens while ')' or annot_pragma_openmp_end is not found.
  2798. while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
  2799. CXXScopeSpec SS;
  2800. UnqualifiedId Name;
  2801. // Read var name.
  2802. Token PrevTok = Tok;
  2803. NoIdentIsFound = false;
  2804. if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
  2805. ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
  2806. /*ObjectHasErrors=*/false, false)) {
  2807. IsCorrect = false;
  2808. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  2809. StopBeforeMatch);
  2810. } else if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
  2811. /*ObjectHadErrors=*/false, false, false,
  2812. false, false, nullptr, Name)) {
  2813. IsCorrect = false;
  2814. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  2815. StopBeforeMatch);
  2816. } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
  2817. Tok.isNot(tok::annot_pragma_openmp_end)) {
  2818. IsCorrect = false;
  2819. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  2820. StopBeforeMatch);
  2821. Diag(PrevTok.getLocation(), diag::err_expected)
  2822. << tok::identifier
  2823. << SourceRange(PrevTok.getLocation(), PrevTokLocation);
  2824. } else {
  2825. Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
  2826. }
  2827. // Consume ','.
  2828. if (Tok.is(tok::comma)) {
  2829. ConsumeToken();
  2830. }
  2831. }
  2832. if (NoIdentIsFound) {
  2833. Diag(Tok, diag::err_expected) << tok::identifier;
  2834. IsCorrect = false;
  2835. }
  2836. // Parse ')'.
  2837. IsCorrect = !T.consumeClose() && IsCorrect;
  2838. return !IsCorrect;
  2839. }
  2840. OMPClause *Parser::ParseOpenMPSizesClause() {
  2841. SourceLocation ClauseNameLoc = ConsumeToken();
  2842. SmallVector<Expr *, 4> ValExprs;
  2843. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  2844. if (T.consumeOpen()) {
  2845. Diag(Tok, diag::err_expected) << tok::l_paren;
  2846. return nullptr;
  2847. }
  2848. while (true) {
  2849. ExprResult Val = ParseConstantExpression();
  2850. if (!Val.isUsable()) {
  2851. T.skipToEnd();
  2852. return nullptr;
  2853. }
  2854. ValExprs.push_back(Val.get());
  2855. if (Tok.is(tok::r_paren) || Tok.is(tok::annot_pragma_openmp_end))
  2856. break;
  2857. ExpectAndConsume(tok::comma);
  2858. }
  2859. T.consumeClose();
  2860. return Actions.ActOnOpenMPSizesClause(
  2861. ValExprs, ClauseNameLoc, T.getOpenLocation(), T.getCloseLocation());
  2862. }
  2863. OMPClause *Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) {
  2864. SourceLocation Loc = Tok.getLocation();
  2865. ConsumeAnyToken();
  2866. // Parse '('.
  2867. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  2868. if (T.expectAndConsume(diag::err_expected_lparen_after, "uses_allocator"))
  2869. return nullptr;
  2870. SmallVector<Sema::UsesAllocatorsData, 4> Data;
  2871. do {
  2872. ExprResult Allocator =
  2873. getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
  2874. if (Allocator.isInvalid()) {
  2875. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  2876. StopBeforeMatch);
  2877. break;
  2878. }
  2879. Sema::UsesAllocatorsData &D = Data.emplace_back();
  2880. D.Allocator = Allocator.get();
  2881. if (Tok.is(tok::l_paren)) {
  2882. BalancedDelimiterTracker T(*this, tok::l_paren,
  2883. tok::annot_pragma_openmp_end);
  2884. T.consumeOpen();
  2885. ExprResult AllocatorTraits =
  2886. getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
  2887. T.consumeClose();
  2888. if (AllocatorTraits.isInvalid()) {
  2889. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  2890. StopBeforeMatch);
  2891. break;
  2892. }
  2893. D.AllocatorTraits = AllocatorTraits.get();
  2894. D.LParenLoc = T.getOpenLocation();
  2895. D.RParenLoc = T.getCloseLocation();
  2896. }
  2897. if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
  2898. Diag(Tok, diag::err_omp_expected_punc) << "uses_allocators" << 0;
  2899. // Parse ','
  2900. if (Tok.is(tok::comma))
  2901. ConsumeAnyToken();
  2902. } while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end));
  2903. T.consumeClose();
  2904. return Actions.ActOnOpenMPUsesAllocatorClause(Loc, T.getOpenLocation(),
  2905. T.getCloseLocation(), Data);
  2906. }
  2907. /// Parsing of OpenMP clauses.
  2908. ///
  2909. /// clause:
  2910. /// if-clause | final-clause | num_threads-clause | safelen-clause |
  2911. /// default-clause | private-clause | firstprivate-clause | shared-clause
  2912. /// | linear-clause | aligned-clause | collapse-clause | bind-clause |
  2913. /// lastprivate-clause | reduction-clause | proc_bind-clause |
  2914. /// schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
  2915. /// mergeable-clause | flush-clause | read-clause | write-clause |
  2916. /// update-clause | capture-clause | seq_cst-clause | device-clause |
  2917. /// simdlen-clause | threads-clause | simd-clause | num_teams-clause |
  2918. /// thread_limit-clause | priority-clause | grainsize-clause |
  2919. /// nogroup-clause | num_tasks-clause | hint-clause | to-clause |
  2920. /// from-clause | is_device_ptr-clause | task_reduction-clause |
  2921. /// in_reduction-clause | allocator-clause | allocate-clause |
  2922. /// acq_rel-clause | acquire-clause | release-clause | relaxed-clause |
  2923. /// depobj-clause | destroy-clause | detach-clause | inclusive-clause |
  2924. /// exclusive-clause | uses_allocators-clause | use_device_addr-clause |
  2925. /// has_device_addr
  2926. ///
  2927. OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
  2928. OpenMPClauseKind CKind, bool FirstClause) {
  2929. OMPClauseKind = CKind;
  2930. OMPClause *Clause = nullptr;
  2931. bool ErrorFound = false;
  2932. bool WrongDirective = false;
  2933. // Check if clause is allowed for the given directive.
  2934. if (CKind != OMPC_unknown &&
  2935. !isAllowedClauseForDirective(DKind, CKind, getLangOpts().OpenMP)) {
  2936. Diag(Tok, diag::err_omp_unexpected_clause)
  2937. << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
  2938. ErrorFound = true;
  2939. WrongDirective = true;
  2940. }
  2941. switch (CKind) {
  2942. case OMPC_final:
  2943. case OMPC_num_threads:
  2944. case OMPC_safelen:
  2945. case OMPC_simdlen:
  2946. case OMPC_collapse:
  2947. case OMPC_ordered:
  2948. case OMPC_num_teams:
  2949. case OMPC_thread_limit:
  2950. case OMPC_priority:
  2951. case OMPC_grainsize:
  2952. case OMPC_num_tasks:
  2953. case OMPC_hint:
  2954. case OMPC_allocator:
  2955. case OMPC_depobj:
  2956. case OMPC_detach:
  2957. case OMPC_novariants:
  2958. case OMPC_nocontext:
  2959. case OMPC_filter:
  2960. case OMPC_partial:
  2961. case OMPC_align:
  2962. case OMPC_message:
  2963. case OMPC_ompx_dyn_cgroup_mem:
  2964. // OpenMP [2.5, Restrictions]
  2965. // At most one num_threads clause can appear on the directive.
  2966. // OpenMP [2.8.1, simd construct, Restrictions]
  2967. // Only one safelen clause can appear on a simd directive.
  2968. // Only one simdlen clause can appear on a simd directive.
  2969. // Only one collapse clause can appear on a simd directive.
  2970. // OpenMP [2.11.1, task Construct, Restrictions]
  2971. // At most one if clause can appear on the directive.
  2972. // At most one final clause can appear on the directive.
  2973. // OpenMP [teams Construct, Restrictions]
  2974. // At most one num_teams clause can appear on the directive.
  2975. // At most one thread_limit clause can appear on the directive.
  2976. // OpenMP [2.9.1, task Construct, Restrictions]
  2977. // At most one priority clause can appear on the directive.
  2978. // OpenMP [2.9.2, taskloop Construct, Restrictions]
  2979. // At most one grainsize clause can appear on the directive.
  2980. // OpenMP [2.9.2, taskloop Construct, Restrictions]
  2981. // At most one num_tasks clause can appear on the directive.
  2982. // OpenMP [2.11.3, allocate Directive, Restrictions]
  2983. // At most one allocator clause can appear on the directive.
  2984. // OpenMP 5.0, 2.10.1 task Construct, Restrictions.
  2985. // At most one detach clause can appear on the directive.
  2986. // OpenMP 5.1, 2.3.6 dispatch Construct, Restrictions.
  2987. // At most one novariants clause can appear on a dispatch directive.
  2988. // At most one nocontext clause can appear on a dispatch directive.
  2989. // OpenMP [5.1, error directive, Restrictions]
  2990. // At most one message clause can appear on the directive
  2991. if (!FirstClause) {
  2992. Diag(Tok, diag::err_omp_more_one_clause)
  2993. << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
  2994. ErrorFound = true;
  2995. }
  2996. if ((CKind == OMPC_ordered || CKind == OMPC_partial) &&
  2997. PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
  2998. Clause = ParseOpenMPClause(CKind, WrongDirective);
  2999. else if (CKind == OMPC_grainsize || CKind == OMPC_num_tasks)
  3000. Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
  3001. else
  3002. Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
  3003. break;
  3004. case OMPC_default:
  3005. case OMPC_proc_bind:
  3006. case OMPC_atomic_default_mem_order:
  3007. case OMPC_at:
  3008. case OMPC_severity:
  3009. case OMPC_bind:
  3010. // OpenMP [2.14.3.1, Restrictions]
  3011. // Only a single default clause may be specified on a parallel, task or
  3012. // teams directive.
  3013. // OpenMP [2.5, parallel Construct, Restrictions]
  3014. // At most one proc_bind clause can appear on the directive.
  3015. // OpenMP [5.0, Requires directive, Restrictions]
  3016. // At most one atomic_default_mem_order clause can appear
  3017. // on the directive
  3018. // OpenMP [5.1, error directive, Restrictions]
  3019. // At most one at clause can appear on the directive
  3020. // At most one severity clause can appear on the directive
  3021. // OpenMP 5.1, 2.11.7 loop Construct, Restrictions.
  3022. // At most one bind clause can appear on a loop directive.
  3023. if (!FirstClause) {
  3024. Diag(Tok, diag::err_omp_more_one_clause)
  3025. << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
  3026. ErrorFound = true;
  3027. }
  3028. Clause = ParseOpenMPSimpleClause(CKind, WrongDirective);
  3029. break;
  3030. case OMPC_device:
  3031. case OMPC_schedule:
  3032. case OMPC_dist_schedule:
  3033. case OMPC_defaultmap:
  3034. case OMPC_order:
  3035. // OpenMP [2.7.1, Restrictions, p. 3]
  3036. // Only one schedule clause can appear on a loop directive.
  3037. // OpenMP 4.5 [2.10.4, Restrictions, p. 106]
  3038. // At most one defaultmap clause can appear on the directive.
  3039. // OpenMP 5.0 [2.12.5, target construct, Restrictions]
  3040. // At most one device clause can appear on the directive.
  3041. // OpenMP 5.1 [2.11.3, order clause, Restrictions]
  3042. // At most one order clause may appear on a construct.
  3043. if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) &&
  3044. (CKind != OMPC_order || getLangOpts().OpenMP >= 51) && !FirstClause) {
  3045. Diag(Tok, diag::err_omp_more_one_clause)
  3046. << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
  3047. ErrorFound = true;
  3048. }
  3049. [[fallthrough]];
  3050. case OMPC_if:
  3051. Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
  3052. break;
  3053. case OMPC_nowait:
  3054. case OMPC_untied:
  3055. case OMPC_mergeable:
  3056. case OMPC_read:
  3057. case OMPC_write:
  3058. case OMPC_capture:
  3059. case OMPC_compare:
  3060. case OMPC_seq_cst:
  3061. case OMPC_acq_rel:
  3062. case OMPC_acquire:
  3063. case OMPC_release:
  3064. case OMPC_relaxed:
  3065. case OMPC_threads:
  3066. case OMPC_simd:
  3067. case OMPC_nogroup:
  3068. case OMPC_unified_address:
  3069. case OMPC_unified_shared_memory:
  3070. case OMPC_reverse_offload:
  3071. case OMPC_dynamic_allocators:
  3072. case OMPC_full:
  3073. // OpenMP [2.7.1, Restrictions, p. 9]
  3074. // Only one ordered clause can appear on a loop directive.
  3075. // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
  3076. // Only one nowait clause can appear on a for directive.
  3077. // OpenMP [5.0, Requires directive, Restrictions]
  3078. // Each of the requires clauses can appear at most once on the directive.
  3079. if (!FirstClause) {
  3080. Diag(Tok, diag::err_omp_more_one_clause)
  3081. << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
  3082. ErrorFound = true;
  3083. }
  3084. Clause = ParseOpenMPClause(CKind, WrongDirective);
  3085. break;
  3086. case OMPC_update:
  3087. if (!FirstClause) {
  3088. Diag(Tok, diag::err_omp_more_one_clause)
  3089. << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
  3090. ErrorFound = true;
  3091. }
  3092. Clause = (DKind == OMPD_depobj)
  3093. ? ParseOpenMPSimpleClause(CKind, WrongDirective)
  3094. : ParseOpenMPClause(CKind, WrongDirective);
  3095. break;
  3096. case OMPC_private:
  3097. case OMPC_firstprivate:
  3098. case OMPC_lastprivate:
  3099. case OMPC_shared:
  3100. case OMPC_reduction:
  3101. case OMPC_task_reduction:
  3102. case OMPC_in_reduction:
  3103. case OMPC_linear:
  3104. case OMPC_aligned:
  3105. case OMPC_copyin:
  3106. case OMPC_copyprivate:
  3107. case OMPC_flush:
  3108. case OMPC_depend:
  3109. case OMPC_map:
  3110. case OMPC_to:
  3111. case OMPC_from:
  3112. case OMPC_use_device_ptr:
  3113. case OMPC_use_device_addr:
  3114. case OMPC_is_device_ptr:
  3115. case OMPC_has_device_addr:
  3116. case OMPC_allocate:
  3117. case OMPC_nontemporal:
  3118. case OMPC_inclusive:
  3119. case OMPC_exclusive:
  3120. case OMPC_affinity:
  3121. Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective);
  3122. break;
  3123. case OMPC_sizes:
  3124. if (!FirstClause) {
  3125. Diag(Tok, diag::err_omp_more_one_clause)
  3126. << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
  3127. ErrorFound = true;
  3128. }
  3129. Clause = ParseOpenMPSizesClause();
  3130. break;
  3131. case OMPC_uses_allocators:
  3132. Clause = ParseOpenMPUsesAllocatorClause(DKind);
  3133. break;
  3134. case OMPC_destroy:
  3135. if (DKind != OMPD_interop) {
  3136. if (!FirstClause) {
  3137. Diag(Tok, diag::err_omp_more_one_clause)
  3138. << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
  3139. ErrorFound = true;
  3140. }
  3141. Clause = ParseOpenMPClause(CKind, WrongDirective);
  3142. break;
  3143. }
  3144. [[fallthrough]];
  3145. case OMPC_init:
  3146. case OMPC_use:
  3147. Clause = ParseOpenMPInteropClause(CKind, WrongDirective);
  3148. break;
  3149. case OMPC_device_type:
  3150. case OMPC_unknown:
  3151. skipUntilPragmaOpenMPEnd(DKind);
  3152. break;
  3153. case OMPC_threadprivate:
  3154. case OMPC_uniform:
  3155. case OMPC_match:
  3156. if (!WrongDirective)
  3157. Diag(Tok, diag::err_omp_unexpected_clause)
  3158. << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
  3159. SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
  3160. break;
  3161. default:
  3162. break;
  3163. }
  3164. return ErrorFound ? nullptr : Clause;
  3165. }
  3166. /// Parses simple expression in parens for single-expression clauses of OpenMP
  3167. /// constructs.
  3168. /// \param RLoc Returned location of right paren.
  3169. ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
  3170. SourceLocation &RLoc,
  3171. bool IsAddressOfOperand) {
  3172. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  3173. if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
  3174. return ExprError();
  3175. SourceLocation ELoc = Tok.getLocation();
  3176. ExprResult LHS(
  3177. ParseCastExpression(AnyCastExpr, IsAddressOfOperand, NotTypeCast));
  3178. ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
  3179. Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
  3180. // Parse ')'.
  3181. RLoc = Tok.getLocation();
  3182. if (!T.consumeClose())
  3183. RLoc = T.getCloseLocation();
  3184. return Val;
  3185. }
  3186. /// Parsing of OpenMP clauses with single expressions like 'final',
  3187. /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
  3188. /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or
  3189. /// 'detach'.
  3190. ///
  3191. /// final-clause:
  3192. /// 'final' '(' expression ')'
  3193. ///
  3194. /// num_threads-clause:
  3195. /// 'num_threads' '(' expression ')'
  3196. ///
  3197. /// safelen-clause:
  3198. /// 'safelen' '(' expression ')'
  3199. ///
  3200. /// simdlen-clause:
  3201. /// 'simdlen' '(' expression ')'
  3202. ///
  3203. /// collapse-clause:
  3204. /// 'collapse' '(' expression ')'
  3205. ///
  3206. /// priority-clause:
  3207. /// 'priority' '(' expression ')'
  3208. ///
  3209. /// grainsize-clause:
  3210. /// 'grainsize' '(' expression ')'
  3211. ///
  3212. /// num_tasks-clause:
  3213. /// 'num_tasks' '(' expression ')'
  3214. ///
  3215. /// hint-clause:
  3216. /// 'hint' '(' expression ')'
  3217. ///
  3218. /// allocator-clause:
  3219. /// 'allocator' '(' expression ')'
  3220. ///
  3221. /// detach-clause:
  3222. /// 'detach' '(' event-handler-expression ')'
  3223. ///
  3224. /// align-clause
  3225. /// 'align' '(' positive-integer-constant ')'
  3226. ///
  3227. OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
  3228. bool ParseOnly) {
  3229. SourceLocation Loc = ConsumeToken();
  3230. SourceLocation LLoc = Tok.getLocation();
  3231. SourceLocation RLoc;
  3232. ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
  3233. if (Val.isInvalid())
  3234. return nullptr;
  3235. if (ParseOnly)
  3236. return nullptr;
  3237. return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
  3238. }
  3239. /// Parse indirect clause for '#pragma omp declare target' directive.
  3240. /// 'indirect' '[' '(' invoked-by-fptr ')' ']'
  3241. /// where invoked-by-fptr is a constant boolean expression that evaluates to
  3242. /// true or false at compile time.
  3243. bool Parser::ParseOpenMPIndirectClause(Sema::DeclareTargetContextInfo &DTCI,
  3244. bool ParseOnly) {
  3245. SourceLocation Loc = ConsumeToken();
  3246. SourceLocation RLoc;
  3247. if (Tok.isNot(tok::l_paren)) {
  3248. if (ParseOnly)
  3249. return false;
  3250. DTCI.Indirect = nullptr;
  3251. return true;
  3252. }
  3253. ExprResult Val =
  3254. ParseOpenMPParensExpr(getOpenMPClauseName(OMPC_indirect), RLoc);
  3255. if (Val.isInvalid())
  3256. return false;
  3257. if (ParseOnly)
  3258. return false;
  3259. if (!Val.get()->isValueDependent() && !Val.get()->isTypeDependent() &&
  3260. !Val.get()->isInstantiationDependent() &&
  3261. !Val.get()->containsUnexpandedParameterPack()) {
  3262. ExprResult Ret = Actions.CheckBooleanCondition(Loc, Val.get());
  3263. if (Ret.isInvalid())
  3264. return false;
  3265. llvm::APSInt Result;
  3266. Ret = Actions.VerifyIntegerConstantExpression(Val.get(), &Result,
  3267. Sema::AllowFold);
  3268. if (Ret.isInvalid())
  3269. return false;
  3270. DTCI.Indirect = Val.get();
  3271. return true;
  3272. }
  3273. return false;
  3274. }
  3275. /// Parses a comma-separated list of interop-types and a prefer_type list.
  3276. ///
  3277. bool Parser::ParseOMPInteropInfo(OMPInteropInfo &InteropInfo,
  3278. OpenMPClauseKind Kind) {
  3279. const Token &Tok = getCurToken();
  3280. bool HasError = false;
  3281. bool IsTarget = false;
  3282. bool IsTargetSync = false;
  3283. while (Tok.is(tok::identifier)) {
  3284. // Currently prefer_type is only allowed with 'init' and it must be first.
  3285. bool PreferTypeAllowed = Kind == OMPC_init &&
  3286. InteropInfo.PreferTypes.empty() && !IsTarget &&
  3287. !IsTargetSync;
  3288. if (Tok.getIdentifierInfo()->isStr("target")) {
  3289. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  3290. // Each interop-type may be specified on an action-clause at most
  3291. // once.
  3292. if (IsTarget)
  3293. Diag(Tok, diag::warn_omp_more_one_interop_type) << "target";
  3294. IsTarget = true;
  3295. ConsumeToken();
  3296. } else if (Tok.getIdentifierInfo()->isStr("targetsync")) {
  3297. if (IsTargetSync)
  3298. Diag(Tok, diag::warn_omp_more_one_interop_type) << "targetsync";
  3299. IsTargetSync = true;
  3300. ConsumeToken();
  3301. } else if (Tok.getIdentifierInfo()->isStr("prefer_type") &&
  3302. PreferTypeAllowed) {
  3303. ConsumeToken();
  3304. BalancedDelimiterTracker PT(*this, tok::l_paren,
  3305. tok::annot_pragma_openmp_end);
  3306. if (PT.expectAndConsume(diag::err_expected_lparen_after, "prefer_type"))
  3307. HasError = true;
  3308. while (Tok.isNot(tok::r_paren)) {
  3309. SourceLocation Loc = Tok.getLocation();
  3310. ExprResult LHS = ParseCastExpression(AnyCastExpr);
  3311. ExprResult PTExpr = Actions.CorrectDelayedTyposInExpr(
  3312. ParseRHSOfBinaryExpression(LHS, prec::Conditional));
  3313. PTExpr = Actions.ActOnFinishFullExpr(PTExpr.get(), Loc,
  3314. /*DiscardedValue=*/false);
  3315. if (PTExpr.isUsable()) {
  3316. InteropInfo.PreferTypes.push_back(PTExpr.get());
  3317. } else {
  3318. HasError = true;
  3319. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  3320. StopBeforeMatch);
  3321. }
  3322. if (Tok.is(tok::comma))
  3323. ConsumeToken();
  3324. }
  3325. PT.consumeClose();
  3326. } else {
  3327. HasError = true;
  3328. Diag(Tok, diag::err_omp_expected_interop_type);
  3329. ConsumeToken();
  3330. }
  3331. if (!Tok.is(tok::comma))
  3332. break;
  3333. ConsumeToken();
  3334. }
  3335. if (!HasError && !IsTarget && !IsTargetSync) {
  3336. Diag(Tok, diag::err_omp_expected_interop_type);
  3337. HasError = true;
  3338. }
  3339. if (Kind == OMPC_init) {
  3340. if (Tok.isNot(tok::colon) && (IsTarget || IsTargetSync))
  3341. Diag(Tok, diag::warn_pragma_expected_colon) << "interop types";
  3342. if (Tok.is(tok::colon))
  3343. ConsumeToken();
  3344. }
  3345. // As of OpenMP 5.1,there are two interop-types, "target" and
  3346. // "targetsync". Either or both are allowed for a single interop.
  3347. InteropInfo.IsTarget = IsTarget;
  3348. InteropInfo.IsTargetSync = IsTargetSync;
  3349. return HasError;
  3350. }
  3351. /// Parsing of OpenMP clauses that use an interop-var.
  3352. ///
  3353. /// init-clause:
  3354. /// init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var)
  3355. ///
  3356. /// destroy-clause:
  3357. /// destroy(interop-var)
  3358. ///
  3359. /// use-clause:
  3360. /// use(interop-var)
  3361. ///
  3362. /// interop-modifier:
  3363. /// prefer_type(preference-list)
  3364. ///
  3365. /// preference-list:
  3366. /// foreign-runtime-id [, foreign-runtime-id]...
  3367. ///
  3368. /// foreign-runtime-id:
  3369. /// <string-literal> | <constant-integral-expression>
  3370. ///
  3371. /// interop-type:
  3372. /// target | targetsync
  3373. ///
  3374. OMPClause *Parser::ParseOpenMPInteropClause(OpenMPClauseKind Kind,
  3375. bool ParseOnly) {
  3376. SourceLocation Loc = ConsumeToken();
  3377. // Parse '('.
  3378. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  3379. if (T.expectAndConsume(diag::err_expected_lparen_after,
  3380. getOpenMPClauseName(Kind).data()))
  3381. return nullptr;
  3382. bool InteropError = false;
  3383. OMPInteropInfo InteropInfo;
  3384. if (Kind == OMPC_init)
  3385. InteropError = ParseOMPInteropInfo(InteropInfo, OMPC_init);
  3386. // Parse the variable.
  3387. SourceLocation VarLoc = Tok.getLocation();
  3388. ExprResult InteropVarExpr =
  3389. Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
  3390. if (!InteropVarExpr.isUsable()) {
  3391. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  3392. StopBeforeMatch);
  3393. }
  3394. // Parse ')'.
  3395. SourceLocation RLoc = Tok.getLocation();
  3396. if (!T.consumeClose())
  3397. RLoc = T.getCloseLocation();
  3398. if (ParseOnly || !InteropVarExpr.isUsable() || InteropError)
  3399. return nullptr;
  3400. if (Kind == OMPC_init)
  3401. return Actions.ActOnOpenMPInitClause(InteropVarExpr.get(), InteropInfo, Loc,
  3402. T.getOpenLocation(), VarLoc, RLoc);
  3403. if (Kind == OMPC_use)
  3404. return Actions.ActOnOpenMPUseClause(InteropVarExpr.get(), Loc,
  3405. T.getOpenLocation(), VarLoc, RLoc);
  3406. if (Kind == OMPC_destroy)
  3407. return Actions.ActOnOpenMPDestroyClause(InteropVarExpr.get(), Loc,
  3408. T.getOpenLocation(), VarLoc, RLoc);
  3409. llvm_unreachable("Unexpected interop variable clause.");
  3410. }
  3411. /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
  3412. ///
  3413. /// default-clause:
  3414. /// 'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')'
  3415. ///
  3416. /// proc_bind-clause:
  3417. /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')'
  3418. ///
  3419. /// bind-clause:
  3420. /// 'bind' '(' 'teams' | 'parallel' | 'thread' ')'
  3421. ///
  3422. /// update-clause:
  3423. /// 'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' |
  3424. /// 'inoutset' ')'
  3425. ///
  3426. OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind,
  3427. bool ParseOnly) {
  3428. std::optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind);
  3429. if (!Val || ParseOnly)
  3430. return nullptr;
  3431. if (getLangOpts().OpenMP < 51 && Kind == OMPC_default &&
  3432. (static_cast<DefaultKind>(Val->Type) == OMP_DEFAULT_private ||
  3433. static_cast<DefaultKind>(Val->Type) ==
  3434. OMP_DEFAULT_firstprivate)) {
  3435. Diag(Val->LOpen, diag::err_omp_invalid_dsa)
  3436. << getOpenMPClauseName(static_cast<DefaultKind>(Val->Type) ==
  3437. OMP_DEFAULT_private
  3438. ? OMPC_private
  3439. : OMPC_firstprivate)
  3440. << getOpenMPClauseName(OMPC_default) << "5.1";
  3441. return nullptr;
  3442. }
  3443. return Actions.ActOnOpenMPSimpleClause(Kind, Val->Type,
  3444. Val->TypeLoc, Val->LOpen,
  3445. Val->Loc, Val->RLoc);
  3446. }
  3447. /// Parsing of OpenMP clauses like 'ordered'.
  3448. ///
  3449. /// ordered-clause:
  3450. /// 'ordered'
  3451. ///
  3452. /// nowait-clause:
  3453. /// 'nowait'
  3454. ///
  3455. /// untied-clause:
  3456. /// 'untied'
  3457. ///
  3458. /// mergeable-clause:
  3459. /// 'mergeable'
  3460. ///
  3461. /// read-clause:
  3462. /// 'read'
  3463. ///
  3464. /// threads-clause:
  3465. /// 'threads'
  3466. ///
  3467. /// simd-clause:
  3468. /// 'simd'
  3469. ///
  3470. /// nogroup-clause:
  3471. /// 'nogroup'
  3472. ///
  3473. OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) {
  3474. SourceLocation Loc = Tok.getLocation();
  3475. ConsumeAnyToken();
  3476. if (ParseOnly)
  3477. return nullptr;
  3478. return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
  3479. }
  3480. /// Parsing of OpenMP clauses with single expressions and some additional
  3481. /// argument like 'schedule' or 'dist_schedule'.
  3482. ///
  3483. /// schedule-clause:
  3484. /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
  3485. /// ')'
  3486. ///
  3487. /// if-clause:
  3488. /// 'if' '(' [ directive-name-modifier ':' ] expression ')'
  3489. ///
  3490. /// defaultmap:
  3491. /// 'defaultmap' '(' modifier [ ':' kind ] ')'
  3492. ///
  3493. /// device-clause:
  3494. /// 'device' '(' [ device-modifier ':' ] expression ')'
  3495. ///
  3496. OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
  3497. OpenMPClauseKind Kind,
  3498. bool ParseOnly) {
  3499. SourceLocation Loc = ConsumeToken();
  3500. SourceLocation DelimLoc;
  3501. // Parse '('.
  3502. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  3503. if (T.expectAndConsume(diag::err_expected_lparen_after,
  3504. getOpenMPClauseName(Kind).data()))
  3505. return nullptr;
  3506. ExprResult Val;
  3507. SmallVector<unsigned, 4> Arg;
  3508. SmallVector<SourceLocation, 4> KLoc;
  3509. if (Kind == OMPC_schedule) {
  3510. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  3511. Arg.resize(NumberOfElements);
  3512. KLoc.resize(NumberOfElements);
  3513. Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
  3514. Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
  3515. Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
  3516. unsigned KindModifier = getOpenMPSimpleClauseType(
  3517. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
  3518. if (KindModifier > OMPC_SCHEDULE_unknown) {
  3519. // Parse 'modifier'
  3520. Arg[Modifier1] = KindModifier;
  3521. KLoc[Modifier1] = Tok.getLocation();
  3522. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  3523. Tok.isNot(tok::annot_pragma_openmp_end))
  3524. ConsumeAnyToken();
  3525. if (Tok.is(tok::comma)) {
  3526. // Parse ',' 'modifier'
  3527. ConsumeAnyToken();
  3528. KindModifier = getOpenMPSimpleClauseType(
  3529. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
  3530. Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
  3531. ? KindModifier
  3532. : (unsigned)OMPC_SCHEDULE_unknown;
  3533. KLoc[Modifier2] = Tok.getLocation();
  3534. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  3535. Tok.isNot(tok::annot_pragma_openmp_end))
  3536. ConsumeAnyToken();
  3537. }
  3538. // Parse ':'
  3539. if (Tok.is(tok::colon))
  3540. ConsumeAnyToken();
  3541. else
  3542. Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
  3543. KindModifier = getOpenMPSimpleClauseType(
  3544. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
  3545. }
  3546. Arg[ScheduleKind] = KindModifier;
  3547. KLoc[ScheduleKind] = Tok.getLocation();
  3548. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  3549. Tok.isNot(tok::annot_pragma_openmp_end))
  3550. ConsumeAnyToken();
  3551. if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
  3552. Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
  3553. Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
  3554. Tok.is(tok::comma))
  3555. DelimLoc = ConsumeAnyToken();
  3556. } else if (Kind == OMPC_dist_schedule) {
  3557. Arg.push_back(getOpenMPSimpleClauseType(
  3558. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
  3559. KLoc.push_back(Tok.getLocation());
  3560. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  3561. Tok.isNot(tok::annot_pragma_openmp_end))
  3562. ConsumeAnyToken();
  3563. if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
  3564. DelimLoc = ConsumeAnyToken();
  3565. } else if (Kind == OMPC_defaultmap) {
  3566. // Get a defaultmap modifier
  3567. unsigned Modifier = getOpenMPSimpleClauseType(
  3568. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
  3569. // Set defaultmap modifier to unknown if it is either scalar, aggregate, or
  3570. // pointer
  3571. if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown)
  3572. Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown;
  3573. Arg.push_back(Modifier);
  3574. KLoc.push_back(Tok.getLocation());
  3575. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  3576. Tok.isNot(tok::annot_pragma_openmp_end))
  3577. ConsumeAnyToken();
  3578. // Parse ':'
  3579. if (Tok.is(tok::colon) || getLangOpts().OpenMP < 50) {
  3580. if (Tok.is(tok::colon))
  3581. ConsumeAnyToken();
  3582. else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
  3583. Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
  3584. // Get a defaultmap kind
  3585. Arg.push_back(getOpenMPSimpleClauseType(
  3586. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
  3587. KLoc.push_back(Tok.getLocation());
  3588. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  3589. Tok.isNot(tok::annot_pragma_openmp_end))
  3590. ConsumeAnyToken();
  3591. } else {
  3592. Arg.push_back(OMPC_DEFAULTMAP_unknown);
  3593. KLoc.push_back(SourceLocation());
  3594. }
  3595. } else if (Kind == OMPC_order) {
  3596. enum { Modifier, OrderKind, NumberOfElements };
  3597. Arg.resize(NumberOfElements);
  3598. KLoc.resize(NumberOfElements);
  3599. Arg[Modifier] = OMPC_ORDER_MODIFIER_unknown;
  3600. Arg[OrderKind] = OMPC_ORDER_unknown;
  3601. unsigned KindModifier = getOpenMPSimpleClauseType(
  3602. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
  3603. if (KindModifier > OMPC_ORDER_unknown) {
  3604. // Parse 'modifier'
  3605. Arg[Modifier] = KindModifier;
  3606. KLoc[Modifier] = Tok.getLocation();
  3607. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  3608. Tok.isNot(tok::annot_pragma_openmp_end))
  3609. ConsumeAnyToken();
  3610. // Parse ':'
  3611. if (Tok.is(tok::colon))
  3612. ConsumeAnyToken();
  3613. else
  3614. Diag(Tok, diag::warn_pragma_expected_colon) << "order modifier";
  3615. KindModifier = getOpenMPSimpleClauseType(
  3616. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
  3617. }
  3618. Arg[OrderKind] = KindModifier;
  3619. KLoc[OrderKind] = Tok.getLocation();
  3620. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
  3621. Tok.isNot(tok::annot_pragma_openmp_end))
  3622. ConsumeAnyToken();
  3623. } else if (Kind == OMPC_device) {
  3624. // Only target executable directives support extended device construct.
  3625. if (isOpenMPTargetExecutionDirective(DKind) && getLangOpts().OpenMP >= 50 &&
  3626. NextToken().is(tok::colon)) {
  3627. // Parse optional <device modifier> ':'
  3628. Arg.push_back(getOpenMPSimpleClauseType(
  3629. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
  3630. KLoc.push_back(Tok.getLocation());
  3631. ConsumeAnyToken();
  3632. // Parse ':'
  3633. ConsumeAnyToken();
  3634. } else {
  3635. Arg.push_back(OMPC_DEVICE_unknown);
  3636. KLoc.emplace_back();
  3637. }
  3638. } else if (Kind == OMPC_grainsize) {
  3639. // Parse optional <grainsize modifier> ':'
  3640. OpenMPGrainsizeClauseModifier Modifier =
  3641. static_cast<OpenMPGrainsizeClauseModifier>(getOpenMPSimpleClauseType(
  3642. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok),
  3643. getLangOpts()));
  3644. if (getLangOpts().OpenMP >= 51) {
  3645. if (NextToken().is(tok::colon)) {
  3646. Arg.push_back(Modifier);
  3647. KLoc.push_back(Tok.getLocation());
  3648. // Parse modifier
  3649. ConsumeAnyToken();
  3650. // Parse ':'
  3651. ConsumeAnyToken();
  3652. } else {
  3653. if (Modifier == OMPC_GRAINSIZE_strict) {
  3654. Diag(Tok, diag::err_modifier_expected_colon) << "strict";
  3655. // Parse modifier
  3656. ConsumeAnyToken();
  3657. }
  3658. Arg.push_back(OMPC_GRAINSIZE_unknown);
  3659. KLoc.emplace_back();
  3660. }
  3661. } else {
  3662. Arg.push_back(OMPC_GRAINSIZE_unknown);
  3663. KLoc.emplace_back();
  3664. }
  3665. } else if (Kind == OMPC_num_tasks) {
  3666. // Parse optional <num_tasks modifier> ':'
  3667. OpenMPNumTasksClauseModifier Modifier =
  3668. static_cast<OpenMPNumTasksClauseModifier>(getOpenMPSimpleClauseType(
  3669. Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok),
  3670. getLangOpts()));
  3671. if (getLangOpts().OpenMP >= 51) {
  3672. if (NextToken().is(tok::colon)) {
  3673. Arg.push_back(Modifier);
  3674. KLoc.push_back(Tok.getLocation());
  3675. // Parse modifier
  3676. ConsumeAnyToken();
  3677. // Parse ':'
  3678. ConsumeAnyToken();
  3679. } else {
  3680. if (Modifier == OMPC_NUMTASKS_strict) {
  3681. Diag(Tok, diag::err_modifier_expected_colon) << "strict";
  3682. // Parse modifier
  3683. ConsumeAnyToken();
  3684. }
  3685. Arg.push_back(OMPC_NUMTASKS_unknown);
  3686. KLoc.emplace_back();
  3687. }
  3688. } else {
  3689. Arg.push_back(OMPC_NUMTASKS_unknown);
  3690. KLoc.emplace_back();
  3691. }
  3692. } else {
  3693. assert(Kind == OMPC_if);
  3694. KLoc.push_back(Tok.getLocation());
  3695. TentativeParsingAction TPA(*this);
  3696. auto DK = parseOpenMPDirectiveKind(*this);
  3697. Arg.push_back(DK);
  3698. if (DK != OMPD_unknown) {
  3699. ConsumeToken();
  3700. if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
  3701. TPA.Commit();
  3702. DelimLoc = ConsumeToken();
  3703. } else {
  3704. TPA.Revert();
  3705. Arg.back() = unsigned(OMPD_unknown);
  3706. }
  3707. } else {
  3708. TPA.Revert();
  3709. }
  3710. }
  3711. bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
  3712. (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
  3713. Kind == OMPC_if || Kind == OMPC_device ||
  3714. Kind == OMPC_grainsize || Kind == OMPC_num_tasks;
  3715. if (NeedAnExpression) {
  3716. SourceLocation ELoc = Tok.getLocation();
  3717. ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
  3718. Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
  3719. Val =
  3720. Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
  3721. }
  3722. // Parse ')'.
  3723. SourceLocation RLoc = Tok.getLocation();
  3724. if (!T.consumeClose())
  3725. RLoc = T.getCloseLocation();
  3726. if (NeedAnExpression && Val.isInvalid())
  3727. return nullptr;
  3728. if (ParseOnly)
  3729. return nullptr;
  3730. return Actions.ActOnOpenMPSingleExprWithArgClause(
  3731. Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc);
  3732. }
  3733. static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
  3734. UnqualifiedId &ReductionId) {
  3735. if (ReductionIdScopeSpec.isEmpty()) {
  3736. auto OOK = OO_None;
  3737. switch (P.getCurToken().getKind()) {
  3738. case tok::plus:
  3739. OOK = OO_Plus;
  3740. break;
  3741. case tok::minus:
  3742. OOK = OO_Minus;
  3743. break;
  3744. case tok::star:
  3745. OOK = OO_Star;
  3746. break;
  3747. case tok::amp:
  3748. OOK = OO_Amp;
  3749. break;
  3750. case tok::pipe:
  3751. OOK = OO_Pipe;
  3752. break;
  3753. case tok::caret:
  3754. OOK = OO_Caret;
  3755. break;
  3756. case tok::ampamp:
  3757. OOK = OO_AmpAmp;
  3758. break;
  3759. case tok::pipepipe:
  3760. OOK = OO_PipePipe;
  3761. break;
  3762. default:
  3763. break;
  3764. }
  3765. if (OOK != OO_None) {
  3766. SourceLocation OpLoc = P.ConsumeToken();
  3767. SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
  3768. ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
  3769. return false;
  3770. }
  3771. }
  3772. return P.ParseUnqualifiedId(
  3773. ReductionIdScopeSpec, /*ObjectType=*/nullptr,
  3774. /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
  3775. /*AllowDestructorName*/ false,
  3776. /*AllowConstructorName*/ false,
  3777. /*AllowDeductionGuide*/ false, nullptr, ReductionId);
  3778. }
  3779. /// Checks if the token is a valid map-type-modifier.
  3780. /// FIXME: It will return an OpenMPMapClauseKind if that's what it parses.
  3781. static OpenMPMapModifierKind isMapModifier(Parser &P) {
  3782. Token Tok = P.getCurToken();
  3783. if (!Tok.is(tok::identifier))
  3784. return OMPC_MAP_MODIFIER_unknown;
  3785. Preprocessor &PP = P.getPreprocessor();
  3786. OpenMPMapModifierKind TypeModifier =
  3787. static_cast<OpenMPMapModifierKind>(getOpenMPSimpleClauseType(
  3788. OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
  3789. return TypeModifier;
  3790. }
  3791. /// Parse the mapper modifier in map, to, and from clauses.
  3792. bool Parser::parseMapperModifier(Sema::OpenMPVarListDataTy &Data) {
  3793. // Parse '('.
  3794. BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon);
  3795. if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) {
  3796. SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
  3797. StopBeforeMatch);
  3798. return true;
  3799. }
  3800. // Parse mapper-identifier
  3801. if (getLangOpts().CPlusPlus)
  3802. ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
  3803. /*ObjectType=*/nullptr,
  3804. /*ObjectHasErrors=*/false,
  3805. /*EnteringContext=*/false);
  3806. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
  3807. Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
  3808. SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
  3809. StopBeforeMatch);
  3810. return true;
  3811. }
  3812. auto &DeclNames = Actions.getASTContext().DeclarationNames;
  3813. Data.ReductionOrMapperId = DeclarationNameInfo(
  3814. DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation());
  3815. ConsumeToken();
  3816. // Parse ')'.
  3817. return T.consumeClose();
  3818. }
  3819. /// Parse map-type-modifiers in map clause.
  3820. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
  3821. /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
  3822. /// present
  3823. bool Parser::parseMapTypeModifiers(Sema::OpenMPVarListDataTy &Data) {
  3824. while (getCurToken().isNot(tok::colon)) {
  3825. OpenMPMapModifierKind TypeModifier = isMapModifier(*this);
  3826. if (TypeModifier == OMPC_MAP_MODIFIER_always ||
  3827. TypeModifier == OMPC_MAP_MODIFIER_close ||
  3828. TypeModifier == OMPC_MAP_MODIFIER_present ||
  3829. TypeModifier == OMPC_MAP_MODIFIER_ompx_hold) {
  3830. Data.MapTypeModifiers.push_back(TypeModifier);
  3831. Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
  3832. ConsumeToken();
  3833. } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) {
  3834. Data.MapTypeModifiers.push_back(TypeModifier);
  3835. Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
  3836. ConsumeToken();
  3837. if (parseMapperModifier(Data))
  3838. return true;
  3839. } else {
  3840. // For the case of unknown map-type-modifier or a map-type.
  3841. // Map-type is followed by a colon; the function returns when it
  3842. // encounters a token followed by a colon.
  3843. if (Tok.is(tok::comma)) {
  3844. Diag(Tok, diag::err_omp_map_type_modifier_missing);
  3845. ConsumeToken();
  3846. continue;
  3847. }
  3848. // Potential map-type token as it is followed by a colon.
  3849. if (PP.LookAhead(0).is(tok::colon))
  3850. return false;
  3851. Diag(Tok, diag::err_omp_unknown_map_type_modifier)
  3852. << (getLangOpts().OpenMP >= 51 ? (getLangOpts().OpenMP >= 52 ? 2 : 1)
  3853. : 0)
  3854. << getLangOpts().OpenMPExtensions;
  3855. ConsumeToken();
  3856. }
  3857. if (getCurToken().is(tok::comma))
  3858. ConsumeToken();
  3859. }
  3860. return false;
  3861. }
  3862. /// Checks if the token is a valid map-type.
  3863. /// FIXME: It will return an OpenMPMapModifierKind if that's what it parses.
  3864. static OpenMPMapClauseKind isMapType(Parser &P) {
  3865. Token Tok = P.getCurToken();
  3866. // The map-type token can be either an identifier or the C++ delete keyword.
  3867. if (!Tok.isOneOf(tok::identifier, tok::kw_delete))
  3868. return OMPC_MAP_unknown;
  3869. Preprocessor &PP = P.getPreprocessor();
  3870. OpenMPMapClauseKind MapType =
  3871. static_cast<OpenMPMapClauseKind>(getOpenMPSimpleClauseType(
  3872. OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
  3873. return MapType;
  3874. }
  3875. /// Parse map-type in map clause.
  3876. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
  3877. /// where, map-type ::= to | from | tofrom | alloc | release | delete
  3878. static void parseMapType(Parser &P, Sema::OpenMPVarListDataTy &Data) {
  3879. Token Tok = P.getCurToken();
  3880. if (Tok.is(tok::colon)) {
  3881. P.Diag(Tok, diag::err_omp_map_type_missing);
  3882. return;
  3883. }
  3884. Data.ExtraModifier = isMapType(P);
  3885. if (Data.ExtraModifier == OMPC_MAP_unknown)
  3886. P.Diag(Tok, diag::err_omp_unknown_map_type);
  3887. P.ConsumeToken();
  3888. }
  3889. /// Parses simple expression in parens for single-expression clauses of OpenMP
  3890. /// constructs.
  3891. ExprResult Parser::ParseOpenMPIteratorsExpr() {
  3892. assert(Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator" &&
  3893. "Expected 'iterator' token.");
  3894. SourceLocation IteratorKwLoc = ConsumeToken();
  3895. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  3896. if (T.expectAndConsume(diag::err_expected_lparen_after, "iterator"))
  3897. return ExprError();
  3898. SourceLocation LLoc = T.getOpenLocation();
  3899. SmallVector<Sema::OMPIteratorData, 4> Data;
  3900. while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
  3901. // Check if the type parsing is required.
  3902. ParsedType IteratorType;
  3903. if (Tok.isNot(tok::identifier) || NextToken().isNot(tok::equal)) {
  3904. // identifier '=' is not found - parse type.
  3905. TypeResult TR = ParseTypeName();
  3906. if (TR.isInvalid()) {
  3907. T.skipToEnd();
  3908. return ExprError();
  3909. }
  3910. IteratorType = TR.get();
  3911. }
  3912. // Parse identifier.
  3913. IdentifierInfo *II = nullptr;
  3914. SourceLocation IdLoc;
  3915. if (Tok.is(tok::identifier)) {
  3916. II = Tok.getIdentifierInfo();
  3917. IdLoc = ConsumeToken();
  3918. } else {
  3919. Diag(Tok, diag::err_expected_unqualified_id) << 0;
  3920. }
  3921. // Parse '='.
  3922. SourceLocation AssignLoc;
  3923. if (Tok.is(tok::equal))
  3924. AssignLoc = ConsumeToken();
  3925. else
  3926. Diag(Tok, diag::err_omp_expected_equal_in_iterator);
  3927. // Parse range-specification - <begin> ':' <end> [ ':' <step> ]
  3928. ColonProtectionRAIIObject ColonRAII(*this);
  3929. // Parse <begin>
  3930. SourceLocation Loc = Tok.getLocation();
  3931. ExprResult LHS = ParseCastExpression(AnyCastExpr);
  3932. ExprResult Begin = Actions.CorrectDelayedTyposInExpr(
  3933. ParseRHSOfBinaryExpression(LHS, prec::Conditional));
  3934. Begin = Actions.ActOnFinishFullExpr(Begin.get(), Loc,
  3935. /*DiscardedValue=*/false);
  3936. // Parse ':'.
  3937. SourceLocation ColonLoc;
  3938. if (Tok.is(tok::colon))
  3939. ColonLoc = ConsumeToken();
  3940. // Parse <end>
  3941. Loc = Tok.getLocation();
  3942. LHS = ParseCastExpression(AnyCastExpr);
  3943. ExprResult End = Actions.CorrectDelayedTyposInExpr(
  3944. ParseRHSOfBinaryExpression(LHS, prec::Conditional));
  3945. End = Actions.ActOnFinishFullExpr(End.get(), Loc,
  3946. /*DiscardedValue=*/false);
  3947. SourceLocation SecColonLoc;
  3948. ExprResult Step;
  3949. // Parse optional step.
  3950. if (Tok.is(tok::colon)) {
  3951. // Parse ':'
  3952. SecColonLoc = ConsumeToken();
  3953. // Parse <step>
  3954. Loc = Tok.getLocation();
  3955. LHS = ParseCastExpression(AnyCastExpr);
  3956. Step = Actions.CorrectDelayedTyposInExpr(
  3957. ParseRHSOfBinaryExpression(LHS, prec::Conditional));
  3958. Step = Actions.ActOnFinishFullExpr(Step.get(), Loc,
  3959. /*DiscardedValue=*/false);
  3960. }
  3961. // Parse ',' or ')'
  3962. if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
  3963. Diag(Tok, diag::err_omp_expected_punc_after_iterator);
  3964. if (Tok.is(tok::comma))
  3965. ConsumeToken();
  3966. Sema::OMPIteratorData &D = Data.emplace_back();
  3967. D.DeclIdent = II;
  3968. D.DeclIdentLoc = IdLoc;
  3969. D.Type = IteratorType;
  3970. D.AssignLoc = AssignLoc;
  3971. D.ColonLoc = ColonLoc;
  3972. D.SecColonLoc = SecColonLoc;
  3973. D.Range.Begin = Begin.get();
  3974. D.Range.End = End.get();
  3975. D.Range.Step = Step.get();
  3976. }
  3977. // Parse ')'.
  3978. SourceLocation RLoc = Tok.getLocation();
  3979. if (!T.consumeClose())
  3980. RLoc = T.getCloseLocation();
  3981. return Actions.ActOnOMPIteratorExpr(getCurScope(), IteratorKwLoc, LLoc, RLoc,
  3982. Data);
  3983. }
  3984. bool Parser::ParseOpenMPReservedLocator(OpenMPClauseKind Kind,
  3985. Sema::OpenMPVarListDataTy &Data,
  3986. const LangOptions &LangOpts) {
  3987. // Currently the only reserved locator is 'omp_all_memory' which is only
  3988. // allowed on a depend clause.
  3989. if (Kind != OMPC_depend || LangOpts.OpenMP < 51)
  3990. return false;
  3991. if (Tok.is(tok::identifier) &&
  3992. Tok.getIdentifierInfo()->isStr("omp_all_memory")) {
  3993. if (Data.ExtraModifier == OMPC_DEPEND_outallmemory ||
  3994. Data.ExtraModifier == OMPC_DEPEND_inoutallmemory)
  3995. Diag(Tok, diag::warn_omp_more_one_omp_all_memory);
  3996. else if (Data.ExtraModifier != OMPC_DEPEND_out &&
  3997. Data.ExtraModifier != OMPC_DEPEND_inout)
  3998. Diag(Tok, diag::err_omp_requires_out_inout_depend_type);
  3999. else
  4000. Data.ExtraModifier = Data.ExtraModifier == OMPC_DEPEND_out
  4001. ? OMPC_DEPEND_outallmemory
  4002. : OMPC_DEPEND_inoutallmemory;
  4003. ConsumeToken();
  4004. return true;
  4005. }
  4006. return false;
  4007. }
  4008. /// Parses clauses with list.
  4009. bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
  4010. OpenMPClauseKind Kind,
  4011. SmallVectorImpl<Expr *> &Vars,
  4012. Sema::OpenMPVarListDataTy &Data) {
  4013. UnqualifiedId UnqualifiedReductionId;
  4014. bool InvalidReductionId = false;
  4015. bool IsInvalidMapperModifier = false;
  4016. // Parse '('.
  4017. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
  4018. if (T.expectAndConsume(diag::err_expected_lparen_after,
  4019. getOpenMPClauseName(Kind).data()))
  4020. return true;
  4021. bool HasIterator = false;
  4022. bool InvalidIterator = false;
  4023. bool NeedRParenForLinear = false;
  4024. BalancedDelimiterTracker LinearT(*this, tok::l_paren,
  4025. tok::annot_pragma_openmp_end);
  4026. // Handle reduction-identifier for reduction clause.
  4027. if (Kind == OMPC_reduction || Kind == OMPC_task_reduction ||
  4028. Kind == OMPC_in_reduction) {
  4029. Data.ExtraModifier = OMPC_REDUCTION_unknown;
  4030. if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 50 &&
  4031. (Tok.is(tok::identifier) || Tok.is(tok::kw_default)) &&
  4032. NextToken().is(tok::comma)) {
  4033. // Parse optional reduction modifier.
  4034. Data.ExtraModifier =
  4035. getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
  4036. Data.ExtraModifierLoc = Tok.getLocation();
  4037. ConsumeToken();
  4038. assert(Tok.is(tok::comma) && "Expected comma.");
  4039. (void)ConsumeToken();
  4040. }
  4041. ColonProtectionRAIIObject ColonRAII(*this);
  4042. if (getLangOpts().CPlusPlus)
  4043. ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
  4044. /*ObjectType=*/nullptr,
  4045. /*ObjectHasErrors=*/false,
  4046. /*EnteringContext=*/false);
  4047. InvalidReductionId = ParseReductionId(
  4048. *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId);
  4049. if (InvalidReductionId) {
  4050. SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
  4051. StopBeforeMatch);
  4052. }
  4053. if (Tok.is(tok::colon))
  4054. Data.ColonLoc = ConsumeToken();
  4055. else
  4056. Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
  4057. if (!InvalidReductionId)
  4058. Data.ReductionOrMapperId =
  4059. Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
  4060. } else if (Kind == OMPC_depend) {
  4061. if (getLangOpts().OpenMP >= 50) {
  4062. if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
  4063. // Handle optional dependence modifier.
  4064. // iterator(iterators-definition)
  4065. // where iterators-definition is iterator-specifier [,
  4066. // iterators-definition ]
  4067. // where iterator-specifier is [ iterator-type ] identifier =
  4068. // range-specification
  4069. HasIterator = true;
  4070. EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
  4071. ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
  4072. Data.DepModOrTailExpr = IteratorRes.get();
  4073. // Parse ','
  4074. ExpectAndConsume(tok::comma);
  4075. }
  4076. }
  4077. // Handle dependency type for depend clause.
  4078. ColonProtectionRAIIObject ColonRAII(*this);
  4079. Data.ExtraModifier = getOpenMPSimpleClauseType(
  4080. Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
  4081. getLangOpts());
  4082. Data.ExtraModifierLoc = Tok.getLocation();
  4083. if (Data.ExtraModifier == OMPC_DEPEND_unknown) {
  4084. SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
  4085. StopBeforeMatch);
  4086. } else {
  4087. ConsumeToken();
  4088. // Special processing for depend(source) clause.
  4089. if (DKind == OMPD_ordered && Data.ExtraModifier == OMPC_DEPEND_source) {
  4090. // Parse ')'.
  4091. T.consumeClose();
  4092. return false;
  4093. }
  4094. }
  4095. if (Tok.is(tok::colon)) {
  4096. Data.ColonLoc = ConsumeToken();
  4097. } else {
  4098. Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
  4099. : diag::warn_pragma_expected_colon)
  4100. << "dependency type";
  4101. }
  4102. } else if (Kind == OMPC_linear) {
  4103. // Try to parse modifier if any.
  4104. Data.ExtraModifier = OMPC_LINEAR_val;
  4105. if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
  4106. Data.ExtraModifier =
  4107. getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
  4108. Data.ExtraModifierLoc = ConsumeToken();
  4109. LinearT.consumeOpen();
  4110. NeedRParenForLinear = true;
  4111. }
  4112. } else if (Kind == OMPC_lastprivate) {
  4113. // Try to parse modifier if any.
  4114. Data.ExtraModifier = OMPC_LASTPRIVATE_unknown;
  4115. // Conditional modifier allowed only in OpenMP 5.0 and not supported in
  4116. // distribute and taskloop based directives.
  4117. if ((getLangOpts().OpenMP >= 50 && !isOpenMPDistributeDirective(DKind) &&
  4118. !isOpenMPTaskLoopDirective(DKind)) &&
  4119. Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::colon)) {
  4120. Data.ExtraModifier =
  4121. getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
  4122. Data.ExtraModifierLoc = Tok.getLocation();
  4123. ConsumeToken();
  4124. assert(Tok.is(tok::colon) && "Expected colon.");
  4125. Data.ColonLoc = ConsumeToken();
  4126. }
  4127. } else if (Kind == OMPC_map) {
  4128. // Handle optional iterator map modifier.
  4129. if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
  4130. HasIterator = true;
  4131. EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
  4132. Data.MapTypeModifiers.push_back(OMPC_MAP_MODIFIER_iterator);
  4133. Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
  4134. ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
  4135. Data.IteratorExpr = IteratorRes.get();
  4136. // Parse ','
  4137. ExpectAndConsume(tok::comma);
  4138. if (getLangOpts().OpenMP < 52) {
  4139. Diag(Tok, diag::err_omp_unknown_map_type_modifier)
  4140. << (getLangOpts().OpenMP >= 51 ? 1 : 0)
  4141. << getLangOpts().OpenMPExtensions;
  4142. InvalidIterator = true;
  4143. }
  4144. }
  4145. // Handle map type for map clause.
  4146. ColonProtectionRAIIObject ColonRAII(*this);
  4147. // The first identifier may be a list item, a map-type or a
  4148. // map-type-modifier. The map-type can also be delete which has the same
  4149. // spelling of the C++ delete keyword.
  4150. Data.ExtraModifier = OMPC_MAP_unknown;
  4151. Data.ExtraModifierLoc = Tok.getLocation();
  4152. // Check for presence of a colon in the map clause.
  4153. TentativeParsingAction TPA(*this);
  4154. bool ColonPresent = false;
  4155. if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
  4156. StopBeforeMatch)) {
  4157. if (Tok.is(tok::colon))
  4158. ColonPresent = true;
  4159. }
  4160. TPA.Revert();
  4161. // Only parse map-type-modifier[s] and map-type if a colon is present in
  4162. // the map clause.
  4163. if (ColonPresent) {
  4164. IsInvalidMapperModifier = parseMapTypeModifiers(Data);
  4165. if (!IsInvalidMapperModifier)
  4166. parseMapType(*this, Data);
  4167. else
  4168. SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch);
  4169. }
  4170. if (Data.ExtraModifier == OMPC_MAP_unknown) {
  4171. Data.ExtraModifier = OMPC_MAP_tofrom;
  4172. if (getLangOpts().OpenMP >= 52) {
  4173. if (DKind == OMPD_target_enter_data)
  4174. Data.ExtraModifier = OMPC_MAP_to;
  4175. else if (DKind == OMPD_target_exit_data)
  4176. Data.ExtraModifier = OMPC_MAP_from;
  4177. }
  4178. Data.IsMapTypeImplicit = true;
  4179. }
  4180. if (Tok.is(tok::colon))
  4181. Data.ColonLoc = ConsumeToken();
  4182. } else if (Kind == OMPC_to || Kind == OMPC_from) {
  4183. while (Tok.is(tok::identifier)) {
  4184. auto Modifier = static_cast<OpenMPMotionModifierKind>(
  4185. getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()));
  4186. if (Modifier == OMPC_MOTION_MODIFIER_unknown)
  4187. break;
  4188. Data.MotionModifiers.push_back(Modifier);
  4189. Data.MotionModifiersLoc.push_back(Tok.getLocation());
  4190. ConsumeToken();
  4191. if (Modifier == OMPC_MOTION_MODIFIER_mapper) {
  4192. IsInvalidMapperModifier = parseMapperModifier(Data);
  4193. if (IsInvalidMapperModifier)
  4194. break;
  4195. }
  4196. // OpenMP < 5.1 doesn't permit a ',' or additional modifiers.
  4197. if (getLangOpts().OpenMP < 51)
  4198. break;
  4199. // OpenMP 5.1 accepts an optional ',' even if the next character is ':'.
  4200. // TODO: Is that intentional?
  4201. if (Tok.is(tok::comma))
  4202. ConsumeToken();
  4203. }
  4204. if (!Data.MotionModifiers.empty() && Tok.isNot(tok::colon)) {
  4205. if (!IsInvalidMapperModifier) {
  4206. if (getLangOpts().OpenMP < 51)
  4207. Diag(Tok, diag::warn_pragma_expected_colon) << ")";
  4208. else
  4209. Diag(Tok, diag::warn_pragma_expected_colon) << "motion modifier";
  4210. }
  4211. SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
  4212. StopBeforeMatch);
  4213. }
  4214. // OpenMP 5.1 permits a ':' even without a preceding modifier. TODO: Is
  4215. // that intentional?
  4216. if ((!Data.MotionModifiers.empty() || getLangOpts().OpenMP >= 51) &&
  4217. Tok.is(tok::colon))
  4218. Data.ColonLoc = ConsumeToken();
  4219. } else if (Kind == OMPC_allocate ||
  4220. (Kind == OMPC_affinity && Tok.is(tok::identifier) &&
  4221. PP.getSpelling(Tok) == "iterator")) {
  4222. // Handle optional allocator expression followed by colon delimiter.
  4223. ColonProtectionRAIIObject ColonRAII(*this);
  4224. TentativeParsingAction TPA(*this);
  4225. // OpenMP 5.0, 2.10.1, task Construct.
  4226. // where aff-modifier is one of the following:
  4227. // iterator(iterators-definition)
  4228. ExprResult Tail;
  4229. if (Kind == OMPC_allocate) {
  4230. Tail = ParseAssignmentExpression();
  4231. } else {
  4232. HasIterator = true;
  4233. EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
  4234. Tail = ParseOpenMPIteratorsExpr();
  4235. }
  4236. Tail = Actions.CorrectDelayedTyposInExpr(Tail);
  4237. Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(),
  4238. /*DiscardedValue=*/false);
  4239. if (Tail.isUsable()) {
  4240. if (Tok.is(tok::colon)) {
  4241. Data.DepModOrTailExpr = Tail.get();
  4242. Data.ColonLoc = ConsumeToken();
  4243. TPA.Commit();
  4244. } else {
  4245. // Colon not found, parse only list of variables.
  4246. TPA.Revert();
  4247. }
  4248. } else {
  4249. // Parsing was unsuccessfull, revert and skip to the end of clause or
  4250. // directive.
  4251. TPA.Revert();
  4252. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  4253. StopBeforeMatch);
  4254. }
  4255. } else if (Kind == OMPC_adjust_args) {
  4256. // Handle adjust-op for adjust_args clause.
  4257. ColonProtectionRAIIObject ColonRAII(*this);
  4258. Data.ExtraModifier = getOpenMPSimpleClauseType(
  4259. Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
  4260. getLangOpts());
  4261. Data.ExtraModifierLoc = Tok.getLocation();
  4262. if (Data.ExtraModifier == OMPC_ADJUST_ARGS_unknown) {
  4263. SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
  4264. StopBeforeMatch);
  4265. } else {
  4266. ConsumeToken();
  4267. if (Tok.is(tok::colon))
  4268. Data.ColonLoc = Tok.getLocation();
  4269. ExpectAndConsume(tok::colon, diag::warn_pragma_expected_colon,
  4270. "adjust-op");
  4271. }
  4272. }
  4273. bool IsComma =
  4274. (Kind != OMPC_reduction && Kind != OMPC_task_reduction &&
  4275. Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
  4276. (Kind == OMPC_reduction && !InvalidReductionId) ||
  4277. (Kind == OMPC_map && Data.ExtraModifier != OMPC_MAP_unknown) ||
  4278. (Kind == OMPC_depend && Data.ExtraModifier != OMPC_DEPEND_unknown) ||
  4279. (Kind == OMPC_adjust_args &&
  4280. Data.ExtraModifier != OMPC_ADJUST_ARGS_unknown);
  4281. const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
  4282. while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
  4283. Tok.isNot(tok::annot_pragma_openmp_end))) {
  4284. ParseScope OMPListScope(this, Scope::OpenMPDirectiveScope);
  4285. ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
  4286. if (!ParseOpenMPReservedLocator(Kind, Data, getLangOpts())) {
  4287. // Parse variable
  4288. ExprResult VarExpr =
  4289. Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
  4290. if (VarExpr.isUsable()) {
  4291. Vars.push_back(VarExpr.get());
  4292. } else {
  4293. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  4294. StopBeforeMatch);
  4295. }
  4296. }
  4297. // Skip ',' if any
  4298. IsComma = Tok.is(tok::comma);
  4299. if (IsComma)
  4300. ConsumeToken();
  4301. else if (Tok.isNot(tok::r_paren) &&
  4302. Tok.isNot(tok::annot_pragma_openmp_end) &&
  4303. (!MayHaveTail || Tok.isNot(tok::colon)))
  4304. Diag(Tok, diag::err_omp_expected_punc)
  4305. << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
  4306. : getOpenMPClauseName(Kind))
  4307. << (Kind == OMPC_flush);
  4308. }
  4309. // Parse ')' for linear clause with modifier.
  4310. if (NeedRParenForLinear)
  4311. LinearT.consumeClose();
  4312. // Parse ':' linear-step (or ':' alignment).
  4313. const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
  4314. if (MustHaveTail) {
  4315. Data.ColonLoc = Tok.getLocation();
  4316. SourceLocation ELoc = ConsumeToken();
  4317. ExprResult Tail = ParseAssignmentExpression();
  4318. Tail =
  4319. Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false);
  4320. if (Tail.isUsable())
  4321. Data.DepModOrTailExpr = Tail.get();
  4322. else
  4323. SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
  4324. StopBeforeMatch);
  4325. }
  4326. // Parse ')'.
  4327. Data.RLoc = Tok.getLocation();
  4328. if (!T.consumeClose())
  4329. Data.RLoc = T.getCloseLocation();
  4330. // Exit from scope when the iterator is used in depend clause.
  4331. if (HasIterator)
  4332. ExitScope();
  4333. return (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
  4334. (MustHaveTail && !Data.DepModOrTailExpr) || InvalidReductionId ||
  4335. IsInvalidMapperModifier || InvalidIterator;
  4336. }
  4337. /// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
  4338. /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction',
  4339. /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'.
  4340. ///
  4341. /// private-clause:
  4342. /// 'private' '(' list ')'
  4343. /// firstprivate-clause:
  4344. /// 'firstprivate' '(' list ')'
  4345. /// lastprivate-clause:
  4346. /// 'lastprivate' '(' list ')'
  4347. /// shared-clause:
  4348. /// 'shared' '(' list ')'
  4349. /// linear-clause:
  4350. /// 'linear' '(' linear-list [ ':' linear-step ] ')'
  4351. /// aligned-clause:
  4352. /// 'aligned' '(' list [ ':' alignment ] ')'
  4353. /// reduction-clause:
  4354. /// 'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')'
  4355. /// task_reduction-clause:
  4356. /// 'task_reduction' '(' reduction-identifier ':' list ')'
  4357. /// in_reduction-clause:
  4358. /// 'in_reduction' '(' reduction-identifier ':' list ')'
  4359. /// copyprivate-clause:
  4360. /// 'copyprivate' '(' list ')'
  4361. /// flush-clause:
  4362. /// 'flush' '(' list ')'
  4363. /// depend-clause:
  4364. /// 'depend' '(' in | out | inout : list | source ')'
  4365. /// map-clause:
  4366. /// 'map' '(' [ [ always [,] ] [ close [,] ]
  4367. /// [ mapper '(' mapper-identifier ')' [,] ]
  4368. /// to | from | tofrom | alloc | release | delete ':' ] list ')';
  4369. /// to-clause:
  4370. /// 'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
  4371. /// from-clause:
  4372. /// 'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
  4373. /// use_device_ptr-clause:
  4374. /// 'use_device_ptr' '(' list ')'
  4375. /// use_device_addr-clause:
  4376. /// 'use_device_addr' '(' list ')'
  4377. /// is_device_ptr-clause:
  4378. /// 'is_device_ptr' '(' list ')'
  4379. /// has_device_addr-clause:
  4380. /// 'has_device_addr' '(' list ')'
  4381. /// allocate-clause:
  4382. /// 'allocate' '(' [ allocator ':' ] list ')'
  4383. /// nontemporal-clause:
  4384. /// 'nontemporal' '(' list ')'
  4385. /// inclusive-clause:
  4386. /// 'inclusive' '(' list ')'
  4387. /// exclusive-clause:
  4388. /// 'exclusive' '(' list ')'
  4389. ///
  4390. /// For 'linear' clause linear-list may have the following forms:
  4391. /// list
  4392. /// modifier(list)
  4393. /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
  4394. OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
  4395. OpenMPClauseKind Kind,
  4396. bool ParseOnly) {
  4397. SourceLocation Loc = Tok.getLocation();
  4398. SourceLocation LOpen = ConsumeToken();
  4399. SmallVector<Expr *, 4> Vars;
  4400. Sema::OpenMPVarListDataTy Data;
  4401. if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
  4402. return nullptr;
  4403. if (ParseOnly)
  4404. return nullptr;
  4405. OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc);
  4406. return Actions.ActOnOpenMPVarListClause(Kind, Vars, Locs, Data);
  4407. }