SemaOpenMP.cpp 548 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// This file implements semantic analysis for OpenMP directives and
  11. /// clauses.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/Basic/OpenMPKinds.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/ScopeInfo.h"
  29. #include "clang/Sema/SemaInternal.h"
  30. #include "llvm/ADT/PointerEmbeddedInt.h"
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // Stack of data-sharing attributes for variables
  34. //===----------------------------------------------------------------------===//
  35. static const Expr *checkMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind, bool NoDiagnose);
  39. namespace {
  40. /// Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
  45. };
  46. /// Attributes of the defaultmap clause.
  47. enum DefaultMapAttributes {
  48. DMA_unspecified, /// Default mapping is not specified.
  49. DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
  50. };
  51. /// Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy {
  54. public:
  55. struct DSAVarData {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. const Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  63. const Expr *RefExpr, DeclRefExpr *PrivateCopy,
  64. SourceLocation ImplicitDSALoc)
  65. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  66. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  67. };
  68. using OperatorOffsetTy =
  69. llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
  70. using DoacrossDependMapTy =
  71. llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
  72. private:
  73. struct DSAInfo {
  74. OpenMPClauseKind Attributes = OMPC_unknown;
  75. /// Pointer to a reference expression and a flag which shows that the
  76. /// variable is marked as lastprivate(true) or not (false).
  77. llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
  78. DeclRefExpr *PrivateCopy = nullptr;
  79. };
  80. using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
  81. using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
  82. using LCDeclInfo = std::pair<unsigned, VarDecl *>;
  83. using LoopControlVariablesMapTy =
  84. llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
  85. /// Struct that associates a component with the clause kind where they are
  86. /// found.
  87. struct MappedExprComponentTy {
  88. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  89. OpenMPClauseKind Kind = OMPC_unknown;
  90. };
  91. using MappedExprComponentsTy =
  92. llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
  93. using CriticalsWithHintsTy =
  94. llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
  95. struct ReductionData {
  96. using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
  97. SourceRange ReductionRange;
  98. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  99. ReductionData() = default;
  100. void set(BinaryOperatorKind BO, SourceRange RR) {
  101. ReductionRange = RR;
  102. ReductionOp = BO;
  103. }
  104. void set(const Expr *RefExpr, SourceRange RR) {
  105. ReductionRange = RR;
  106. ReductionOp = RefExpr;
  107. }
  108. };
  109. using DeclReductionMapTy =
  110. llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
  111. struct SharingMapTy {
  112. DeclSAMapTy SharingMap;
  113. DeclReductionMapTy ReductionMap;
  114. AlignedMapTy AlignedMap;
  115. MappedExprComponentsTy MappedExprComponents;
  116. LoopControlVariablesMapTy LCVMap;
  117. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  118. SourceLocation DefaultAttrLoc;
  119. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  120. SourceLocation DefaultMapAttrLoc;
  121. OpenMPDirectiveKind Directive = OMPD_unknown;
  122. DeclarationNameInfo DirectiveName;
  123. Scope *CurScope = nullptr;
  124. SourceLocation ConstructLoc;
  125. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  126. /// get the data (loop counters etc.) about enclosing loop-based construct.
  127. /// This data is required during codegen.
  128. DoacrossDependMapTy DoacrossDepends;
  129. /// first argument (Expr *) contains optional argument of the
  130. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  131. /// clause, false otherwise.
  132. llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
  133. unsigned AssociatedLoops = 1;
  134. const Decl *PossiblyLoopCounter = nullptr;
  135. bool NowaitRegion = false;
  136. bool CancelRegion = false;
  137. bool LoopStart = false;
  138. SourceLocation InnerTeamsRegionLoc;
  139. /// Reference to the taskgroup task_reduction reference expression.
  140. Expr *TaskgroupReductionRef = nullptr;
  141. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  142. Scope *CurScope, SourceLocation Loc)
  143. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  144. ConstructLoc(Loc) {}
  145. SharingMapTy() = default;
  146. };
  147. using StackTy = SmallVector<SharingMapTy, 4>;
  148. /// Stack of used declaration and their data-sharing attributes.
  149. DeclSAMapTy Threadprivates;
  150. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  151. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  152. /// true, if check for DSA must be from parent directive, false, if
  153. /// from current directive.
  154. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  155. Sema &SemaRef;
  156. bool ForceCapturing = false;
  157. /// true if all the vaiables in the target executable directives must be
  158. /// captured by reference.
  159. bool ForceCaptureByReferenceInTargetExecutable = false;
  160. CriticalsWithHintsTy Criticals;
  161. using iterator = StackTy::const_reverse_iterator;
  162. DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
  163. /// Checks if the variable is a local for OpenMP region.
  164. bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
  165. bool isStackEmpty() const {
  166. return Stack.empty() ||
  167. Stack.back().second != CurrentNonCapturingFunctionScope ||
  168. Stack.back().first.empty();
  169. }
  170. /// Vector of previously declared requires directives
  171. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  172. public:
  173. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  174. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  175. OpenMPClauseKind getClauseParsingMode() const {
  176. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  177. return ClauseKindMode;
  178. }
  179. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  180. bool isForceVarCapturing() const { return ForceCapturing; }
  181. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  182. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  183. ForceCaptureByReferenceInTargetExecutable = V;
  184. }
  185. bool isForceCaptureByReferenceInTargetExecutable() const {
  186. return ForceCaptureByReferenceInTargetExecutable;
  187. }
  188. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  189. Scope *CurScope, SourceLocation Loc) {
  190. if (Stack.empty() ||
  191. Stack.back().second != CurrentNonCapturingFunctionScope)
  192. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  193. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  194. Stack.back().first.back().DefaultAttrLoc = Loc;
  195. }
  196. void pop() {
  197. assert(!Stack.back().first.empty() &&
  198. "Data-sharing attributes stack is empty!");
  199. Stack.back().first.pop_back();
  200. }
  201. /// Marks that we're started loop parsing.
  202. void loopInit() {
  203. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  204. "Expected loop-based directive.");
  205. Stack.back().first.back().LoopStart = true;
  206. }
  207. /// Start capturing of the variables in the loop context.
  208. void loopStart() {
  209. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  210. "Expected loop-based directive.");
  211. Stack.back().first.back().LoopStart = false;
  212. }
  213. /// true, if variables are captured, false otherwise.
  214. bool isLoopStarted() const {
  215. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  216. "Expected loop-based directive.");
  217. return !Stack.back().first.back().LoopStart;
  218. }
  219. /// Marks (or clears) declaration as possibly loop counter.
  220. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  221. Stack.back().first.back().PossiblyLoopCounter =
  222. D ? D->getCanonicalDecl() : D;
  223. }
  224. /// Gets the possible loop counter decl.
  225. const Decl *getPossiblyLoopCunter() const {
  226. return Stack.back().first.back().PossiblyLoopCounter;
  227. }
  228. /// Start new OpenMP region stack in new non-capturing function.
  229. void pushFunction() {
  230. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  231. assert(!isa<CapturingScopeInfo>(CurFnScope));
  232. CurrentNonCapturingFunctionScope = CurFnScope;
  233. }
  234. /// Pop region stack for non-capturing function.
  235. void popFunction(const FunctionScopeInfo *OldFSI) {
  236. if (!Stack.empty() && Stack.back().second == OldFSI) {
  237. assert(Stack.back().first.empty());
  238. Stack.pop_back();
  239. }
  240. CurrentNonCapturingFunctionScope = nullptr;
  241. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  242. if (!isa<CapturingScopeInfo>(FSI)) {
  243. CurrentNonCapturingFunctionScope = FSI;
  244. break;
  245. }
  246. }
  247. }
  248. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  249. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  250. }
  251. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  252. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  253. auto I = Criticals.find(Name.getAsString());
  254. if (I != Criticals.end())
  255. return I->second;
  256. return std::make_pair(nullptr, llvm::APSInt());
  257. }
  258. /// If 'aligned' declaration for given variable \a D was not seen yet,
  259. /// add it and return NULL; otherwise return previous occurrence's expression
  260. /// for diagnostics.
  261. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  262. /// Register specified variable as loop control variable.
  263. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  264. /// Check if the specified variable is a loop control variable for
  265. /// current region.
  266. /// \return The index of the loop control variable in the list of associated
  267. /// for-loops (from outer to inner).
  268. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  269. /// Check if the specified variable is a loop control variable for
  270. /// parent region.
  271. /// \return The index of the loop control variable in the list of associated
  272. /// for-loops (from outer to inner).
  273. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  274. /// Get the loop control variable for the I-th loop (or nullptr) in
  275. /// parent directive.
  276. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  277. /// Adds explicit data sharing attribute to the specified declaration.
  278. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  279. DeclRefExpr *PrivateCopy = nullptr);
  280. /// Adds additional information for the reduction items with the reduction id
  281. /// represented as an operator.
  282. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  283. BinaryOperatorKind BOK);
  284. /// Adds additional information for the reduction items with the reduction id
  285. /// represented as reduction identifier.
  286. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  287. const Expr *ReductionRef);
  288. /// Returns the location and reduction operation from the innermost parent
  289. /// region for the given \p D.
  290. const DSAVarData
  291. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  292. BinaryOperatorKind &BOK,
  293. Expr *&TaskgroupDescriptor) const;
  294. /// Returns the location and reduction operation from the innermost parent
  295. /// region for the given \p D.
  296. const DSAVarData
  297. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  298. const Expr *&ReductionRef,
  299. Expr *&TaskgroupDescriptor) const;
  300. /// Return reduction reference expression for the current taskgroup.
  301. Expr *getTaskgroupReductionRef() const {
  302. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  303. "taskgroup reference expression requested for non taskgroup "
  304. "directive.");
  305. return Stack.back().first.back().TaskgroupReductionRef;
  306. }
  307. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  308. /// descriptor variable at the \p Level of OpenMP regions.
  309. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  310. return Stack.back().first[Level].TaskgroupReductionRef &&
  311. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  312. ->getDecl() == VD;
  313. }
  314. /// Returns data sharing attributes from top of the stack for the
  315. /// specified declaration.
  316. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  317. /// Returns data-sharing attributes for the specified declaration.
  318. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  319. /// Checks if the specified variables has data-sharing attributes which
  320. /// match specified \a CPred predicate in any directive which matches \a DPred
  321. /// predicate.
  322. const DSAVarData
  323. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  324. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  325. bool FromParent) const;
  326. /// Checks if the specified variables has data-sharing attributes which
  327. /// match specified \a CPred predicate in any innermost directive which
  328. /// matches \a DPred predicate.
  329. const DSAVarData
  330. hasInnermostDSA(ValueDecl *D,
  331. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  332. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  333. bool FromParent) const;
  334. /// Checks if the specified variables has explicit data-sharing
  335. /// attributes which match specified \a CPred predicate at the specified
  336. /// OpenMP region.
  337. bool hasExplicitDSA(const ValueDecl *D,
  338. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  339. unsigned Level, bool NotLastprivate = false) const;
  340. /// Returns true if the directive at level \Level matches in the
  341. /// specified \a DPred predicate.
  342. bool hasExplicitDirective(
  343. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  344. unsigned Level) const;
  345. /// Finds a directive which matches specified \a DPred predicate.
  346. bool hasDirective(
  347. const llvm::function_ref<bool(
  348. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  349. DPred,
  350. bool FromParent) const;
  351. /// Returns currently analyzed directive.
  352. OpenMPDirectiveKind getCurrentDirective() const {
  353. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  354. }
  355. /// Returns directive kind at specified level.
  356. OpenMPDirectiveKind getDirective(unsigned Level) const {
  357. assert(!isStackEmpty() && "No directive at specified level.");
  358. return Stack.back().first[Level].Directive;
  359. }
  360. /// Returns parent directive.
  361. OpenMPDirectiveKind getParentDirective() const {
  362. if (isStackEmpty() || Stack.back().first.size() == 1)
  363. return OMPD_unknown;
  364. return std::next(Stack.back().first.rbegin())->Directive;
  365. }
  366. /// Add requires decl to internal vector
  367. void addRequiresDecl(OMPRequiresDecl *RD) {
  368. RequiresDecls.push_back(RD);
  369. }
  370. /// Checks for a duplicate clause amongst previously declared requires
  371. /// directives
  372. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  373. bool IsDuplicate = false;
  374. for (OMPClause *CNew : ClauseList) {
  375. for (const OMPRequiresDecl *D : RequiresDecls) {
  376. for (const OMPClause *CPrev : D->clauselists()) {
  377. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  378. SemaRef.Diag(CNew->getBeginLoc(),
  379. diag::err_omp_requires_clause_redeclaration)
  380. << getOpenMPClauseName(CNew->getClauseKind());
  381. SemaRef.Diag(CPrev->getBeginLoc(),
  382. diag::note_omp_requires_previous_clause)
  383. << getOpenMPClauseName(CPrev->getClauseKind());
  384. IsDuplicate = true;
  385. }
  386. }
  387. }
  388. }
  389. return IsDuplicate;
  390. }
  391. /// Set default data sharing attribute to none.
  392. void setDefaultDSANone(SourceLocation Loc) {
  393. assert(!isStackEmpty());
  394. Stack.back().first.back().DefaultAttr = DSA_none;
  395. Stack.back().first.back().DefaultAttrLoc = Loc;
  396. }
  397. /// Set default data sharing attribute to shared.
  398. void setDefaultDSAShared(SourceLocation Loc) {
  399. assert(!isStackEmpty());
  400. Stack.back().first.back().DefaultAttr = DSA_shared;
  401. Stack.back().first.back().DefaultAttrLoc = Loc;
  402. }
  403. /// Set default data mapping attribute to 'tofrom:scalar'.
  404. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  405. assert(!isStackEmpty());
  406. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  407. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  408. }
  409. DefaultDataSharingAttributes getDefaultDSA() const {
  410. return isStackEmpty() ? DSA_unspecified
  411. : Stack.back().first.back().DefaultAttr;
  412. }
  413. SourceLocation getDefaultDSALocation() const {
  414. return isStackEmpty() ? SourceLocation()
  415. : Stack.back().first.back().DefaultAttrLoc;
  416. }
  417. DefaultMapAttributes getDefaultDMA() const {
  418. return isStackEmpty() ? DMA_unspecified
  419. : Stack.back().first.back().DefaultMapAttr;
  420. }
  421. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  422. return Stack.back().first[Level].DefaultMapAttr;
  423. }
  424. SourceLocation getDefaultDMALocation() const {
  425. return isStackEmpty() ? SourceLocation()
  426. : Stack.back().first.back().DefaultMapAttrLoc;
  427. }
  428. /// Checks if the specified variable is a threadprivate.
  429. bool isThreadPrivate(VarDecl *D) {
  430. const DSAVarData DVar = getTopDSA(D, false);
  431. return isOpenMPThreadPrivate(DVar.CKind);
  432. }
  433. /// Marks current region as ordered (it has an 'ordered' clause).
  434. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  435. OMPOrderedClause *Clause) {
  436. assert(!isStackEmpty());
  437. if (IsOrdered)
  438. Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
  439. else
  440. Stack.back().first.back().OrderedRegion.reset();
  441. }
  442. /// Returns true, if region is ordered (has associated 'ordered' clause),
  443. /// false - otherwise.
  444. bool isOrderedRegion() const {
  445. if (isStackEmpty())
  446. return false;
  447. return Stack.back().first.rbegin()->OrderedRegion.hasValue();
  448. }
  449. /// Returns optional parameter for the ordered region.
  450. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  451. if (isStackEmpty() ||
  452. !Stack.back().first.rbegin()->OrderedRegion.hasValue())
  453. return std::make_pair(nullptr, nullptr);
  454. return Stack.back().first.rbegin()->OrderedRegion.getValue();
  455. }
  456. /// Returns true, if parent region is ordered (has associated
  457. /// 'ordered' clause), false - otherwise.
  458. bool isParentOrderedRegion() const {
  459. if (isStackEmpty() || Stack.back().first.size() == 1)
  460. return false;
  461. return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
  462. }
  463. /// Returns optional parameter for the ordered region.
  464. std::pair<const Expr *, OMPOrderedClause *>
  465. getParentOrderedRegionParam() const {
  466. if (isStackEmpty() || Stack.back().first.size() == 1 ||
  467. !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
  468. return std::make_pair(nullptr, nullptr);
  469. return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
  470. }
  471. /// Marks current region as nowait (it has a 'nowait' clause).
  472. void setNowaitRegion(bool IsNowait = true) {
  473. assert(!isStackEmpty());
  474. Stack.back().first.back().NowaitRegion = IsNowait;
  475. }
  476. /// Returns true, if parent region is nowait (has associated
  477. /// 'nowait' clause), false - otherwise.
  478. bool isParentNowaitRegion() const {
  479. if (isStackEmpty() || Stack.back().first.size() == 1)
  480. return false;
  481. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  482. }
  483. /// Marks parent region as cancel region.
  484. void setParentCancelRegion(bool Cancel = true) {
  485. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  486. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  487. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  488. }
  489. }
  490. /// Return true if current region has inner cancel construct.
  491. bool isCancelRegion() const {
  492. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  493. }
  494. /// Set collapse value for the region.
  495. void setAssociatedLoops(unsigned Val) {
  496. assert(!isStackEmpty());
  497. Stack.back().first.back().AssociatedLoops = Val;
  498. }
  499. /// Return collapse value for region.
  500. unsigned getAssociatedLoops() const {
  501. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  502. }
  503. /// Marks current target region as one with closely nested teams
  504. /// region.
  505. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  506. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  507. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  508. TeamsRegionLoc;
  509. }
  510. }
  511. /// Returns true, if current region has closely nested teams region.
  512. bool hasInnerTeamsRegion() const {
  513. return getInnerTeamsRegionLoc().isValid();
  514. }
  515. /// Returns location of the nested teams region (if any).
  516. SourceLocation getInnerTeamsRegionLoc() const {
  517. return isStackEmpty() ? SourceLocation()
  518. : Stack.back().first.back().InnerTeamsRegionLoc;
  519. }
  520. Scope *getCurScope() const {
  521. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  522. }
  523. SourceLocation getConstructLoc() const {
  524. return isStackEmpty() ? SourceLocation()
  525. : Stack.back().first.back().ConstructLoc;
  526. }
  527. /// Do the check specified in \a Check to all component lists and return true
  528. /// if any issue is found.
  529. bool checkMappableExprComponentListsForDecl(
  530. const ValueDecl *VD, bool CurrentRegionOnly,
  531. const llvm::function_ref<
  532. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  533. OpenMPClauseKind)>
  534. Check) const {
  535. if (isStackEmpty())
  536. return false;
  537. auto SI = Stack.back().first.rbegin();
  538. auto SE = Stack.back().first.rend();
  539. if (SI == SE)
  540. return false;
  541. if (CurrentRegionOnly)
  542. SE = std::next(SI);
  543. else
  544. std::advance(SI, 1);
  545. for (; SI != SE; ++SI) {
  546. auto MI = SI->MappedExprComponents.find(VD);
  547. if (MI != SI->MappedExprComponents.end())
  548. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  549. MI->second.Components)
  550. if (Check(L, MI->second.Kind))
  551. return true;
  552. }
  553. return false;
  554. }
  555. /// Do the check specified in \a Check to all component lists at a given level
  556. /// and return true if any issue is found.
  557. bool checkMappableExprComponentListsForDeclAtLevel(
  558. const ValueDecl *VD, unsigned Level,
  559. const llvm::function_ref<
  560. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  561. OpenMPClauseKind)>
  562. Check) const {
  563. if (isStackEmpty())
  564. return false;
  565. auto StartI = Stack.back().first.begin();
  566. auto EndI = Stack.back().first.end();
  567. if (std::distance(StartI, EndI) <= (int)Level)
  568. return false;
  569. std::advance(StartI, Level);
  570. auto MI = StartI->MappedExprComponents.find(VD);
  571. if (MI != StartI->MappedExprComponents.end())
  572. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  573. MI->second.Components)
  574. if (Check(L, MI->second.Kind))
  575. return true;
  576. return false;
  577. }
  578. /// Create a new mappable expression component list associated with a given
  579. /// declaration and initialize it with the provided list of components.
  580. void addMappableExpressionComponents(
  581. const ValueDecl *VD,
  582. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  583. OpenMPClauseKind WhereFoundClauseKind) {
  584. assert(!isStackEmpty() &&
  585. "Not expecting to retrieve components from a empty stack!");
  586. MappedExprComponentTy &MEC =
  587. Stack.back().first.back().MappedExprComponents[VD];
  588. // Create new entry and append the new components there.
  589. MEC.Components.resize(MEC.Components.size() + 1);
  590. MEC.Components.back().append(Components.begin(), Components.end());
  591. MEC.Kind = WhereFoundClauseKind;
  592. }
  593. unsigned getNestingLevel() const {
  594. assert(!isStackEmpty());
  595. return Stack.back().first.size() - 1;
  596. }
  597. void addDoacrossDependClause(OMPDependClause *C,
  598. const OperatorOffsetTy &OpsOffs) {
  599. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  600. SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  601. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  602. StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
  603. }
  604. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  605. getDoacrossDependClauses() const {
  606. assert(!isStackEmpty());
  607. const SharingMapTy &StackElem = Stack.back().first.back();
  608. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  609. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  610. return llvm::make_range(Ref.begin(), Ref.end());
  611. }
  612. return llvm::make_range(StackElem.DoacrossDepends.end(),
  613. StackElem.DoacrossDepends.end());
  614. }
  615. };
  616. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  617. return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
  618. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  619. }
  620. } // namespace
  621. static const Expr *getExprAsWritten(const Expr *E) {
  622. if (const auto *FE = dyn_cast<FullExpr>(E))
  623. E = FE->getSubExpr();
  624. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  625. E = MTE->GetTemporaryExpr();
  626. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  627. E = Binder->getSubExpr();
  628. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  629. E = ICE->getSubExprAsWritten();
  630. return E->IgnoreParens();
  631. }
  632. static Expr *getExprAsWritten(Expr *E) {
  633. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  634. }
  635. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  636. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  637. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  638. D = ME->getMemberDecl();
  639. const auto *VD = dyn_cast<VarDecl>(D);
  640. const auto *FD = dyn_cast<FieldDecl>(D);
  641. if (VD != nullptr) {
  642. VD = VD->getCanonicalDecl();
  643. D = VD;
  644. } else {
  645. assert(FD);
  646. FD = FD->getCanonicalDecl();
  647. D = FD;
  648. }
  649. return D;
  650. }
  651. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  652. return const_cast<ValueDecl *>(
  653. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  654. }
  655. DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
  656. ValueDecl *D) const {
  657. D = getCanonicalDecl(D);
  658. auto *VD = dyn_cast<VarDecl>(D);
  659. const auto *FD = dyn_cast<FieldDecl>(D);
  660. DSAVarData DVar;
  661. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  662. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  663. // in a region but not in construct]
  664. // File-scope or namespace-scope variables referenced in called routines
  665. // in the region are shared unless they appear in a threadprivate
  666. // directive.
  667. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  668. DVar.CKind = OMPC_shared;
  669. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  670. // in a region but not in construct]
  671. // Variables with static storage duration that are declared in called
  672. // routines in the region are shared.
  673. if (VD && VD->hasGlobalStorage())
  674. DVar.CKind = OMPC_shared;
  675. // Non-static data members are shared by default.
  676. if (FD)
  677. DVar.CKind = OMPC_shared;
  678. return DVar;
  679. }
  680. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  681. // in a Construct, C/C++, predetermined, p.1]
  682. // Variables with automatic storage duration that are declared in a scope
  683. // inside the construct are private.
  684. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  685. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  686. DVar.CKind = OMPC_private;
  687. return DVar;
  688. }
  689. DVar.DKind = Iter->Directive;
  690. // Explicitly specified attributes and local variables with predetermined
  691. // attributes.
  692. if (Iter->SharingMap.count(D)) {
  693. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  694. DVar.RefExpr = Data.RefExpr.getPointer();
  695. DVar.PrivateCopy = Data.PrivateCopy;
  696. DVar.CKind = Data.Attributes;
  697. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  698. return DVar;
  699. }
  700. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  701. // in a Construct, C/C++, implicitly determined, p.1]
  702. // In a parallel or task construct, the data-sharing attributes of these
  703. // variables are determined by the default clause, if present.
  704. switch (Iter->DefaultAttr) {
  705. case DSA_shared:
  706. DVar.CKind = OMPC_shared;
  707. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  708. return DVar;
  709. case DSA_none:
  710. return DVar;
  711. case DSA_unspecified:
  712. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  713. // in a Construct, implicitly determined, p.2]
  714. // In a parallel construct, if no default clause is present, these
  715. // variables are shared.
  716. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  717. if (isOpenMPParallelDirective(DVar.DKind) ||
  718. isOpenMPTeamsDirective(DVar.DKind)) {
  719. DVar.CKind = OMPC_shared;
  720. return DVar;
  721. }
  722. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  723. // in a Construct, implicitly determined, p.4]
  724. // In a task construct, if no default clause is present, a variable that in
  725. // the enclosing context is determined to be shared by all implicit tasks
  726. // bound to the current team is shared.
  727. if (isOpenMPTaskingDirective(DVar.DKind)) {
  728. DSAVarData DVarTemp;
  729. iterator I = Iter, E = Stack.back().first.rend();
  730. do {
  731. ++I;
  732. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  733. // Referenced in a Construct, implicitly determined, p.6]
  734. // In a task construct, if no default clause is present, a variable
  735. // whose data-sharing attribute is not determined by the rules above is
  736. // firstprivate.
  737. DVarTemp = getDSA(I, D);
  738. if (DVarTemp.CKind != OMPC_shared) {
  739. DVar.RefExpr = nullptr;
  740. DVar.CKind = OMPC_firstprivate;
  741. return DVar;
  742. }
  743. } while (I != E && !isParallelOrTaskRegion(I->Directive));
  744. DVar.CKind =
  745. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  746. return DVar;
  747. }
  748. }
  749. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  750. // in a Construct, implicitly determined, p.3]
  751. // For constructs other than task, if no default clause is present, these
  752. // variables inherit their data-sharing attributes from the enclosing
  753. // context.
  754. return getDSA(++Iter, D);
  755. }
  756. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  757. const Expr *NewDE) {
  758. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  759. D = getCanonicalDecl(D);
  760. SharingMapTy &StackElem = Stack.back().first.back();
  761. auto It = StackElem.AlignedMap.find(D);
  762. if (It == StackElem.AlignedMap.end()) {
  763. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  764. StackElem.AlignedMap[D] = NewDE;
  765. return nullptr;
  766. }
  767. assert(It->second && "Unexpected nullptr expr in the aligned map");
  768. return It->second;
  769. }
  770. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  771. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  772. D = getCanonicalDecl(D);
  773. SharingMapTy &StackElem = Stack.back().first.back();
  774. StackElem.LCVMap.try_emplace(
  775. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  776. }
  777. const DSAStackTy::LCDeclInfo
  778. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  779. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  780. D = getCanonicalDecl(D);
  781. const SharingMapTy &StackElem = Stack.back().first.back();
  782. auto It = StackElem.LCVMap.find(D);
  783. if (It != StackElem.LCVMap.end())
  784. return It->second;
  785. return {0, nullptr};
  786. }
  787. const DSAStackTy::LCDeclInfo
  788. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  789. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  790. "Data-sharing attributes stack is empty");
  791. D = getCanonicalDecl(D);
  792. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  793. auto It = StackElem.LCVMap.find(D);
  794. if (It != StackElem.LCVMap.end())
  795. return It->second;
  796. return {0, nullptr};
  797. }
  798. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  799. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  800. "Data-sharing attributes stack is empty");
  801. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  802. if (StackElem.LCVMap.size() < I)
  803. return nullptr;
  804. for (const auto &Pair : StackElem.LCVMap)
  805. if (Pair.second.first == I)
  806. return Pair.first;
  807. return nullptr;
  808. }
  809. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  810. DeclRefExpr *PrivateCopy) {
  811. D = getCanonicalDecl(D);
  812. if (A == OMPC_threadprivate) {
  813. DSAInfo &Data = Threadprivates[D];
  814. Data.Attributes = A;
  815. Data.RefExpr.setPointer(E);
  816. Data.PrivateCopy = nullptr;
  817. } else {
  818. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  819. DSAInfo &Data = Stack.back().first.back().SharingMap[D];
  820. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  821. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  822. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  823. (isLoopControlVariable(D).first && A == OMPC_private));
  824. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  825. Data.RefExpr.setInt(/*IntVal=*/true);
  826. return;
  827. }
  828. const bool IsLastprivate =
  829. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  830. Data.Attributes = A;
  831. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  832. Data.PrivateCopy = PrivateCopy;
  833. if (PrivateCopy) {
  834. DSAInfo &Data =
  835. Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  836. Data.Attributes = A;
  837. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  838. Data.PrivateCopy = nullptr;
  839. }
  840. }
  841. }
  842. /// Build a variable declaration for OpenMP loop iteration variable.
  843. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  844. StringRef Name, const AttrVec *Attrs = nullptr,
  845. DeclRefExpr *OrigRef = nullptr) {
  846. DeclContext *DC = SemaRef.CurContext;
  847. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  848. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  849. auto *Decl =
  850. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  851. if (Attrs) {
  852. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  853. I != E; ++I)
  854. Decl->addAttr(*I);
  855. }
  856. Decl->setImplicit();
  857. if (OrigRef) {
  858. Decl->addAttr(
  859. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  860. }
  861. return Decl;
  862. }
  863. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  864. SourceLocation Loc,
  865. bool RefersToCapture = false) {
  866. D->setReferenced();
  867. D->markUsed(S.Context);
  868. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  869. SourceLocation(), D, RefersToCapture, Loc, Ty,
  870. VK_LValue);
  871. }
  872. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  873. BinaryOperatorKind BOK) {
  874. D = getCanonicalDecl(D);
  875. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  876. assert(
  877. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  878. "Additional reduction info may be specified only for reduction items.");
  879. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  880. assert(ReductionData.ReductionRange.isInvalid() &&
  881. Stack.back().first.back().Directive == OMPD_taskgroup &&
  882. "Additional reduction info may be specified only once for reduction "
  883. "items.");
  884. ReductionData.set(BOK, SR);
  885. Expr *&TaskgroupReductionRef =
  886. Stack.back().first.back().TaskgroupReductionRef;
  887. if (!TaskgroupReductionRef) {
  888. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  889. SemaRef.Context.VoidPtrTy, ".task_red.");
  890. TaskgroupReductionRef =
  891. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  892. }
  893. }
  894. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  895. const Expr *ReductionRef) {
  896. D = getCanonicalDecl(D);
  897. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  898. assert(
  899. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  900. "Additional reduction info may be specified only for reduction items.");
  901. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  902. assert(ReductionData.ReductionRange.isInvalid() &&
  903. Stack.back().first.back().Directive == OMPD_taskgroup &&
  904. "Additional reduction info may be specified only once for reduction "
  905. "items.");
  906. ReductionData.set(ReductionRef, SR);
  907. Expr *&TaskgroupReductionRef =
  908. Stack.back().first.back().TaskgroupReductionRef;
  909. if (!TaskgroupReductionRef) {
  910. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  911. SemaRef.Context.VoidPtrTy, ".task_red.");
  912. TaskgroupReductionRef =
  913. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  914. }
  915. }
  916. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  917. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  918. Expr *&TaskgroupDescriptor) const {
  919. D = getCanonicalDecl(D);
  920. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  921. if (Stack.back().first.empty())
  922. return DSAVarData();
  923. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  924. E = Stack.back().first.rend();
  925. I != E; std::advance(I, 1)) {
  926. const DSAInfo &Data = I->SharingMap.lookup(D);
  927. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  928. continue;
  929. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  930. if (!ReductionData.ReductionOp ||
  931. ReductionData.ReductionOp.is<const Expr *>())
  932. return DSAVarData();
  933. SR = ReductionData.ReductionRange;
  934. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  935. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  936. "expression for the descriptor is not "
  937. "set.");
  938. TaskgroupDescriptor = I->TaskgroupReductionRef;
  939. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  940. Data.PrivateCopy, I->DefaultAttrLoc);
  941. }
  942. return DSAVarData();
  943. }
  944. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  945. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  946. Expr *&TaskgroupDescriptor) const {
  947. D = getCanonicalDecl(D);
  948. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  949. if (Stack.back().first.empty())
  950. return DSAVarData();
  951. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  952. E = Stack.back().first.rend();
  953. I != E; std::advance(I, 1)) {
  954. const DSAInfo &Data = I->SharingMap.lookup(D);
  955. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  956. continue;
  957. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  958. if (!ReductionData.ReductionOp ||
  959. !ReductionData.ReductionOp.is<const Expr *>())
  960. return DSAVarData();
  961. SR = ReductionData.ReductionRange;
  962. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  963. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  964. "expression for the descriptor is not "
  965. "set.");
  966. TaskgroupDescriptor = I->TaskgroupReductionRef;
  967. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  968. Data.PrivateCopy, I->DefaultAttrLoc);
  969. }
  970. return DSAVarData();
  971. }
  972. bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
  973. D = D->getCanonicalDecl();
  974. if (!isStackEmpty()) {
  975. iterator I = Iter, E = Stack.back().first.rend();
  976. Scope *TopScope = nullptr;
  977. while (I != E && !isParallelOrTaskRegion(I->Directive) &&
  978. !isOpenMPTargetExecutionDirective(I->Directive))
  979. ++I;
  980. if (I == E)
  981. return false;
  982. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  983. Scope *CurScope = getCurScope();
  984. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  985. CurScope = CurScope->getParent();
  986. return CurScope != TopScope;
  987. }
  988. return false;
  989. }
  990. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  991. bool FromParent) {
  992. D = getCanonicalDecl(D);
  993. DSAVarData DVar;
  994. auto *VD = dyn_cast<VarDecl>(D);
  995. auto TI = Threadprivates.find(D);
  996. if (TI != Threadprivates.end()) {
  997. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  998. DVar.CKind = OMPC_threadprivate;
  999. return DVar;
  1000. }
  1001. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1002. DVar.RefExpr = buildDeclRefExpr(
  1003. SemaRef, VD, D->getType().getNonReferenceType(),
  1004. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1005. DVar.CKind = OMPC_threadprivate;
  1006. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1007. return DVar;
  1008. }
  1009. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1010. // in a Construct, C/C++, predetermined, p.1]
  1011. // Variables appearing in threadprivate directives are threadprivate.
  1012. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1013. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1014. SemaRef.getLangOpts().OpenMPUseTLS &&
  1015. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1016. (VD && VD->getStorageClass() == SC_Register &&
  1017. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1018. DVar.RefExpr = buildDeclRefExpr(
  1019. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1020. DVar.CKind = OMPC_threadprivate;
  1021. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1022. return DVar;
  1023. }
  1024. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1025. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1026. !isLoopControlVariable(D).first) {
  1027. iterator IterTarget =
  1028. std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
  1029. [](const SharingMapTy &Data) {
  1030. return isOpenMPTargetExecutionDirective(Data.Directive);
  1031. });
  1032. if (IterTarget != Stack.back().first.rend()) {
  1033. iterator ParentIterTarget = std::next(IterTarget, 1);
  1034. for (iterator Iter = Stack.back().first.rbegin();
  1035. Iter != ParentIterTarget; std::advance(Iter, 1)) {
  1036. if (isOpenMPLocal(VD, Iter)) {
  1037. DVar.RefExpr =
  1038. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1039. D->getLocation());
  1040. DVar.CKind = OMPC_threadprivate;
  1041. return DVar;
  1042. }
  1043. }
  1044. if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
  1045. auto DSAIter = IterTarget->SharingMap.find(D);
  1046. if (DSAIter != IterTarget->SharingMap.end() &&
  1047. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1048. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1049. DVar.CKind = OMPC_threadprivate;
  1050. return DVar;
  1051. }
  1052. iterator End = Stack.back().first.rend();
  1053. if (!SemaRef.isOpenMPCapturedByRef(
  1054. D, std::distance(ParentIterTarget, End))) {
  1055. DVar.RefExpr =
  1056. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1057. IterTarget->ConstructLoc);
  1058. DVar.CKind = OMPC_threadprivate;
  1059. return DVar;
  1060. }
  1061. }
  1062. }
  1063. }
  1064. if (isStackEmpty())
  1065. // Not in OpenMP execution region and top scope was already checked.
  1066. return DVar;
  1067. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1068. // in a Construct, C/C++, predetermined, p.4]
  1069. // Static data members are shared.
  1070. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1071. // in a Construct, C/C++, predetermined, p.7]
  1072. // Variables with static storage duration that are declared in a scope
  1073. // inside the construct are shared.
  1074. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1075. if (VD && VD->isStaticDataMember()) {
  1076. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  1077. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1078. return DVar;
  1079. DVar.CKind = OMPC_shared;
  1080. return DVar;
  1081. }
  1082. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  1083. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  1084. Type = SemaRef.getASTContext().getBaseElementType(Type);
  1085. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1086. // in a Construct, C/C++, predetermined, p.6]
  1087. // Variables with const qualified type having no mutable member are
  1088. // shared.
  1089. const CXXRecordDecl *RD =
  1090. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  1091. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1092. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1093. RD = CTD->getTemplatedDecl();
  1094. if (IsConstant &&
  1095. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  1096. RD->hasMutableFields())) {
  1097. // Variables with const-qualified type having no mutable member may be
  1098. // listed in a firstprivate clause, even if they are static data members.
  1099. DSAVarData DVarTemp =
  1100. hasDSA(D, [](OpenMPClauseKind C) { return C == OMPC_firstprivate; },
  1101. MatchesAlways, FromParent);
  1102. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  1103. return DVarTemp;
  1104. DVar.CKind = OMPC_shared;
  1105. return DVar;
  1106. }
  1107. // Explicitly specified attributes and local variables with predetermined
  1108. // attributes.
  1109. iterator I = Stack.back().first.rbegin();
  1110. iterator EndI = Stack.back().first.rend();
  1111. if (FromParent && I != EndI)
  1112. std::advance(I, 1);
  1113. auto It = I->SharingMap.find(D);
  1114. if (It != I->SharingMap.end()) {
  1115. const DSAInfo &Data = It->getSecond();
  1116. DVar.RefExpr = Data.RefExpr.getPointer();
  1117. DVar.PrivateCopy = Data.PrivateCopy;
  1118. DVar.CKind = Data.Attributes;
  1119. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1120. DVar.DKind = I->Directive;
  1121. }
  1122. return DVar;
  1123. }
  1124. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1125. bool FromParent) const {
  1126. if (isStackEmpty()) {
  1127. iterator I;
  1128. return getDSA(I, D);
  1129. }
  1130. D = getCanonicalDecl(D);
  1131. iterator StartI = Stack.back().first.rbegin();
  1132. iterator EndI = Stack.back().first.rend();
  1133. if (FromParent && StartI != EndI)
  1134. std::advance(StartI, 1);
  1135. return getDSA(StartI, D);
  1136. }
  1137. const DSAStackTy::DSAVarData
  1138. DSAStackTy::hasDSA(ValueDecl *D,
  1139. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1140. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1141. bool FromParent) const {
  1142. if (isStackEmpty())
  1143. return {};
  1144. D = getCanonicalDecl(D);
  1145. iterator I = Stack.back().first.rbegin();
  1146. iterator EndI = Stack.back().first.rend();
  1147. if (FromParent && I != EndI)
  1148. std::advance(I, 1);
  1149. for (; I != EndI; std::advance(I, 1)) {
  1150. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  1151. continue;
  1152. iterator NewI = I;
  1153. DSAVarData DVar = getDSA(NewI, D);
  1154. if (I == NewI && CPred(DVar.CKind))
  1155. return DVar;
  1156. }
  1157. return {};
  1158. }
  1159. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1160. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1161. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1162. bool FromParent) const {
  1163. if (isStackEmpty())
  1164. return {};
  1165. D = getCanonicalDecl(D);
  1166. iterator StartI = Stack.back().first.rbegin();
  1167. iterator EndI = Stack.back().first.rend();
  1168. if (FromParent && StartI != EndI)
  1169. std::advance(StartI, 1);
  1170. if (StartI == EndI || !DPred(StartI->Directive))
  1171. return {};
  1172. iterator NewI = StartI;
  1173. DSAVarData DVar = getDSA(NewI, D);
  1174. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1175. }
  1176. bool DSAStackTy::hasExplicitDSA(
  1177. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1178. unsigned Level, bool NotLastprivate) const {
  1179. if (isStackEmpty())
  1180. return false;
  1181. D = getCanonicalDecl(D);
  1182. auto StartI = Stack.back().first.begin();
  1183. auto EndI = Stack.back().first.end();
  1184. if (std::distance(StartI, EndI) <= (int)Level)
  1185. return false;
  1186. std::advance(StartI, Level);
  1187. auto I = StartI->SharingMap.find(D);
  1188. if ((I != StartI->SharingMap.end()) &&
  1189. I->getSecond().RefExpr.getPointer() &&
  1190. CPred(I->getSecond().Attributes) &&
  1191. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1192. return true;
  1193. // Check predetermined rules for the loop control variables.
  1194. auto LI = StartI->LCVMap.find(D);
  1195. if (LI != StartI->LCVMap.end())
  1196. return CPred(OMPC_private);
  1197. return false;
  1198. }
  1199. bool DSAStackTy::hasExplicitDirective(
  1200. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1201. unsigned Level) const {
  1202. if (isStackEmpty())
  1203. return false;
  1204. auto StartI = Stack.back().first.begin();
  1205. auto EndI = Stack.back().first.end();
  1206. if (std::distance(StartI, EndI) <= (int)Level)
  1207. return false;
  1208. std::advance(StartI, Level);
  1209. return DPred(StartI->Directive);
  1210. }
  1211. bool DSAStackTy::hasDirective(
  1212. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1213. const DeclarationNameInfo &, SourceLocation)>
  1214. DPred,
  1215. bool FromParent) const {
  1216. // We look only in the enclosing region.
  1217. if (isStackEmpty())
  1218. return false;
  1219. auto StartI = std::next(Stack.back().first.rbegin());
  1220. auto EndI = Stack.back().first.rend();
  1221. if (FromParent && StartI != EndI)
  1222. StartI = std::next(StartI);
  1223. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1224. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1225. return true;
  1226. }
  1227. return false;
  1228. }
  1229. void Sema::InitDataSharingAttributesStack() {
  1230. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1231. }
  1232. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1233. void Sema::pushOpenMPFunctionRegion() {
  1234. DSAStack->pushFunction();
  1235. }
  1236. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1237. DSAStack->popFunction(OldFSI);
  1238. }
  1239. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
  1240. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1241. ASTContext &Ctx = getASTContext();
  1242. bool IsByRef = true;
  1243. // Find the directive that is associated with the provided scope.
  1244. D = cast<ValueDecl>(D->getCanonicalDecl());
  1245. QualType Ty = D->getType();
  1246. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1247. // This table summarizes how a given variable should be passed to the device
  1248. // given its type and the clauses where it appears. This table is based on
  1249. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1250. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1251. //
  1252. // =========================================================================
  1253. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1254. // | |(tofrom:scalar)| | pvt | | | |
  1255. // =========================================================================
  1256. // | scl | | | | - | | bycopy|
  1257. // | scl | | - | x | - | - | bycopy|
  1258. // | scl | | x | - | - | - | null |
  1259. // | scl | x | | | - | | byref |
  1260. // | scl | x | - | x | - | - | bycopy|
  1261. // | scl | x | x | - | - | - | null |
  1262. // | scl | | - | - | - | x | byref |
  1263. // | scl | x | - | - | - | x | byref |
  1264. //
  1265. // | agg | n.a. | | | - | | byref |
  1266. // | agg | n.a. | - | x | - | - | byref |
  1267. // | agg | n.a. | x | - | - | - | null |
  1268. // | agg | n.a. | - | - | - | x | byref |
  1269. // | agg | n.a. | - | - | - | x[] | byref |
  1270. //
  1271. // | ptr | n.a. | | | - | | bycopy|
  1272. // | ptr | n.a. | - | x | - | - | bycopy|
  1273. // | ptr | n.a. | x | - | - | - | null |
  1274. // | ptr | n.a. | - | - | - | x | byref |
  1275. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1276. // | ptr | n.a. | - | - | x | | bycopy|
  1277. // | ptr | n.a. | - | - | x | x | bycopy|
  1278. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1279. // =========================================================================
  1280. // Legend:
  1281. // scl - scalar
  1282. // ptr - pointer
  1283. // agg - aggregate
  1284. // x - applies
  1285. // - - invalid in this combination
  1286. // [] - mapped with an array section
  1287. // byref - should be mapped by reference
  1288. // byval - should be mapped by value
  1289. // null - initialize a local variable to null on the device
  1290. //
  1291. // Observations:
  1292. // - All scalar declarations that show up in a map clause have to be passed
  1293. // by reference, because they may have been mapped in the enclosing data
  1294. // environment.
  1295. // - If the scalar value does not fit the size of uintptr, it has to be
  1296. // passed by reference, regardless the result in the table above.
  1297. // - For pointers mapped by value that have either an implicit map or an
  1298. // array section, the runtime library may pass the NULL value to the
  1299. // device instead of the value passed to it by the compiler.
  1300. if (Ty->isReferenceType())
  1301. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1302. // Locate map clauses and see if the variable being captured is referred to
  1303. // in any of those clauses. Here we only care about variables, not fields,
  1304. // because fields are part of aggregates.
  1305. bool IsVariableUsedInMapClause = false;
  1306. bool IsVariableAssociatedWithSection = false;
  1307. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1308. D, Level,
  1309. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1310. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1311. MapExprComponents,
  1312. OpenMPClauseKind WhereFoundClauseKind) {
  1313. // Only the map clause information influences how a variable is
  1314. // captured. E.g. is_device_ptr does not require changing the default
  1315. // behavior.
  1316. if (WhereFoundClauseKind != OMPC_map)
  1317. return false;
  1318. auto EI = MapExprComponents.rbegin();
  1319. auto EE = MapExprComponents.rend();
  1320. assert(EI != EE && "Invalid map expression!");
  1321. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1322. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1323. ++EI;
  1324. if (EI == EE)
  1325. return false;
  1326. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1327. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1328. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1329. IsVariableAssociatedWithSection = true;
  1330. // There is nothing more we need to know about this variable.
  1331. return true;
  1332. }
  1333. // Keep looking for more map info.
  1334. return false;
  1335. });
  1336. if (IsVariableUsedInMapClause) {
  1337. // If variable is identified in a map clause it is always captured by
  1338. // reference except if it is a pointer that is dereferenced somehow.
  1339. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1340. } else {
  1341. // By default, all the data that has a scalar type is mapped by copy
  1342. // (except for reduction variables).
  1343. IsByRef =
  1344. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1345. !Ty->isAnyPointerType()) ||
  1346. !Ty->isScalarType() ||
  1347. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1348. DSAStack->hasExplicitDSA(
  1349. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1350. }
  1351. }
  1352. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1353. IsByRef =
  1354. ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1355. !Ty->isAnyPointerType()) ||
  1356. !DSAStack->hasExplicitDSA(
  1357. D,
  1358. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1359. Level, /*NotLastprivate=*/true)) &&
  1360. // If the variable is artificial and must be captured by value - try to
  1361. // capture by value.
  1362. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1363. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1364. }
  1365. // When passing data by copy, we need to make sure it fits the uintptr size
  1366. // and alignment, because the runtime library only deals with uintptr types.
  1367. // If it does not fit the uintptr size, we need to pass the data by reference
  1368. // instead.
  1369. if (!IsByRef &&
  1370. (Ctx.getTypeSizeInChars(Ty) >
  1371. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1372. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1373. IsByRef = true;
  1374. }
  1375. return IsByRef;
  1376. }
  1377. unsigned Sema::getOpenMPNestingLevel() const {
  1378. assert(getLangOpts().OpenMP);
  1379. return DSAStack->getNestingLevel();
  1380. }
  1381. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1382. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1383. !DSAStack->isClauseParsingMode()) ||
  1384. DSAStack->hasDirective(
  1385. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1386. SourceLocation) -> bool {
  1387. return isOpenMPTargetExecutionDirective(K);
  1388. },
  1389. false);
  1390. }
  1391. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
  1392. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1393. D = getCanonicalDecl(D);
  1394. // If we are attempting to capture a global variable in a directive with
  1395. // 'target' we return true so that this global is also mapped to the device.
  1396. //
  1397. auto *VD = dyn_cast<VarDecl>(D);
  1398. if (VD && !VD->hasLocalStorage()) {
  1399. if (isInOpenMPDeclareTargetContext() &&
  1400. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1401. // Try to mark variable as declare target if it is used in capturing
  1402. // regions.
  1403. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1404. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1405. return nullptr;
  1406. } else if (isInOpenMPTargetExecutionDirective()) {
  1407. // If the declaration is enclosed in a 'declare target' directive,
  1408. // then it should not be captured.
  1409. //
  1410. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1411. return nullptr;
  1412. return VD;
  1413. }
  1414. }
  1415. // Capture variables captured by reference in lambdas for target-based
  1416. // directives.
  1417. if (VD && !DSAStack->isClauseParsingMode()) {
  1418. if (const auto *RD = VD->getType()
  1419. .getCanonicalType()
  1420. .getNonReferenceType()
  1421. ->getAsCXXRecordDecl()) {
  1422. bool SavedForceCaptureByReferenceInTargetExecutable =
  1423. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  1424. DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
  1425. if (RD->isLambda()) {
  1426. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  1427. FieldDecl *ThisCapture;
  1428. RD->getCaptureFields(Captures, ThisCapture);
  1429. for (const LambdaCapture &LC : RD->captures()) {
  1430. if (LC.getCaptureKind() == LCK_ByRef) {
  1431. VarDecl *VD = LC.getCapturedVar();
  1432. DeclContext *VDC = VD->getDeclContext();
  1433. if (!VDC->Encloses(CurContext))
  1434. continue;
  1435. DSAStackTy::DSAVarData DVarPrivate =
  1436. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1437. // Do not capture already captured variables.
  1438. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  1439. DVarPrivate.CKind == OMPC_unknown &&
  1440. !DSAStack->checkMappableExprComponentListsForDecl(
  1441. D, /*CurrentRegionOnly=*/true,
  1442. [](OMPClauseMappableExprCommon::
  1443. MappableExprComponentListRef,
  1444. OpenMPClauseKind) { return true; }))
  1445. MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
  1446. } else if (LC.getCaptureKind() == LCK_This) {
  1447. QualType ThisTy = getCurrentThisType();
  1448. if (!ThisTy.isNull() &&
  1449. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  1450. CheckCXXThisCapture(LC.getLocation());
  1451. }
  1452. }
  1453. }
  1454. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  1455. SavedForceCaptureByReferenceInTargetExecutable);
  1456. }
  1457. }
  1458. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1459. (!DSAStack->isClauseParsingMode() ||
  1460. DSAStack->getParentDirective() != OMPD_unknown)) {
  1461. auto &&Info = DSAStack->isLoopControlVariable(D);
  1462. if (Info.first ||
  1463. (VD && VD->hasLocalStorage() &&
  1464. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1465. (VD && DSAStack->isForceVarCapturing()))
  1466. return VD ? VD : Info.second;
  1467. DSAStackTy::DSAVarData DVarPrivate =
  1468. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1469. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1470. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1471. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1472. [](OpenMPDirectiveKind) { return true; },
  1473. DSAStack->isClauseParsingMode());
  1474. if (DVarPrivate.CKind != OMPC_unknown)
  1475. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1476. }
  1477. return nullptr;
  1478. }
  1479. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1480. unsigned Level) const {
  1481. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1482. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1483. FunctionScopesIndex -= Regions.size();
  1484. }
  1485. void Sema::startOpenMPLoop() {
  1486. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1487. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1488. DSAStack->loopInit();
  1489. }
  1490. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1491. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1492. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1493. if (DSAStack->getAssociatedLoops() > 0 &&
  1494. !DSAStack->isLoopStarted()) {
  1495. DSAStack->resetPossibleLoopCounter(D);
  1496. DSAStack->loopStart();
  1497. return true;
  1498. }
  1499. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1500. DSAStack->isLoopControlVariable(D).first) &&
  1501. !DSAStack->hasExplicitDSA(
  1502. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1503. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1504. return true;
  1505. }
  1506. return DSAStack->hasExplicitDSA(
  1507. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1508. (DSAStack->isClauseParsingMode() &&
  1509. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1510. // Consider taskgroup reduction descriptor variable a private to avoid
  1511. // possible capture in the region.
  1512. (DSAStack->hasExplicitDirective(
  1513. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1514. Level) &&
  1515. DSAStack->isTaskgroupReductionRef(D, Level));
  1516. }
  1517. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1518. unsigned Level) {
  1519. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1520. D = getCanonicalDecl(D);
  1521. OpenMPClauseKind OMPC = OMPC_unknown;
  1522. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1523. const unsigned NewLevel = I - 1;
  1524. if (DSAStack->hasExplicitDSA(D,
  1525. [&OMPC](const OpenMPClauseKind K) {
  1526. if (isOpenMPPrivate(K)) {
  1527. OMPC = K;
  1528. return true;
  1529. }
  1530. return false;
  1531. },
  1532. NewLevel))
  1533. break;
  1534. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1535. D, NewLevel,
  1536. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1537. OpenMPClauseKind) { return true; })) {
  1538. OMPC = OMPC_map;
  1539. break;
  1540. }
  1541. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1542. NewLevel)) {
  1543. OMPC = OMPC_map;
  1544. if (D->getType()->isScalarType() &&
  1545. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1546. DefaultMapAttributes::DMA_tofrom_scalar)
  1547. OMPC = OMPC_firstprivate;
  1548. break;
  1549. }
  1550. }
  1551. if (OMPC != OMPC_unknown)
  1552. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1553. }
  1554. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1555. unsigned Level) const {
  1556. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1557. // Return true if the current level is no longer enclosed in a target region.
  1558. const auto *VD = dyn_cast<VarDecl>(D);
  1559. return VD && !VD->hasLocalStorage() &&
  1560. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1561. Level);
  1562. }
  1563. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1564. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1565. const DeclarationNameInfo &DirName,
  1566. Scope *CurScope, SourceLocation Loc) {
  1567. DSAStack->push(DKind, DirName, CurScope, Loc);
  1568. PushExpressionEvaluationContext(
  1569. ExpressionEvaluationContext::PotentiallyEvaluated);
  1570. }
  1571. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1572. DSAStack->setClauseParsingMode(K);
  1573. }
  1574. void Sema::EndOpenMPClause() {
  1575. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1576. }
  1577. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1578. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1579. // A variable of class type (or array thereof) that appears in a lastprivate
  1580. // clause requires an accessible, unambiguous default constructor for the
  1581. // class type, unless the list item is also specified in a firstprivate
  1582. // clause.
  1583. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1584. for (OMPClause *C : D->clauses()) {
  1585. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1586. SmallVector<Expr *, 8> PrivateCopies;
  1587. for (Expr *DE : Clause->varlists()) {
  1588. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1589. PrivateCopies.push_back(nullptr);
  1590. continue;
  1591. }
  1592. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1593. auto *VD = cast<VarDecl>(DRE->getDecl());
  1594. QualType Type = VD->getType().getNonReferenceType();
  1595. const DSAStackTy::DSAVarData DVar =
  1596. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1597. if (DVar.CKind == OMPC_lastprivate) {
  1598. // Generate helper private variable and initialize it with the
  1599. // default value. The address of the original variable is replaced
  1600. // by the address of the new private variable in CodeGen. This new
  1601. // variable is not added to IdResolver, so the code in the OpenMP
  1602. // region uses original variable for proper diagnostics.
  1603. VarDecl *VDPrivate = buildVarDecl(
  1604. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1605. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  1606. ActOnUninitializedDecl(VDPrivate);
  1607. if (VDPrivate->isInvalidDecl())
  1608. continue;
  1609. PrivateCopies.push_back(buildDeclRefExpr(
  1610. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1611. } else {
  1612. // The variable is also a firstprivate, so initialization sequence
  1613. // for private copy is generated already.
  1614. PrivateCopies.push_back(nullptr);
  1615. }
  1616. }
  1617. // Set initializers to private copies if no errors were found.
  1618. if (PrivateCopies.size() == Clause->varlist_size())
  1619. Clause->setPrivateCopies(PrivateCopies);
  1620. }
  1621. }
  1622. }
  1623. DSAStack->pop();
  1624. DiscardCleanupsInEvaluationContext();
  1625. PopExpressionEvaluationContext();
  1626. }
  1627. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1628. Expr *NumIterations, Sema &SemaRef,
  1629. Scope *S, DSAStackTy *Stack);
  1630. namespace {
  1631. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  1632. private:
  1633. Sema &SemaRef;
  1634. public:
  1635. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1636. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1637. NamedDecl *ND = Candidate.getCorrectionDecl();
  1638. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1639. return VD->hasGlobalStorage() &&
  1640. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1641. SemaRef.getCurScope());
  1642. }
  1643. return false;
  1644. }
  1645. };
  1646. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  1647. private:
  1648. Sema &SemaRef;
  1649. public:
  1650. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1651. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1652. NamedDecl *ND = Candidate.getCorrectionDecl();
  1653. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1654. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1655. SemaRef.getCurScope());
  1656. }
  1657. return false;
  1658. }
  1659. };
  1660. } // namespace
  1661. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1662. CXXScopeSpec &ScopeSpec,
  1663. const DeclarationNameInfo &Id) {
  1664. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1665. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1666. if (Lookup.isAmbiguous())
  1667. return ExprError();
  1668. VarDecl *VD;
  1669. if (!Lookup.isSingleResult()) {
  1670. if (TypoCorrection Corrected = CorrectTypo(
  1671. Id, LookupOrdinaryName, CurScope, nullptr,
  1672. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1673. diagnoseTypo(Corrected,
  1674. PDiag(Lookup.empty()
  1675. ? diag::err_undeclared_var_use_suggest
  1676. : diag::err_omp_expected_var_arg_suggest)
  1677. << Id.getName());
  1678. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1679. } else {
  1680. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1681. : diag::err_omp_expected_var_arg)
  1682. << Id.getName();
  1683. return ExprError();
  1684. }
  1685. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1686. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1687. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1688. return ExprError();
  1689. }
  1690. Lookup.suppressDiagnostics();
  1691. // OpenMP [2.9.2, Syntax, C/C++]
  1692. // Variables must be file-scope, namespace-scope, or static block-scope.
  1693. if (!VD->hasGlobalStorage()) {
  1694. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1695. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1696. bool IsDecl =
  1697. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1698. Diag(VD->getLocation(),
  1699. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1700. << VD;
  1701. return ExprError();
  1702. }
  1703. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1704. NamedDecl *ND = CanonicalVD;
  1705. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1706. // A threadprivate directive for file-scope variables must appear outside
  1707. // any definition or declaration.
  1708. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1709. !getCurLexicalContext()->isTranslationUnit()) {
  1710. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1711. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1712. bool IsDecl =
  1713. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1714. Diag(VD->getLocation(),
  1715. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1716. << VD;
  1717. return ExprError();
  1718. }
  1719. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1720. // A threadprivate directive for static class member variables must appear
  1721. // in the class definition, in the same scope in which the member
  1722. // variables are declared.
  1723. if (CanonicalVD->isStaticDataMember() &&
  1724. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1725. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1726. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1727. bool IsDecl =
  1728. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1729. Diag(VD->getLocation(),
  1730. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1731. << VD;
  1732. return ExprError();
  1733. }
  1734. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1735. // A threadprivate directive for namespace-scope variables must appear
  1736. // outside any definition or declaration other than the namespace
  1737. // definition itself.
  1738. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1739. (!getCurLexicalContext()->isFileContext() ||
  1740. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1741. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1742. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1743. bool IsDecl =
  1744. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1745. Diag(VD->getLocation(),
  1746. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1747. << VD;
  1748. return ExprError();
  1749. }
  1750. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1751. // A threadprivate directive for static block-scope variables must appear
  1752. // in the scope of the variable and not in a nested scope.
  1753. if (CanonicalVD->isStaticLocal() && CurScope &&
  1754. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1755. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1756. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1757. bool IsDecl =
  1758. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1759. Diag(VD->getLocation(),
  1760. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1761. << VD;
  1762. return ExprError();
  1763. }
  1764. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1765. // A threadprivate directive must lexically precede all references to any
  1766. // of the variables in its list.
  1767. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1768. Diag(Id.getLoc(), diag::err_omp_var_used)
  1769. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1770. return ExprError();
  1771. }
  1772. QualType ExprType = VD->getType().getNonReferenceType();
  1773. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1774. SourceLocation(), VD,
  1775. /*RefersToEnclosingVariableOrCapture=*/false,
  1776. Id.getLoc(), ExprType, VK_LValue);
  1777. }
  1778. Sema::DeclGroupPtrTy
  1779. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1780. ArrayRef<Expr *> VarList) {
  1781. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1782. CurContext->addDecl(D);
  1783. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1784. }
  1785. return nullptr;
  1786. }
  1787. namespace {
  1788. class LocalVarRefChecker final
  1789. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1790. Sema &SemaRef;
  1791. public:
  1792. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1793. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1794. if (VD->hasLocalStorage()) {
  1795. SemaRef.Diag(E->getBeginLoc(),
  1796. diag::err_omp_local_var_in_threadprivate_init)
  1797. << E->getSourceRange();
  1798. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1799. << VD << VD->getSourceRange();
  1800. return true;
  1801. }
  1802. }
  1803. return false;
  1804. }
  1805. bool VisitStmt(const Stmt *S) {
  1806. for (const Stmt *Child : S->children()) {
  1807. if (Child && Visit(Child))
  1808. return true;
  1809. }
  1810. return false;
  1811. }
  1812. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1813. };
  1814. } // namespace
  1815. OMPThreadPrivateDecl *
  1816. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1817. SmallVector<Expr *, 8> Vars;
  1818. for (Expr *RefExpr : VarList) {
  1819. auto *DE = cast<DeclRefExpr>(RefExpr);
  1820. auto *VD = cast<VarDecl>(DE->getDecl());
  1821. SourceLocation ILoc = DE->getExprLoc();
  1822. // Mark variable as used.
  1823. VD->setReferenced();
  1824. VD->markUsed(Context);
  1825. QualType QType = VD->getType();
  1826. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1827. // It will be analyzed later.
  1828. Vars.push_back(DE);
  1829. continue;
  1830. }
  1831. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1832. // A threadprivate variable must not have an incomplete type.
  1833. if (RequireCompleteType(ILoc, VD->getType(),
  1834. diag::err_omp_threadprivate_incomplete_type)) {
  1835. continue;
  1836. }
  1837. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1838. // A threadprivate variable must not have a reference type.
  1839. if (VD->getType()->isReferenceType()) {
  1840. Diag(ILoc, diag::err_omp_ref_type_arg)
  1841. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1842. bool IsDecl =
  1843. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1844. Diag(VD->getLocation(),
  1845. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1846. << VD;
  1847. continue;
  1848. }
  1849. // Check if this is a TLS variable. If TLS is not being supported, produce
  1850. // the corresponding diagnostic.
  1851. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1852. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1853. getLangOpts().OpenMPUseTLS &&
  1854. getASTContext().getTargetInfo().isTLSSupported())) ||
  1855. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1856. !VD->isLocalVarDecl())) {
  1857. Diag(ILoc, diag::err_omp_var_thread_local)
  1858. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1859. bool IsDecl =
  1860. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1861. Diag(VD->getLocation(),
  1862. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1863. << VD;
  1864. continue;
  1865. }
  1866. // Check if initial value of threadprivate variable reference variable with
  1867. // local storage (it is not supported by runtime).
  1868. if (const Expr *Init = VD->getAnyInitializer()) {
  1869. LocalVarRefChecker Checker(*this);
  1870. if (Checker.Visit(Init))
  1871. continue;
  1872. }
  1873. Vars.push_back(RefExpr);
  1874. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1875. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1876. Context, SourceRange(Loc, Loc)));
  1877. if (ASTMutationListener *ML = Context.getASTMutationListener())
  1878. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1879. }
  1880. OMPThreadPrivateDecl *D = nullptr;
  1881. if (!Vars.empty()) {
  1882. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1883. Vars);
  1884. D->setAccess(AS_public);
  1885. }
  1886. return D;
  1887. }
  1888. Sema::DeclGroupPtrTy
  1889. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  1890. ArrayRef<OMPClause *> ClauseList) {
  1891. OMPRequiresDecl *D = nullptr;
  1892. if (!CurContext->isFileContext()) {
  1893. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  1894. } else {
  1895. D = CheckOMPRequiresDecl(Loc, ClauseList);
  1896. if (D) {
  1897. CurContext->addDecl(D);
  1898. DSAStack->addRequiresDecl(D);
  1899. }
  1900. }
  1901. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1902. }
  1903. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  1904. ArrayRef<OMPClause *> ClauseList) {
  1905. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  1906. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  1907. ClauseList);
  1908. return nullptr;
  1909. }
  1910. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  1911. const ValueDecl *D,
  1912. const DSAStackTy::DSAVarData &DVar,
  1913. bool IsLoopIterVar = false) {
  1914. if (DVar.RefExpr) {
  1915. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1916. << getOpenMPClauseName(DVar.CKind);
  1917. return;
  1918. }
  1919. enum {
  1920. PDSA_StaticMemberShared,
  1921. PDSA_StaticLocalVarShared,
  1922. PDSA_LoopIterVarPrivate,
  1923. PDSA_LoopIterVarLinear,
  1924. PDSA_LoopIterVarLastprivate,
  1925. PDSA_ConstVarShared,
  1926. PDSA_GlobalVarShared,
  1927. PDSA_TaskVarFirstprivate,
  1928. PDSA_LocalVarPrivate,
  1929. PDSA_Implicit
  1930. } Reason = PDSA_Implicit;
  1931. bool ReportHint = false;
  1932. auto ReportLoc = D->getLocation();
  1933. auto *VD = dyn_cast<VarDecl>(D);
  1934. if (IsLoopIterVar) {
  1935. if (DVar.CKind == OMPC_private)
  1936. Reason = PDSA_LoopIterVarPrivate;
  1937. else if (DVar.CKind == OMPC_lastprivate)
  1938. Reason = PDSA_LoopIterVarLastprivate;
  1939. else
  1940. Reason = PDSA_LoopIterVarLinear;
  1941. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1942. DVar.CKind == OMPC_firstprivate) {
  1943. Reason = PDSA_TaskVarFirstprivate;
  1944. ReportLoc = DVar.ImplicitDSALoc;
  1945. } else if (VD && VD->isStaticLocal())
  1946. Reason = PDSA_StaticLocalVarShared;
  1947. else if (VD && VD->isStaticDataMember())
  1948. Reason = PDSA_StaticMemberShared;
  1949. else if (VD && VD->isFileVarDecl())
  1950. Reason = PDSA_GlobalVarShared;
  1951. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1952. Reason = PDSA_ConstVarShared;
  1953. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1954. ReportHint = true;
  1955. Reason = PDSA_LocalVarPrivate;
  1956. }
  1957. if (Reason != PDSA_Implicit) {
  1958. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1959. << Reason << ReportHint
  1960. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1961. } else if (DVar.ImplicitDSALoc.isValid()) {
  1962. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1963. << getOpenMPClauseName(DVar.CKind);
  1964. }
  1965. }
  1966. namespace {
  1967. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  1968. DSAStackTy *Stack;
  1969. Sema &SemaRef;
  1970. bool ErrorFound = false;
  1971. CapturedStmt *CS = nullptr;
  1972. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  1973. llvm::SmallVector<Expr *, 4> ImplicitMap;
  1974. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  1975. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  1976. void VisitSubCaptures(OMPExecutableDirective *S) {
  1977. // Check implicitly captured variables.
  1978. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  1979. return;
  1980. for (const CapturedStmt::Capture &Cap :
  1981. S->getInnermostCapturedStmt()->captures()) {
  1982. if (!Cap.capturesVariable())
  1983. continue;
  1984. VarDecl *VD = Cap.getCapturedVar();
  1985. // Do not try to map the variable if it or its sub-component was mapped
  1986. // already.
  1987. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  1988. Stack->checkMappableExprComponentListsForDecl(
  1989. VD, /*CurrentRegionOnly=*/true,
  1990. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1991. OpenMPClauseKind) { return true; }))
  1992. continue;
  1993. DeclRefExpr *DRE = buildDeclRefExpr(
  1994. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  1995. Cap.getLocation(), /*RefersToCapture=*/true);
  1996. Visit(DRE);
  1997. }
  1998. }
  1999. public:
  2000. void VisitDeclRefExpr(DeclRefExpr *E) {
  2001. if (E->isTypeDependent() || E->isValueDependent() ||
  2002. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2003. return;
  2004. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2005. VD = VD->getCanonicalDecl();
  2006. // Skip internally declared variables.
  2007. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  2008. return;
  2009. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2010. // Check if the variable has explicit DSA set and stop analysis if it so.
  2011. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2012. return;
  2013. // Skip internally declared static variables.
  2014. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2015. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2016. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
  2017. (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2018. return;
  2019. SourceLocation ELoc = E->getExprLoc();
  2020. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2021. // The default(none) clause requires that each variable that is referenced
  2022. // in the construct, and does not have a predetermined data-sharing
  2023. // attribute, must have its data-sharing attribute explicitly determined
  2024. // by being listed in a data-sharing attribute clause.
  2025. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2026. isParallelOrTaskRegion(DKind) &&
  2027. VarsWithInheritedDSA.count(VD) == 0) {
  2028. VarsWithInheritedDSA[VD] = E;
  2029. return;
  2030. }
  2031. if (isOpenMPTargetExecutionDirective(DKind) &&
  2032. !Stack->isLoopControlVariable(VD).first) {
  2033. if (!Stack->checkMappableExprComponentListsForDecl(
  2034. VD, /*CurrentRegionOnly=*/true,
  2035. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2036. StackComponents,
  2037. OpenMPClauseKind) {
  2038. // Variable is used if it has been marked as an array, array
  2039. // section or the variable iself.
  2040. return StackComponents.size() == 1 ||
  2041. std::all_of(
  2042. std::next(StackComponents.rbegin()),
  2043. StackComponents.rend(),
  2044. [](const OMPClauseMappableExprCommon::
  2045. MappableComponent &MC) {
  2046. return MC.getAssociatedDeclaration() ==
  2047. nullptr &&
  2048. (isa<OMPArraySectionExpr>(
  2049. MC.getAssociatedExpression()) ||
  2050. isa<ArraySubscriptExpr>(
  2051. MC.getAssociatedExpression()));
  2052. });
  2053. })) {
  2054. bool IsFirstprivate = false;
  2055. // By default lambdas are captured as firstprivates.
  2056. if (const auto *RD =
  2057. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2058. IsFirstprivate = RD->isLambda();
  2059. IsFirstprivate =
  2060. IsFirstprivate ||
  2061. (VD->getType().getNonReferenceType()->isScalarType() &&
  2062. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2063. if (IsFirstprivate)
  2064. ImplicitFirstprivate.emplace_back(E);
  2065. else
  2066. ImplicitMap.emplace_back(E);
  2067. return;
  2068. }
  2069. }
  2070. // OpenMP [2.9.3.6, Restrictions, p.2]
  2071. // A list item that appears in a reduction clause of the innermost
  2072. // enclosing worksharing or parallel construct may not be accessed in an
  2073. // explicit task.
  2074. DVar = Stack->hasInnermostDSA(
  2075. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2076. [](OpenMPDirectiveKind K) {
  2077. return isOpenMPParallelDirective(K) ||
  2078. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2079. },
  2080. /*FromParent=*/true);
  2081. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2082. ErrorFound = true;
  2083. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2084. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2085. return;
  2086. }
  2087. // Define implicit data-sharing attributes for task.
  2088. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2089. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2090. !Stack->isLoopControlVariable(VD).first)
  2091. ImplicitFirstprivate.push_back(E);
  2092. }
  2093. }
  2094. void VisitMemberExpr(MemberExpr *E) {
  2095. if (E->isTypeDependent() || E->isValueDependent() ||
  2096. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2097. return;
  2098. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2099. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2100. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2101. if (!FD)
  2102. return;
  2103. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2104. // Check if the variable has explicit DSA set and stop analysis if it
  2105. // so.
  2106. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2107. return;
  2108. if (isOpenMPTargetExecutionDirective(DKind) &&
  2109. !Stack->isLoopControlVariable(FD).first &&
  2110. !Stack->checkMappableExprComponentListsForDecl(
  2111. FD, /*CurrentRegionOnly=*/true,
  2112. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2113. StackComponents,
  2114. OpenMPClauseKind) {
  2115. return isa<CXXThisExpr>(
  2116. cast<MemberExpr>(
  2117. StackComponents.back().getAssociatedExpression())
  2118. ->getBase()
  2119. ->IgnoreParens());
  2120. })) {
  2121. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2122. // A bit-field cannot appear in a map clause.
  2123. //
  2124. if (FD->isBitField())
  2125. return;
  2126. ImplicitMap.emplace_back(E);
  2127. return;
  2128. }
  2129. SourceLocation ELoc = E->getExprLoc();
  2130. // OpenMP [2.9.3.6, Restrictions, p.2]
  2131. // A list item that appears in a reduction clause of the innermost
  2132. // enclosing worksharing or parallel construct may not be accessed in
  2133. // an explicit task.
  2134. DVar = Stack->hasInnermostDSA(
  2135. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2136. [](OpenMPDirectiveKind K) {
  2137. return isOpenMPParallelDirective(K) ||
  2138. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2139. },
  2140. /*FromParent=*/true);
  2141. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2142. ErrorFound = true;
  2143. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2144. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2145. return;
  2146. }
  2147. // Define implicit data-sharing attributes for task.
  2148. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2149. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2150. !Stack->isLoopControlVariable(FD).first) {
  2151. // Check if there is a captured expression for the current field in the
  2152. // region. Do not mark it as firstprivate unless there is no captured
  2153. // expression.
  2154. // TODO: try to make it firstprivate.
  2155. if (DVar.CKind != OMPC_unknown)
  2156. ImplicitFirstprivate.push_back(E);
  2157. }
  2158. return;
  2159. }
  2160. if (isOpenMPTargetExecutionDirective(DKind)) {
  2161. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2162. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2163. /*NoDiagnose=*/true))
  2164. return;
  2165. const auto *VD = cast<ValueDecl>(
  2166. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2167. if (!Stack->checkMappableExprComponentListsForDecl(
  2168. VD, /*CurrentRegionOnly=*/true,
  2169. [&CurComponents](
  2170. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2171. StackComponents,
  2172. OpenMPClauseKind) {
  2173. auto CCI = CurComponents.rbegin();
  2174. auto CCE = CurComponents.rend();
  2175. for (const auto &SC : llvm::reverse(StackComponents)) {
  2176. // Do both expressions have the same kind?
  2177. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2178. SC.getAssociatedExpression()->getStmtClass())
  2179. if (!(isa<OMPArraySectionExpr>(
  2180. SC.getAssociatedExpression()) &&
  2181. isa<ArraySubscriptExpr>(
  2182. CCI->getAssociatedExpression())))
  2183. return false;
  2184. const Decl *CCD = CCI->getAssociatedDeclaration();
  2185. const Decl *SCD = SC.getAssociatedDeclaration();
  2186. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2187. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2188. if (SCD != CCD)
  2189. return false;
  2190. std::advance(CCI, 1);
  2191. if (CCI == CCE)
  2192. break;
  2193. }
  2194. return true;
  2195. })) {
  2196. Visit(E->getBase());
  2197. }
  2198. } else {
  2199. Visit(E->getBase());
  2200. }
  2201. }
  2202. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2203. for (OMPClause *C : S->clauses()) {
  2204. // Skip analysis of arguments of implicitly defined firstprivate clause
  2205. // for task|target directives.
  2206. // Skip analysis of arguments of implicitly defined map clause for target
  2207. // directives.
  2208. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2209. C->isImplicit())) {
  2210. for (Stmt *CC : C->children()) {
  2211. if (CC)
  2212. Visit(CC);
  2213. }
  2214. }
  2215. }
  2216. // Check implicitly captured variables.
  2217. VisitSubCaptures(S);
  2218. }
  2219. void VisitStmt(Stmt *S) {
  2220. for (Stmt *C : S->children()) {
  2221. if (C) {
  2222. if (auto *OED = dyn_cast<OMPExecutableDirective>(C)) {
  2223. // Check implicitly captured variables in the task-based directives to
  2224. // check if they must be firstprivatized.
  2225. VisitSubCaptures(OED);
  2226. } else {
  2227. Visit(C);
  2228. }
  2229. }
  2230. }
  2231. }
  2232. bool isErrorFound() const { return ErrorFound; }
  2233. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2234. return ImplicitFirstprivate;
  2235. }
  2236. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2237. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2238. return VarsWithInheritedDSA;
  2239. }
  2240. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2241. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  2242. };
  2243. } // namespace
  2244. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2245. switch (DKind) {
  2246. case OMPD_parallel:
  2247. case OMPD_parallel_for:
  2248. case OMPD_parallel_for_simd:
  2249. case OMPD_parallel_sections:
  2250. case OMPD_teams:
  2251. case OMPD_teams_distribute:
  2252. case OMPD_teams_distribute_simd: {
  2253. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2254. QualType KmpInt32PtrTy =
  2255. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2256. Sema::CapturedParamNameType Params[] = {
  2257. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2258. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2259. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2260. };
  2261. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2262. Params);
  2263. break;
  2264. }
  2265. case OMPD_target_teams:
  2266. case OMPD_target_parallel:
  2267. case OMPD_target_parallel_for:
  2268. case OMPD_target_parallel_for_simd:
  2269. case OMPD_target_teams_distribute:
  2270. case OMPD_target_teams_distribute_simd: {
  2271. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2272. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2273. QualType KmpInt32PtrTy =
  2274. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2275. QualType Args[] = {VoidPtrTy};
  2276. FunctionProtoType::ExtProtoInfo EPI;
  2277. EPI.Variadic = true;
  2278. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2279. Sema::CapturedParamNameType Params[] = {
  2280. std::make_pair(".global_tid.", KmpInt32Ty),
  2281. std::make_pair(".part_id.", KmpInt32PtrTy),
  2282. std::make_pair(".privates.", VoidPtrTy),
  2283. std::make_pair(
  2284. ".copy_fn.",
  2285. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2286. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2287. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2288. };
  2289. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2290. Params);
  2291. // Mark this captured region as inlined, because we don't use outlined
  2292. // function directly.
  2293. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2294. AlwaysInlineAttr::CreateImplicit(
  2295. Context, AlwaysInlineAttr::Keyword_forceinline));
  2296. Sema::CapturedParamNameType ParamsTarget[] = {
  2297. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2298. };
  2299. // Start a captured region for 'target' with no implicit parameters.
  2300. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2301. ParamsTarget);
  2302. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2303. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2304. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2305. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2306. };
  2307. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2308. // the same implicit parameters.
  2309. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2310. ParamsTeamsOrParallel);
  2311. break;
  2312. }
  2313. case OMPD_target:
  2314. case OMPD_target_simd: {
  2315. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2316. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2317. QualType KmpInt32PtrTy =
  2318. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2319. QualType Args[] = {VoidPtrTy};
  2320. FunctionProtoType::ExtProtoInfo EPI;
  2321. EPI.Variadic = true;
  2322. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2323. Sema::CapturedParamNameType Params[] = {
  2324. std::make_pair(".global_tid.", KmpInt32Ty),
  2325. std::make_pair(".part_id.", KmpInt32PtrTy),
  2326. std::make_pair(".privates.", VoidPtrTy),
  2327. std::make_pair(
  2328. ".copy_fn.",
  2329. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2330. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2331. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2332. };
  2333. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2334. Params);
  2335. // Mark this captured region as inlined, because we don't use outlined
  2336. // function directly.
  2337. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2338. AlwaysInlineAttr::CreateImplicit(
  2339. Context, AlwaysInlineAttr::Keyword_forceinline));
  2340. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2341. std::make_pair(StringRef(), QualType()));
  2342. break;
  2343. }
  2344. case OMPD_simd:
  2345. case OMPD_for:
  2346. case OMPD_for_simd:
  2347. case OMPD_sections:
  2348. case OMPD_section:
  2349. case OMPD_single:
  2350. case OMPD_master:
  2351. case OMPD_critical:
  2352. case OMPD_taskgroup:
  2353. case OMPD_distribute:
  2354. case OMPD_distribute_simd:
  2355. case OMPD_ordered:
  2356. case OMPD_atomic:
  2357. case OMPD_target_data: {
  2358. Sema::CapturedParamNameType Params[] = {
  2359. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2360. };
  2361. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2362. Params);
  2363. break;
  2364. }
  2365. case OMPD_task: {
  2366. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2367. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2368. QualType KmpInt32PtrTy =
  2369. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2370. QualType Args[] = {VoidPtrTy};
  2371. FunctionProtoType::ExtProtoInfo EPI;
  2372. EPI.Variadic = true;
  2373. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2374. Sema::CapturedParamNameType Params[] = {
  2375. std::make_pair(".global_tid.", KmpInt32Ty),
  2376. std::make_pair(".part_id.", KmpInt32PtrTy),
  2377. std::make_pair(".privates.", VoidPtrTy),
  2378. std::make_pair(
  2379. ".copy_fn.",
  2380. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2381. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2382. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2383. };
  2384. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2385. Params);
  2386. // Mark this captured region as inlined, because we don't use outlined
  2387. // function directly.
  2388. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2389. AlwaysInlineAttr::CreateImplicit(
  2390. Context, AlwaysInlineAttr::Keyword_forceinline));
  2391. break;
  2392. }
  2393. case OMPD_taskloop:
  2394. case OMPD_taskloop_simd: {
  2395. QualType KmpInt32Ty =
  2396. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  2397. .withConst();
  2398. QualType KmpUInt64Ty =
  2399. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  2400. .withConst();
  2401. QualType KmpInt64Ty =
  2402. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  2403. .withConst();
  2404. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2405. QualType KmpInt32PtrTy =
  2406. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2407. QualType Args[] = {VoidPtrTy};
  2408. FunctionProtoType::ExtProtoInfo EPI;
  2409. EPI.Variadic = true;
  2410. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2411. Sema::CapturedParamNameType Params[] = {
  2412. std::make_pair(".global_tid.", KmpInt32Ty),
  2413. std::make_pair(".part_id.", KmpInt32PtrTy),
  2414. std::make_pair(".privates.", VoidPtrTy),
  2415. std::make_pair(
  2416. ".copy_fn.",
  2417. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2418. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2419. std::make_pair(".lb.", KmpUInt64Ty),
  2420. std::make_pair(".ub.", KmpUInt64Ty),
  2421. std::make_pair(".st.", KmpInt64Ty),
  2422. std::make_pair(".liter.", KmpInt32Ty),
  2423. std::make_pair(".reductions.", VoidPtrTy),
  2424. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2425. };
  2426. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2427. Params);
  2428. // Mark this captured region as inlined, because we don't use outlined
  2429. // function directly.
  2430. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2431. AlwaysInlineAttr::CreateImplicit(
  2432. Context, AlwaysInlineAttr::Keyword_forceinline));
  2433. break;
  2434. }
  2435. case OMPD_distribute_parallel_for_simd:
  2436. case OMPD_distribute_parallel_for: {
  2437. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2438. QualType KmpInt32PtrTy =
  2439. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2440. Sema::CapturedParamNameType Params[] = {
  2441. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2442. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2443. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2444. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2445. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2446. };
  2447. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2448. Params);
  2449. break;
  2450. }
  2451. case OMPD_target_teams_distribute_parallel_for:
  2452. case OMPD_target_teams_distribute_parallel_for_simd: {
  2453. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2454. QualType KmpInt32PtrTy =
  2455. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2456. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2457. QualType Args[] = {VoidPtrTy};
  2458. FunctionProtoType::ExtProtoInfo EPI;
  2459. EPI.Variadic = true;
  2460. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2461. Sema::CapturedParamNameType Params[] = {
  2462. std::make_pair(".global_tid.", KmpInt32Ty),
  2463. std::make_pair(".part_id.", KmpInt32PtrTy),
  2464. std::make_pair(".privates.", VoidPtrTy),
  2465. std::make_pair(
  2466. ".copy_fn.",
  2467. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2468. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2469. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2470. };
  2471. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2472. Params);
  2473. // Mark this captured region as inlined, because we don't use outlined
  2474. // function directly.
  2475. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2476. AlwaysInlineAttr::CreateImplicit(
  2477. Context, AlwaysInlineAttr::Keyword_forceinline));
  2478. Sema::CapturedParamNameType ParamsTarget[] = {
  2479. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2480. };
  2481. // Start a captured region for 'target' with no implicit parameters.
  2482. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2483. ParamsTarget);
  2484. Sema::CapturedParamNameType ParamsTeams[] = {
  2485. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2486. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2487. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2488. };
  2489. // Start a captured region for 'target' with no implicit parameters.
  2490. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2491. ParamsTeams);
  2492. Sema::CapturedParamNameType ParamsParallel[] = {
  2493. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2494. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2495. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2496. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2497. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2498. };
  2499. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2500. // the same implicit parameters.
  2501. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2502. ParamsParallel);
  2503. break;
  2504. }
  2505. case OMPD_teams_distribute_parallel_for:
  2506. case OMPD_teams_distribute_parallel_for_simd: {
  2507. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2508. QualType KmpInt32PtrTy =
  2509. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2510. Sema::CapturedParamNameType ParamsTeams[] = {
  2511. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2512. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2513. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2514. };
  2515. // Start a captured region for 'target' with no implicit parameters.
  2516. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2517. ParamsTeams);
  2518. Sema::CapturedParamNameType ParamsParallel[] = {
  2519. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2520. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2521. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2522. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2523. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2524. };
  2525. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2526. // the same implicit parameters.
  2527. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2528. ParamsParallel);
  2529. break;
  2530. }
  2531. case OMPD_target_update:
  2532. case OMPD_target_enter_data:
  2533. case OMPD_target_exit_data: {
  2534. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2535. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2536. QualType KmpInt32PtrTy =
  2537. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2538. QualType Args[] = {VoidPtrTy};
  2539. FunctionProtoType::ExtProtoInfo EPI;
  2540. EPI.Variadic = true;
  2541. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2542. Sema::CapturedParamNameType Params[] = {
  2543. std::make_pair(".global_tid.", KmpInt32Ty),
  2544. std::make_pair(".part_id.", KmpInt32PtrTy),
  2545. std::make_pair(".privates.", VoidPtrTy),
  2546. std::make_pair(
  2547. ".copy_fn.",
  2548. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2549. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2550. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2551. };
  2552. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2553. Params);
  2554. // Mark this captured region as inlined, because we don't use outlined
  2555. // function directly.
  2556. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2557. AlwaysInlineAttr::CreateImplicit(
  2558. Context, AlwaysInlineAttr::Keyword_forceinline));
  2559. break;
  2560. }
  2561. case OMPD_threadprivate:
  2562. case OMPD_taskyield:
  2563. case OMPD_barrier:
  2564. case OMPD_taskwait:
  2565. case OMPD_cancellation_point:
  2566. case OMPD_cancel:
  2567. case OMPD_flush:
  2568. case OMPD_declare_reduction:
  2569. case OMPD_declare_simd:
  2570. case OMPD_declare_target:
  2571. case OMPD_end_declare_target:
  2572. case OMPD_requires:
  2573. llvm_unreachable("OpenMP Directive is not allowed");
  2574. case OMPD_unknown:
  2575. llvm_unreachable("Unknown OpenMP directive");
  2576. }
  2577. }
  2578. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2579. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2580. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2581. return CaptureRegions.size();
  2582. }
  2583. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2584. Expr *CaptureExpr, bool WithInit,
  2585. bool AsExpression) {
  2586. assert(CaptureExpr);
  2587. ASTContext &C = S.getASTContext();
  2588. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2589. QualType Ty = Init->getType();
  2590. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2591. if (S.getLangOpts().CPlusPlus) {
  2592. Ty = C.getLValueReferenceType(Ty);
  2593. } else {
  2594. Ty = C.getPointerType(Ty);
  2595. ExprResult Res =
  2596. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2597. if (!Res.isUsable())
  2598. return nullptr;
  2599. Init = Res.get();
  2600. }
  2601. WithInit = true;
  2602. }
  2603. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2604. CaptureExpr->getBeginLoc());
  2605. if (!WithInit)
  2606. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  2607. S.CurContext->addHiddenDecl(CED);
  2608. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2609. return CED;
  2610. }
  2611. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2612. bool WithInit) {
  2613. OMPCapturedExprDecl *CD;
  2614. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  2615. CD = cast<OMPCapturedExprDecl>(VD);
  2616. else
  2617. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2618. /*AsExpression=*/false);
  2619. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2620. CaptureExpr->getExprLoc());
  2621. }
  2622. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2623. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  2624. if (!Ref) {
  2625. OMPCapturedExprDecl *CD = buildCaptureDecl(
  2626. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  2627. /*WithInit=*/true, /*AsExpression=*/true);
  2628. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2629. CaptureExpr->getExprLoc());
  2630. }
  2631. ExprResult Res = Ref;
  2632. if (!S.getLangOpts().CPlusPlus &&
  2633. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2634. Ref->getType()->isPointerType()) {
  2635. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2636. if (!Res.isUsable())
  2637. return ExprError();
  2638. }
  2639. return S.DefaultLvalueConversion(Res.get());
  2640. }
  2641. namespace {
  2642. // OpenMP directives parsed in this section are represented as a
  2643. // CapturedStatement with an associated statement. If a syntax error
  2644. // is detected during the parsing of the associated statement, the
  2645. // compiler must abort processing and close the CapturedStatement.
  2646. //
  2647. // Combined directives such as 'target parallel' have more than one
  2648. // nested CapturedStatements. This RAII ensures that we unwind out
  2649. // of all the nested CapturedStatements when an error is found.
  2650. class CaptureRegionUnwinderRAII {
  2651. private:
  2652. Sema &S;
  2653. bool &ErrorFound;
  2654. OpenMPDirectiveKind DKind = OMPD_unknown;
  2655. public:
  2656. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2657. OpenMPDirectiveKind DKind)
  2658. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2659. ~CaptureRegionUnwinderRAII() {
  2660. if (ErrorFound) {
  2661. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2662. while (--ThisCaptureLevel >= 0)
  2663. S.ActOnCapturedRegionError();
  2664. }
  2665. }
  2666. };
  2667. } // namespace
  2668. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2669. ArrayRef<OMPClause *> Clauses) {
  2670. bool ErrorFound = false;
  2671. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2672. *this, ErrorFound, DSAStack->getCurrentDirective());
  2673. if (!S.isUsable()) {
  2674. ErrorFound = true;
  2675. return StmtError();
  2676. }
  2677. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2678. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2679. OMPOrderedClause *OC = nullptr;
  2680. OMPScheduleClause *SC = nullptr;
  2681. SmallVector<const OMPLinearClause *, 4> LCs;
  2682. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  2683. // This is required for proper codegen.
  2684. for (OMPClause *Clause : Clauses) {
  2685. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2686. Clause->getClauseKind() == OMPC_in_reduction) {
  2687. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2688. // with the corresponding in_reduction items.
  2689. auto *IRC = cast<OMPInReductionClause>(Clause);
  2690. for (Expr *E : IRC->taskgroup_descriptors())
  2691. if (E)
  2692. MarkDeclarationsReferencedInExpr(E);
  2693. }
  2694. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2695. Clause->getClauseKind() == OMPC_copyprivate ||
  2696. (getLangOpts().OpenMPUseTLS &&
  2697. getASTContext().getTargetInfo().isTLSSupported() &&
  2698. Clause->getClauseKind() == OMPC_copyin)) {
  2699. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2700. // Mark all variables in private list clauses as used in inner region.
  2701. for (Stmt *VarRef : Clause->children()) {
  2702. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2703. MarkDeclarationsReferencedInExpr(E);
  2704. }
  2705. }
  2706. DSAStack->setForceVarCapturing(/*V=*/false);
  2707. } else if (CaptureRegions.size() > 1 ||
  2708. CaptureRegions.back() != OMPD_unknown) {
  2709. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2710. PICs.push_back(C);
  2711. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2712. if (Expr *E = C->getPostUpdateExpr())
  2713. MarkDeclarationsReferencedInExpr(E);
  2714. }
  2715. }
  2716. if (Clause->getClauseKind() == OMPC_schedule)
  2717. SC = cast<OMPScheduleClause>(Clause);
  2718. else if (Clause->getClauseKind() == OMPC_ordered)
  2719. OC = cast<OMPOrderedClause>(Clause);
  2720. else if (Clause->getClauseKind() == OMPC_linear)
  2721. LCs.push_back(cast<OMPLinearClause>(Clause));
  2722. }
  2723. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2724. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2725. // specified.
  2726. if (SC &&
  2727. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2728. SC->getSecondScheduleModifier() ==
  2729. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2730. OC) {
  2731. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2732. ? SC->getFirstScheduleModifierLoc()
  2733. : SC->getSecondScheduleModifierLoc(),
  2734. diag::err_omp_schedule_nonmonotonic_ordered)
  2735. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2736. ErrorFound = true;
  2737. }
  2738. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2739. for (const OMPLinearClause *C : LCs) {
  2740. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  2741. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2742. }
  2743. ErrorFound = true;
  2744. }
  2745. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2746. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2747. OC->getNumForLoops()) {
  2748. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  2749. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2750. ErrorFound = true;
  2751. }
  2752. if (ErrorFound) {
  2753. return StmtError();
  2754. }
  2755. StmtResult SR = S;
  2756. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2757. // Mark all variables in private list clauses as used in inner region.
  2758. // Required for proper codegen of combined directives.
  2759. // TODO: add processing for other clauses.
  2760. if (ThisCaptureRegion != OMPD_unknown) {
  2761. for (const clang::OMPClauseWithPreInit *C : PICs) {
  2762. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2763. // Find the particular capture region for the clause if the
  2764. // directive is a combined one with multiple capture regions.
  2765. // If the directive is not a combined one, the capture region
  2766. // associated with the clause is OMPD_unknown and is generated
  2767. // only once.
  2768. if (CaptureRegion == ThisCaptureRegion ||
  2769. CaptureRegion == OMPD_unknown) {
  2770. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2771. for (Decl *D : DS->decls())
  2772. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2773. }
  2774. }
  2775. }
  2776. }
  2777. SR = ActOnCapturedRegionEnd(SR.get());
  2778. }
  2779. return SR;
  2780. }
  2781. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2782. OpenMPDirectiveKind CancelRegion,
  2783. SourceLocation StartLoc) {
  2784. // CancelRegion is only needed for cancel and cancellation_point.
  2785. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2786. return false;
  2787. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2788. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2789. return false;
  2790. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2791. << getOpenMPDirectiveName(CancelRegion);
  2792. return true;
  2793. }
  2794. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  2795. OpenMPDirectiveKind CurrentRegion,
  2796. const DeclarationNameInfo &CurrentName,
  2797. OpenMPDirectiveKind CancelRegion,
  2798. SourceLocation StartLoc) {
  2799. if (Stack->getCurScope()) {
  2800. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  2801. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  2802. bool NestingProhibited = false;
  2803. bool CloseNesting = true;
  2804. bool OrphanSeen = false;
  2805. enum {
  2806. NoRecommend,
  2807. ShouldBeInParallelRegion,
  2808. ShouldBeInOrderedRegion,
  2809. ShouldBeInTargetRegion,
  2810. ShouldBeInTeamsRegion
  2811. } Recommend = NoRecommend;
  2812. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2813. // OpenMP [2.16, Nesting of Regions]
  2814. // OpenMP constructs may not be nested inside a simd region.
  2815. // OpenMP [2.8.1,simd Construct, Restrictions]
  2816. // An ordered construct with the simd clause is the only OpenMP
  2817. // construct that can appear in the simd region.
  2818. // Allowing a SIMD construct nested in another SIMD construct is an
  2819. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2820. // message.
  2821. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2822. ? diag::err_omp_prohibited_region_simd
  2823. : diag::warn_omp_nesting_simd);
  2824. return CurrentRegion != OMPD_simd;
  2825. }
  2826. if (ParentRegion == OMPD_atomic) {
  2827. // OpenMP [2.16, Nesting of Regions]
  2828. // OpenMP constructs may not be nested inside an atomic region.
  2829. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2830. return true;
  2831. }
  2832. if (CurrentRegion == OMPD_section) {
  2833. // OpenMP [2.7.2, sections Construct, Restrictions]
  2834. // Orphaned section directives are prohibited. That is, the section
  2835. // directives must appear within the sections construct and must not be
  2836. // encountered elsewhere in the sections region.
  2837. if (ParentRegion != OMPD_sections &&
  2838. ParentRegion != OMPD_parallel_sections) {
  2839. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2840. << (ParentRegion != OMPD_unknown)
  2841. << getOpenMPDirectiveName(ParentRegion);
  2842. return true;
  2843. }
  2844. return false;
  2845. }
  2846. // Allow some constructs (except teams) to be orphaned (they could be
  2847. // used in functions, called from OpenMP regions with the required
  2848. // preconditions).
  2849. if (ParentRegion == OMPD_unknown &&
  2850. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2851. return false;
  2852. if (CurrentRegion == OMPD_cancellation_point ||
  2853. CurrentRegion == OMPD_cancel) {
  2854. // OpenMP [2.16, Nesting of Regions]
  2855. // A cancellation point construct for which construct-type-clause is
  2856. // taskgroup must be nested inside a task construct. A cancellation
  2857. // point construct for which construct-type-clause is not taskgroup must
  2858. // be closely nested inside an OpenMP construct that matches the type
  2859. // specified in construct-type-clause.
  2860. // A cancel construct for which construct-type-clause is taskgroup must be
  2861. // nested inside a task construct. A cancel construct for which
  2862. // construct-type-clause is not taskgroup must be closely nested inside an
  2863. // OpenMP construct that matches the type specified in
  2864. // construct-type-clause.
  2865. NestingProhibited =
  2866. !((CancelRegion == OMPD_parallel &&
  2867. (ParentRegion == OMPD_parallel ||
  2868. ParentRegion == OMPD_target_parallel)) ||
  2869. (CancelRegion == OMPD_for &&
  2870. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2871. ParentRegion == OMPD_target_parallel_for ||
  2872. ParentRegion == OMPD_distribute_parallel_for ||
  2873. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2874. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2875. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2876. (CancelRegion == OMPD_sections &&
  2877. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2878. ParentRegion == OMPD_parallel_sections)));
  2879. } else if (CurrentRegion == OMPD_master) {
  2880. // OpenMP [2.16, Nesting of Regions]
  2881. // A master region may not be closely nested inside a worksharing,
  2882. // atomic, or explicit task region.
  2883. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2884. isOpenMPTaskingDirective(ParentRegion);
  2885. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2886. // OpenMP [2.16, Nesting of Regions]
  2887. // A critical region may not be nested (closely or otherwise) inside a
  2888. // critical region with the same name. Note that this restriction is not
  2889. // sufficient to prevent deadlock.
  2890. SourceLocation PreviousCriticalLoc;
  2891. bool DeadLock = Stack->hasDirective(
  2892. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2893. const DeclarationNameInfo &DNI,
  2894. SourceLocation Loc) {
  2895. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2896. PreviousCriticalLoc = Loc;
  2897. return true;
  2898. }
  2899. return false;
  2900. },
  2901. false /* skip top directive */);
  2902. if (DeadLock) {
  2903. SemaRef.Diag(StartLoc,
  2904. diag::err_omp_prohibited_region_critical_same_name)
  2905. << CurrentName.getName();
  2906. if (PreviousCriticalLoc.isValid())
  2907. SemaRef.Diag(PreviousCriticalLoc,
  2908. diag::note_omp_previous_critical_region);
  2909. return true;
  2910. }
  2911. } else if (CurrentRegion == OMPD_barrier) {
  2912. // OpenMP [2.16, Nesting of Regions]
  2913. // A barrier region may not be closely nested inside a worksharing,
  2914. // explicit task, critical, ordered, atomic, or master region.
  2915. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2916. isOpenMPTaskingDirective(ParentRegion) ||
  2917. ParentRegion == OMPD_master ||
  2918. ParentRegion == OMPD_critical ||
  2919. ParentRegion == OMPD_ordered;
  2920. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2921. !isOpenMPParallelDirective(CurrentRegion) &&
  2922. !isOpenMPTeamsDirective(CurrentRegion)) {
  2923. // OpenMP [2.16, Nesting of Regions]
  2924. // A worksharing region may not be closely nested inside a worksharing,
  2925. // explicit task, critical, ordered, atomic, or master region.
  2926. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2927. isOpenMPTaskingDirective(ParentRegion) ||
  2928. ParentRegion == OMPD_master ||
  2929. ParentRegion == OMPD_critical ||
  2930. ParentRegion == OMPD_ordered;
  2931. Recommend = ShouldBeInParallelRegion;
  2932. } else if (CurrentRegion == OMPD_ordered) {
  2933. // OpenMP [2.16, Nesting of Regions]
  2934. // An ordered region may not be closely nested inside a critical,
  2935. // atomic, or explicit task region.
  2936. // An ordered region must be closely nested inside a loop region (or
  2937. // parallel loop region) with an ordered clause.
  2938. // OpenMP [2.8.1,simd Construct, Restrictions]
  2939. // An ordered construct with the simd clause is the only OpenMP construct
  2940. // that can appear in the simd region.
  2941. NestingProhibited = ParentRegion == OMPD_critical ||
  2942. isOpenMPTaskingDirective(ParentRegion) ||
  2943. !(isOpenMPSimdDirective(ParentRegion) ||
  2944. Stack->isParentOrderedRegion());
  2945. Recommend = ShouldBeInOrderedRegion;
  2946. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2947. // OpenMP [2.16, Nesting of Regions]
  2948. // If specified, a teams construct must be contained within a target
  2949. // construct.
  2950. NestingProhibited = ParentRegion != OMPD_target;
  2951. OrphanSeen = ParentRegion == OMPD_unknown;
  2952. Recommend = ShouldBeInTargetRegion;
  2953. }
  2954. if (!NestingProhibited &&
  2955. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2956. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2957. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2958. // OpenMP [2.16, Nesting of Regions]
  2959. // distribute, parallel, parallel sections, parallel workshare, and the
  2960. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2961. // constructs that can be closely nested in the teams region.
  2962. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2963. !isOpenMPDistributeDirective(CurrentRegion);
  2964. Recommend = ShouldBeInParallelRegion;
  2965. }
  2966. if (!NestingProhibited &&
  2967. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2968. // OpenMP 4.5 [2.17 Nesting of Regions]
  2969. // The region associated with the distribute construct must be strictly
  2970. // nested inside a teams region
  2971. NestingProhibited =
  2972. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2973. Recommend = ShouldBeInTeamsRegion;
  2974. }
  2975. if (!NestingProhibited &&
  2976. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2977. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2978. // OpenMP 4.5 [2.17 Nesting of Regions]
  2979. // If a target, target update, target data, target enter data, or
  2980. // target exit data construct is encountered during execution of a
  2981. // target region, the behavior is unspecified.
  2982. NestingProhibited = Stack->hasDirective(
  2983. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2984. SourceLocation) {
  2985. if (isOpenMPTargetExecutionDirective(K)) {
  2986. OffendingRegion = K;
  2987. return true;
  2988. }
  2989. return false;
  2990. },
  2991. false /* don't skip top directive */);
  2992. CloseNesting = false;
  2993. }
  2994. if (NestingProhibited) {
  2995. if (OrphanSeen) {
  2996. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2997. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2998. } else {
  2999. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3000. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3001. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3002. }
  3003. return true;
  3004. }
  3005. }
  3006. return false;
  3007. }
  3008. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3009. ArrayRef<OMPClause *> Clauses,
  3010. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3011. bool ErrorFound = false;
  3012. unsigned NamedModifiersNumber = 0;
  3013. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3014. OMPD_unknown + 1);
  3015. SmallVector<SourceLocation, 4> NameModifierLoc;
  3016. for (const OMPClause *C : Clauses) {
  3017. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3018. // At most one if clause without a directive-name-modifier can appear on
  3019. // the directive.
  3020. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3021. if (FoundNameModifiers[CurNM]) {
  3022. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3023. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3024. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3025. ErrorFound = true;
  3026. } else if (CurNM != OMPD_unknown) {
  3027. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3028. ++NamedModifiersNumber;
  3029. }
  3030. FoundNameModifiers[CurNM] = IC;
  3031. if (CurNM == OMPD_unknown)
  3032. continue;
  3033. // Check if the specified name modifier is allowed for the current
  3034. // directive.
  3035. // At most one if clause with the particular directive-name-modifier can
  3036. // appear on the directive.
  3037. bool MatchFound = false;
  3038. for (auto NM : AllowedNameModifiers) {
  3039. if (CurNM == NM) {
  3040. MatchFound = true;
  3041. break;
  3042. }
  3043. }
  3044. if (!MatchFound) {
  3045. S.Diag(IC->getNameModifierLoc(),
  3046. diag::err_omp_wrong_if_directive_name_modifier)
  3047. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3048. ErrorFound = true;
  3049. }
  3050. }
  3051. }
  3052. // If any if clause on the directive includes a directive-name-modifier then
  3053. // all if clauses on the directive must include a directive-name-modifier.
  3054. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3055. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3056. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3057. diag::err_omp_no_more_if_clause);
  3058. } else {
  3059. std::string Values;
  3060. std::string Sep(", ");
  3061. unsigned AllowedCnt = 0;
  3062. unsigned TotalAllowedNum =
  3063. AllowedNameModifiers.size() - NamedModifiersNumber;
  3064. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3065. ++Cnt) {
  3066. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3067. if (!FoundNameModifiers[NM]) {
  3068. Values += "'";
  3069. Values += getOpenMPDirectiveName(NM);
  3070. Values += "'";
  3071. if (AllowedCnt + 2 == TotalAllowedNum)
  3072. Values += " or ";
  3073. else if (AllowedCnt + 1 != TotalAllowedNum)
  3074. Values += Sep;
  3075. ++AllowedCnt;
  3076. }
  3077. }
  3078. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3079. diag::err_omp_unnamed_if_clause)
  3080. << (TotalAllowedNum > 1) << Values;
  3081. }
  3082. for (SourceLocation Loc : NameModifierLoc) {
  3083. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3084. }
  3085. ErrorFound = true;
  3086. }
  3087. return ErrorFound;
  3088. }
  3089. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3090. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3091. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3092. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3093. StmtResult Res = StmtError();
  3094. // First check CancelRegion which is then used in checkNestingOfRegions.
  3095. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3096. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3097. StartLoc))
  3098. return StmtError();
  3099. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3100. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3101. bool ErrorFound = false;
  3102. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3103. if (AStmt && !CurContext->isDependentContext()) {
  3104. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3105. // Check default data sharing attributes for referenced variables.
  3106. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3107. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3108. Stmt *S = AStmt;
  3109. while (--ThisCaptureLevel >= 0)
  3110. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3111. DSAChecker.Visit(S);
  3112. if (DSAChecker.isErrorFound())
  3113. return StmtError();
  3114. // Generate list of implicitly defined firstprivate variables.
  3115. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3116. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3117. DSAChecker.getImplicitFirstprivate().begin(),
  3118. DSAChecker.getImplicitFirstprivate().end());
  3119. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3120. DSAChecker.getImplicitMap().end());
  3121. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3122. for (OMPClause *C : Clauses) {
  3123. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3124. for (Expr *E : IRC->taskgroup_descriptors())
  3125. if (E)
  3126. ImplicitFirstprivates.emplace_back(E);
  3127. }
  3128. }
  3129. if (!ImplicitFirstprivates.empty()) {
  3130. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3131. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3132. SourceLocation())) {
  3133. ClausesWithImplicit.push_back(Implicit);
  3134. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3135. ImplicitFirstprivates.size();
  3136. } else {
  3137. ErrorFound = true;
  3138. }
  3139. }
  3140. if (!ImplicitMaps.empty()) {
  3141. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3142. llvm::None, llvm::None, OMPC_MAP_tofrom,
  3143. /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
  3144. ImplicitMaps, SourceLocation(), SourceLocation(),
  3145. SourceLocation())) {
  3146. ClausesWithImplicit.emplace_back(Implicit);
  3147. ErrorFound |=
  3148. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3149. } else {
  3150. ErrorFound = true;
  3151. }
  3152. }
  3153. }
  3154. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  3155. switch (Kind) {
  3156. case OMPD_parallel:
  3157. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  3158. EndLoc);
  3159. AllowedNameModifiers.push_back(OMPD_parallel);
  3160. break;
  3161. case OMPD_simd:
  3162. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3163. VarsWithInheritedDSA);
  3164. break;
  3165. case OMPD_for:
  3166. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3167. VarsWithInheritedDSA);
  3168. break;
  3169. case OMPD_for_simd:
  3170. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3171. EndLoc, VarsWithInheritedDSA);
  3172. break;
  3173. case OMPD_sections:
  3174. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3175. EndLoc);
  3176. break;
  3177. case OMPD_section:
  3178. assert(ClausesWithImplicit.empty() &&
  3179. "No clauses are allowed for 'omp section' directive");
  3180. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  3181. break;
  3182. case OMPD_single:
  3183. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  3184. EndLoc);
  3185. break;
  3186. case OMPD_master:
  3187. assert(ClausesWithImplicit.empty() &&
  3188. "No clauses are allowed for 'omp master' directive");
  3189. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  3190. break;
  3191. case OMPD_critical:
  3192. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  3193. StartLoc, EndLoc);
  3194. break;
  3195. case OMPD_parallel_for:
  3196. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  3197. EndLoc, VarsWithInheritedDSA);
  3198. AllowedNameModifiers.push_back(OMPD_parallel);
  3199. break;
  3200. case OMPD_parallel_for_simd:
  3201. Res = ActOnOpenMPParallelForSimdDirective(
  3202. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3203. AllowedNameModifiers.push_back(OMPD_parallel);
  3204. break;
  3205. case OMPD_parallel_sections:
  3206. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  3207. StartLoc, EndLoc);
  3208. AllowedNameModifiers.push_back(OMPD_parallel);
  3209. break;
  3210. case OMPD_task:
  3211. Res =
  3212. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3213. AllowedNameModifiers.push_back(OMPD_task);
  3214. break;
  3215. case OMPD_taskyield:
  3216. assert(ClausesWithImplicit.empty() &&
  3217. "No clauses are allowed for 'omp taskyield' directive");
  3218. assert(AStmt == nullptr &&
  3219. "No associated statement allowed for 'omp taskyield' directive");
  3220. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  3221. break;
  3222. case OMPD_barrier:
  3223. assert(ClausesWithImplicit.empty() &&
  3224. "No clauses are allowed for 'omp barrier' directive");
  3225. assert(AStmt == nullptr &&
  3226. "No associated statement allowed for 'omp barrier' directive");
  3227. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  3228. break;
  3229. case OMPD_taskwait:
  3230. assert(ClausesWithImplicit.empty() &&
  3231. "No clauses are allowed for 'omp taskwait' directive");
  3232. assert(AStmt == nullptr &&
  3233. "No associated statement allowed for 'omp taskwait' directive");
  3234. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  3235. break;
  3236. case OMPD_taskgroup:
  3237. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  3238. EndLoc);
  3239. break;
  3240. case OMPD_flush:
  3241. assert(AStmt == nullptr &&
  3242. "No associated statement allowed for 'omp flush' directive");
  3243. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  3244. break;
  3245. case OMPD_ordered:
  3246. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  3247. EndLoc);
  3248. break;
  3249. case OMPD_atomic:
  3250. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  3251. EndLoc);
  3252. break;
  3253. case OMPD_teams:
  3254. Res =
  3255. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3256. break;
  3257. case OMPD_target:
  3258. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  3259. EndLoc);
  3260. AllowedNameModifiers.push_back(OMPD_target);
  3261. break;
  3262. case OMPD_target_parallel:
  3263. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  3264. StartLoc, EndLoc);
  3265. AllowedNameModifiers.push_back(OMPD_target);
  3266. AllowedNameModifiers.push_back(OMPD_parallel);
  3267. break;
  3268. case OMPD_target_parallel_for:
  3269. Res = ActOnOpenMPTargetParallelForDirective(
  3270. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3271. AllowedNameModifiers.push_back(OMPD_target);
  3272. AllowedNameModifiers.push_back(OMPD_parallel);
  3273. break;
  3274. case OMPD_cancellation_point:
  3275. assert(ClausesWithImplicit.empty() &&
  3276. "No clauses are allowed for 'omp cancellation point' directive");
  3277. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  3278. "cancellation point' directive");
  3279. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  3280. break;
  3281. case OMPD_cancel:
  3282. assert(AStmt == nullptr &&
  3283. "No associated statement allowed for 'omp cancel' directive");
  3284. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  3285. CancelRegion);
  3286. AllowedNameModifiers.push_back(OMPD_cancel);
  3287. break;
  3288. case OMPD_target_data:
  3289. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  3290. EndLoc);
  3291. AllowedNameModifiers.push_back(OMPD_target_data);
  3292. break;
  3293. case OMPD_target_enter_data:
  3294. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  3295. EndLoc, AStmt);
  3296. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  3297. break;
  3298. case OMPD_target_exit_data:
  3299. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  3300. EndLoc, AStmt);
  3301. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  3302. break;
  3303. case OMPD_taskloop:
  3304. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  3305. EndLoc, VarsWithInheritedDSA);
  3306. AllowedNameModifiers.push_back(OMPD_taskloop);
  3307. break;
  3308. case OMPD_taskloop_simd:
  3309. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3310. EndLoc, VarsWithInheritedDSA);
  3311. AllowedNameModifiers.push_back(OMPD_taskloop);
  3312. break;
  3313. case OMPD_distribute:
  3314. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  3315. EndLoc, VarsWithInheritedDSA);
  3316. break;
  3317. case OMPD_target_update:
  3318. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  3319. EndLoc, AStmt);
  3320. AllowedNameModifiers.push_back(OMPD_target_update);
  3321. break;
  3322. case OMPD_distribute_parallel_for:
  3323. Res = ActOnOpenMPDistributeParallelForDirective(
  3324. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3325. AllowedNameModifiers.push_back(OMPD_parallel);
  3326. break;
  3327. case OMPD_distribute_parallel_for_simd:
  3328. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  3329. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3330. AllowedNameModifiers.push_back(OMPD_parallel);
  3331. break;
  3332. case OMPD_distribute_simd:
  3333. Res = ActOnOpenMPDistributeSimdDirective(
  3334. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3335. break;
  3336. case OMPD_target_parallel_for_simd:
  3337. Res = ActOnOpenMPTargetParallelForSimdDirective(
  3338. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3339. AllowedNameModifiers.push_back(OMPD_target);
  3340. AllowedNameModifiers.push_back(OMPD_parallel);
  3341. break;
  3342. case OMPD_target_simd:
  3343. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3344. EndLoc, VarsWithInheritedDSA);
  3345. AllowedNameModifiers.push_back(OMPD_target);
  3346. break;
  3347. case OMPD_teams_distribute:
  3348. Res = ActOnOpenMPTeamsDistributeDirective(
  3349. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3350. break;
  3351. case OMPD_teams_distribute_simd:
  3352. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  3353. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3354. break;
  3355. case OMPD_teams_distribute_parallel_for_simd:
  3356. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  3357. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3358. AllowedNameModifiers.push_back(OMPD_parallel);
  3359. break;
  3360. case OMPD_teams_distribute_parallel_for:
  3361. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  3362. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3363. AllowedNameModifiers.push_back(OMPD_parallel);
  3364. break;
  3365. case OMPD_target_teams:
  3366. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3367. EndLoc);
  3368. AllowedNameModifiers.push_back(OMPD_target);
  3369. break;
  3370. case OMPD_target_teams_distribute:
  3371. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  3372. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3373. AllowedNameModifiers.push_back(OMPD_target);
  3374. break;
  3375. case OMPD_target_teams_distribute_parallel_for:
  3376. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  3377. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3378. AllowedNameModifiers.push_back(OMPD_target);
  3379. AllowedNameModifiers.push_back(OMPD_parallel);
  3380. break;
  3381. case OMPD_target_teams_distribute_parallel_for_simd:
  3382. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  3383. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3384. AllowedNameModifiers.push_back(OMPD_target);
  3385. AllowedNameModifiers.push_back(OMPD_parallel);
  3386. break;
  3387. case OMPD_target_teams_distribute_simd:
  3388. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  3389. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3390. AllowedNameModifiers.push_back(OMPD_target);
  3391. break;
  3392. case OMPD_declare_target:
  3393. case OMPD_end_declare_target:
  3394. case OMPD_threadprivate:
  3395. case OMPD_declare_reduction:
  3396. case OMPD_declare_simd:
  3397. case OMPD_requires:
  3398. llvm_unreachable("OpenMP Directive is not allowed");
  3399. case OMPD_unknown:
  3400. llvm_unreachable("Unknown OpenMP directive");
  3401. }
  3402. for (const auto &P : VarsWithInheritedDSA) {
  3403. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  3404. << P.first << P.second->getSourceRange();
  3405. }
  3406. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  3407. if (!AllowedNameModifiers.empty())
  3408. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  3409. ErrorFound;
  3410. if (ErrorFound)
  3411. return StmtError();
  3412. return Res;
  3413. }
  3414. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  3415. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  3416. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  3417. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  3418. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  3419. assert(Aligneds.size() == Alignments.size());
  3420. assert(Linears.size() == LinModifiers.size());
  3421. assert(Linears.size() == Steps.size());
  3422. if (!DG || DG.get().isNull())
  3423. return DeclGroupPtrTy();
  3424. if (!DG.get().isSingleDecl()) {
  3425. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  3426. return DG;
  3427. }
  3428. Decl *ADecl = DG.get().getSingleDecl();
  3429. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  3430. ADecl = FTD->getTemplatedDecl();
  3431. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  3432. if (!FD) {
  3433. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  3434. return DeclGroupPtrTy();
  3435. }
  3436. // OpenMP [2.8.2, declare simd construct, Description]
  3437. // The parameter of the simdlen clause must be a constant positive integer
  3438. // expression.
  3439. ExprResult SL;
  3440. if (Simdlen)
  3441. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3442. // OpenMP [2.8.2, declare simd construct, Description]
  3443. // The special this pointer can be used as if was one of the arguments to the
  3444. // function in any of the linear, aligned, or uniform clauses.
  3445. // The uniform clause declares one or more arguments to have an invariant
  3446. // value for all concurrent invocations of the function in the execution of a
  3447. // single SIMD loop.
  3448. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  3449. const Expr *UniformedLinearThis = nullptr;
  3450. for (const Expr *E : Uniforms) {
  3451. E = E->IgnoreParenImpCasts();
  3452. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3453. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3454. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3455. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3456. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3457. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  3458. continue;
  3459. }
  3460. if (isa<CXXThisExpr>(E)) {
  3461. UniformedLinearThis = E;
  3462. continue;
  3463. }
  3464. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3465. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3466. }
  3467. // OpenMP [2.8.2, declare simd construct, Description]
  3468. // The aligned clause declares that the object to which each list item points
  3469. // is aligned to the number of bytes expressed in the optional parameter of
  3470. // the aligned clause.
  3471. // The special this pointer can be used as if was one of the arguments to the
  3472. // function in any of the linear, aligned, or uniform clauses.
  3473. // The type of list items appearing in the aligned clause must be array,
  3474. // pointer, reference to array, or reference to pointer.
  3475. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  3476. const Expr *AlignedThis = nullptr;
  3477. for (const Expr *E : Aligneds) {
  3478. E = E->IgnoreParenImpCasts();
  3479. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3480. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3481. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3482. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3483. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3484. ->getCanonicalDecl() == CanonPVD) {
  3485. // OpenMP [2.8.1, simd construct, Restrictions]
  3486. // A list-item cannot appear in more than one aligned clause.
  3487. if (AlignedArgs.count(CanonPVD) > 0) {
  3488. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3489. << 1 << E->getSourceRange();
  3490. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3491. diag::note_omp_explicit_dsa)
  3492. << getOpenMPClauseName(OMPC_aligned);
  3493. continue;
  3494. }
  3495. AlignedArgs[CanonPVD] = E;
  3496. QualType QTy = PVD->getType()
  3497. .getNonReferenceType()
  3498. .getUnqualifiedType()
  3499. .getCanonicalType();
  3500. const Type *Ty = QTy.getTypePtrOrNull();
  3501. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3502. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3503. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3504. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3505. }
  3506. continue;
  3507. }
  3508. }
  3509. if (isa<CXXThisExpr>(E)) {
  3510. if (AlignedThis) {
  3511. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3512. << 2 << E->getSourceRange();
  3513. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3514. << getOpenMPClauseName(OMPC_aligned);
  3515. }
  3516. AlignedThis = E;
  3517. continue;
  3518. }
  3519. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3520. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3521. }
  3522. // The optional parameter of the aligned clause, alignment, must be a constant
  3523. // positive integer expression. If no optional parameter is specified,
  3524. // implementation-defined default alignments for SIMD instructions on the
  3525. // target platforms are assumed.
  3526. SmallVector<const Expr *, 4> NewAligns;
  3527. for (Expr *E : Alignments) {
  3528. ExprResult Align;
  3529. if (E)
  3530. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3531. NewAligns.push_back(Align.get());
  3532. }
  3533. // OpenMP [2.8.2, declare simd construct, Description]
  3534. // The linear clause declares one or more list items to be private to a SIMD
  3535. // lane and to have a linear relationship with respect to the iteration space
  3536. // of a loop.
  3537. // The special this pointer can be used as if was one of the arguments to the
  3538. // function in any of the linear, aligned, or uniform clauses.
  3539. // When a linear-step expression is specified in a linear clause it must be
  3540. // either a constant integer expression or an integer-typed parameter that is
  3541. // specified in a uniform clause on the directive.
  3542. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  3543. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3544. auto MI = LinModifiers.begin();
  3545. for (const Expr *E : Linears) {
  3546. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3547. ++MI;
  3548. E = E->IgnoreParenImpCasts();
  3549. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3550. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3551. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3552. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3553. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3554. ->getCanonicalDecl() == CanonPVD) {
  3555. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3556. // A list-item cannot appear in more than one linear clause.
  3557. if (LinearArgs.count(CanonPVD) > 0) {
  3558. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3559. << getOpenMPClauseName(OMPC_linear)
  3560. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3561. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3562. diag::note_omp_explicit_dsa)
  3563. << getOpenMPClauseName(OMPC_linear);
  3564. continue;
  3565. }
  3566. // Each argument can appear in at most one uniform or linear clause.
  3567. if (UniformedArgs.count(CanonPVD) > 0) {
  3568. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3569. << getOpenMPClauseName(OMPC_linear)
  3570. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3571. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3572. diag::note_omp_explicit_dsa)
  3573. << getOpenMPClauseName(OMPC_uniform);
  3574. continue;
  3575. }
  3576. LinearArgs[CanonPVD] = E;
  3577. if (E->isValueDependent() || E->isTypeDependent() ||
  3578. E->isInstantiationDependent() ||
  3579. E->containsUnexpandedParameterPack())
  3580. continue;
  3581. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3582. PVD->getOriginalType());
  3583. continue;
  3584. }
  3585. }
  3586. if (isa<CXXThisExpr>(E)) {
  3587. if (UniformedLinearThis) {
  3588. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3589. << getOpenMPClauseName(OMPC_linear)
  3590. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3591. << E->getSourceRange();
  3592. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3593. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3594. : OMPC_linear);
  3595. continue;
  3596. }
  3597. UniformedLinearThis = E;
  3598. if (E->isValueDependent() || E->isTypeDependent() ||
  3599. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3600. continue;
  3601. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3602. E->getType());
  3603. continue;
  3604. }
  3605. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3606. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3607. }
  3608. Expr *Step = nullptr;
  3609. Expr *NewStep = nullptr;
  3610. SmallVector<Expr *, 4> NewSteps;
  3611. for (Expr *E : Steps) {
  3612. // Skip the same step expression, it was checked already.
  3613. if (Step == E || !E) {
  3614. NewSteps.push_back(E ? NewStep : nullptr);
  3615. continue;
  3616. }
  3617. Step = E;
  3618. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3619. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3620. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3621. if (UniformedArgs.count(CanonPVD) == 0) {
  3622. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3623. << Step->getSourceRange();
  3624. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3625. E->isInstantiationDependent() ||
  3626. E->containsUnexpandedParameterPack() ||
  3627. CanonPVD->getType()->hasIntegerRepresentation()) {
  3628. NewSteps.push_back(Step);
  3629. } else {
  3630. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3631. << Step->getSourceRange();
  3632. }
  3633. continue;
  3634. }
  3635. NewStep = Step;
  3636. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3637. !Step->isInstantiationDependent() &&
  3638. !Step->containsUnexpandedParameterPack()) {
  3639. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3640. .get();
  3641. if (NewStep)
  3642. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3643. }
  3644. NewSteps.push_back(NewStep);
  3645. }
  3646. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3647. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3648. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3649. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3650. const_cast<Expr **>(Linears.data()), Linears.size(),
  3651. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3652. NewSteps.data(), NewSteps.size(), SR);
  3653. ADecl->addAttr(NewAttr);
  3654. return ConvertDeclToDeclGroup(ADecl);
  3655. }
  3656. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3657. Stmt *AStmt,
  3658. SourceLocation StartLoc,
  3659. SourceLocation EndLoc) {
  3660. if (!AStmt)
  3661. return StmtError();
  3662. auto *CS = cast<CapturedStmt>(AStmt);
  3663. // 1.2.2 OpenMP Language Terminology
  3664. // Structured block - An executable statement with a single entry at the
  3665. // top and a single exit at the bottom.
  3666. // The point of exit cannot be a branch out of the structured block.
  3667. // longjmp() and throw() must not violate the entry/exit criteria.
  3668. CS->getCapturedDecl()->setNothrow();
  3669. setFunctionHasBranchProtectedScope();
  3670. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3671. DSAStack->isCancelRegion());
  3672. }
  3673. namespace {
  3674. /// Helper class for checking canonical form of the OpenMP loops and
  3675. /// extracting iteration space of each loop in the loop nest, that will be used
  3676. /// for IR generation.
  3677. class OpenMPIterationSpaceChecker {
  3678. /// Reference to Sema.
  3679. Sema &SemaRef;
  3680. /// A location for diagnostics (when there is no some better location).
  3681. SourceLocation DefaultLoc;
  3682. /// A location for diagnostics (when increment is not compatible).
  3683. SourceLocation ConditionLoc;
  3684. /// A source location for referring to loop init later.
  3685. SourceRange InitSrcRange;
  3686. /// A source location for referring to condition later.
  3687. SourceRange ConditionSrcRange;
  3688. /// A source location for referring to increment later.
  3689. SourceRange IncrementSrcRange;
  3690. /// Loop variable.
  3691. ValueDecl *LCDecl = nullptr;
  3692. /// Reference to loop variable.
  3693. Expr *LCRef = nullptr;
  3694. /// Lower bound (initializer for the var).
  3695. Expr *LB = nullptr;
  3696. /// Upper bound.
  3697. Expr *UB = nullptr;
  3698. /// Loop step (increment).
  3699. Expr *Step = nullptr;
  3700. /// This flag is true when condition is one of:
  3701. /// Var < UB
  3702. /// Var <= UB
  3703. /// UB > Var
  3704. /// UB >= Var
  3705. /// This will have no value when the condition is !=
  3706. llvm::Optional<bool> TestIsLessOp;
  3707. /// This flag is true when condition is strict ( < or > ).
  3708. bool TestIsStrictOp = false;
  3709. /// This flag is true when step is subtracted on each iteration.
  3710. bool SubtractStep = false;
  3711. public:
  3712. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3713. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3714. /// Check init-expr for canonical loop form and save loop counter
  3715. /// variable - #Var and its initialization value - #LB.
  3716. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  3717. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  3718. /// for less/greater and for strict/non-strict comparison.
  3719. bool checkAndSetCond(Expr *S);
  3720. /// Check incr-expr for canonical loop form and return true if it
  3721. /// does not conform, otherwise save loop step (#Step).
  3722. bool checkAndSetInc(Expr *S);
  3723. /// Return the loop counter variable.
  3724. ValueDecl *getLoopDecl() const { return LCDecl; }
  3725. /// Return the reference expression to loop counter variable.
  3726. Expr *getLoopDeclRefExpr() const { return LCRef; }
  3727. /// Source range of the loop init.
  3728. SourceRange getInitSrcRange() const { return InitSrcRange; }
  3729. /// Source range of the loop condition.
  3730. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  3731. /// Source range of the loop increment.
  3732. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  3733. /// True if the step should be subtracted.
  3734. bool shouldSubtractStep() const { return SubtractStep; }
  3735. /// Build the expression to calculate the number of iterations.
  3736. Expr *buildNumIterations(
  3737. Scope *S, const bool LimitedType,
  3738. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3739. /// Build the precondition expression for the loops.
  3740. Expr *
  3741. buildPreCond(Scope *S, Expr *Cond,
  3742. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3743. /// Build reference expression to the counter be used for codegen.
  3744. DeclRefExpr *
  3745. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3746. DSAStackTy &DSA) const;
  3747. /// Build reference expression to the private counter be used for
  3748. /// codegen.
  3749. Expr *buildPrivateCounterVar() const;
  3750. /// Build initialization of the counter be used for codegen.
  3751. Expr *buildCounterInit() const;
  3752. /// Build step of the counter be used for codegen.
  3753. Expr *buildCounterStep() const;
  3754. /// Build loop data with counter value for depend clauses in ordered
  3755. /// directives.
  3756. Expr *
  3757. buildOrderedLoopData(Scope *S, Expr *Counter,
  3758. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3759. SourceLocation Loc, Expr *Inc = nullptr,
  3760. OverloadedOperatorKind OOK = OO_Amp);
  3761. /// Return true if any expression is dependent.
  3762. bool dependent() const;
  3763. private:
  3764. /// Check the right-hand side of an assignment in the increment
  3765. /// expression.
  3766. bool checkAndSetIncRHS(Expr *RHS);
  3767. /// Helper to set loop counter variable and its initializer.
  3768. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3769. /// Helper to set upper bound.
  3770. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  3771. SourceRange SR, SourceLocation SL);
  3772. /// Helper to set loop increment.
  3773. bool setStep(Expr *NewStep, bool Subtract);
  3774. };
  3775. bool OpenMPIterationSpaceChecker::dependent() const {
  3776. if (!LCDecl) {
  3777. assert(!LB && !UB && !Step);
  3778. return false;
  3779. }
  3780. return LCDecl->getType()->isDependentType() ||
  3781. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3782. (Step && Step->isValueDependent());
  3783. }
  3784. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  3785. Expr *NewLCRefExpr,
  3786. Expr *NewLB) {
  3787. // State consistency checking to ensure correct usage.
  3788. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3789. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3790. if (!NewLCDecl || !NewLB)
  3791. return true;
  3792. LCDecl = getCanonicalDecl(NewLCDecl);
  3793. LCRef = NewLCRefExpr;
  3794. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3795. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3796. if ((Ctor->isCopyOrMoveConstructor() ||
  3797. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3798. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3799. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3800. LB = NewLB;
  3801. return false;
  3802. }
  3803. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, llvm::Optional<bool> LessOp,
  3804. bool StrictOp, SourceRange SR,
  3805. SourceLocation SL) {
  3806. // State consistency checking to ensure correct usage.
  3807. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3808. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3809. if (!NewUB)
  3810. return true;
  3811. UB = NewUB;
  3812. if (LessOp)
  3813. TestIsLessOp = LessOp;
  3814. TestIsStrictOp = StrictOp;
  3815. ConditionSrcRange = SR;
  3816. ConditionLoc = SL;
  3817. return false;
  3818. }
  3819. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  3820. // State consistency checking to ensure correct usage.
  3821. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3822. if (!NewStep)
  3823. return true;
  3824. if (!NewStep->isValueDependent()) {
  3825. // Check that the step is integer expression.
  3826. SourceLocation StepLoc = NewStep->getBeginLoc();
  3827. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3828. StepLoc, getExprAsWritten(NewStep));
  3829. if (Val.isInvalid())
  3830. return true;
  3831. NewStep = Val.get();
  3832. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3833. // If test-expr is of form var relational-op b and relational-op is < or
  3834. // <= then incr-expr must cause var to increase on each iteration of the
  3835. // loop. If test-expr is of form var relational-op b and relational-op is
  3836. // > or >= then incr-expr must cause var to decrease on each iteration of
  3837. // the loop.
  3838. // If test-expr is of form b relational-op var and relational-op is < or
  3839. // <= then incr-expr must cause var to decrease on each iteration of the
  3840. // loop. If test-expr is of form b relational-op var and relational-op is
  3841. // > or >= then incr-expr must cause var to increase on each iteration of
  3842. // the loop.
  3843. llvm::APSInt Result;
  3844. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3845. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3846. bool IsConstNeg =
  3847. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3848. bool IsConstPos =
  3849. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3850. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3851. // != with increment is treated as <; != with decrement is treated as >
  3852. if (!TestIsLessOp.hasValue())
  3853. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  3854. if (UB && (IsConstZero ||
  3855. (TestIsLessOp.getValue() ?
  3856. (IsConstNeg || (IsUnsigned && Subtract)) :
  3857. (IsConstPos || (IsUnsigned && !Subtract))))) {
  3858. SemaRef.Diag(NewStep->getExprLoc(),
  3859. diag::err_omp_loop_incr_not_compatible)
  3860. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  3861. SemaRef.Diag(ConditionLoc,
  3862. diag::note_omp_loop_cond_requres_compatible_incr)
  3863. << TestIsLessOp.getValue() << ConditionSrcRange;
  3864. return true;
  3865. }
  3866. if (TestIsLessOp.getValue() == Subtract) {
  3867. NewStep =
  3868. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3869. .get();
  3870. Subtract = !Subtract;
  3871. }
  3872. }
  3873. Step = NewStep;
  3874. SubtractStep = Subtract;
  3875. return false;
  3876. }
  3877. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  3878. // Check init-expr for canonical loop form and save loop counter
  3879. // variable - #Var and its initialization value - #LB.
  3880. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3881. // var = lb
  3882. // integer-type var = lb
  3883. // random-access-iterator-type var = lb
  3884. // pointer-type var = lb
  3885. //
  3886. if (!S) {
  3887. if (EmitDiags) {
  3888. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3889. }
  3890. return true;
  3891. }
  3892. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3893. if (!ExprTemp->cleanupsHaveSideEffects())
  3894. S = ExprTemp->getSubExpr();
  3895. InitSrcRange = S->getSourceRange();
  3896. if (Expr *E = dyn_cast<Expr>(S))
  3897. S = E->IgnoreParens();
  3898. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3899. if (BO->getOpcode() == BO_Assign) {
  3900. Expr *LHS = BO->getLHS()->IgnoreParens();
  3901. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3902. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3903. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3904. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3905. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3906. }
  3907. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3908. if (ME->isArrow() &&
  3909. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3910. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3911. }
  3912. }
  3913. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3914. if (DS->isSingleDecl()) {
  3915. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3916. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3917. // Accept non-canonical init form here but emit ext. warning.
  3918. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3919. SemaRef.Diag(S->getBeginLoc(),
  3920. diag::ext_omp_loop_not_canonical_init)
  3921. << S->getSourceRange();
  3922. return setLCDeclAndLB(
  3923. Var,
  3924. buildDeclRefExpr(SemaRef, Var,
  3925. Var->getType().getNonReferenceType(),
  3926. DS->getBeginLoc()),
  3927. Var->getInit());
  3928. }
  3929. }
  3930. }
  3931. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3932. if (CE->getOperator() == OO_Equal) {
  3933. Expr *LHS = CE->getArg(0);
  3934. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3935. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3936. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3937. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3938. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3939. }
  3940. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3941. if (ME->isArrow() &&
  3942. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3943. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3944. }
  3945. }
  3946. }
  3947. if (dependent() || SemaRef.CurContext->isDependentContext())
  3948. return false;
  3949. if (EmitDiags) {
  3950. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  3951. << S->getSourceRange();
  3952. }
  3953. return true;
  3954. }
  3955. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  3956. /// variable (which may be the loop variable) if possible.
  3957. static const ValueDecl *getInitLCDecl(const Expr *E) {
  3958. if (!E)
  3959. return nullptr;
  3960. E = getExprAsWritten(E);
  3961. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3962. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3963. if ((Ctor->isCopyOrMoveConstructor() ||
  3964. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3965. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3966. E = CE->getArg(0)->IgnoreParenImpCasts();
  3967. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3968. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3969. return getCanonicalDecl(VD);
  3970. }
  3971. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3972. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3973. return getCanonicalDecl(ME->getMemberDecl());
  3974. return nullptr;
  3975. }
  3976. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  3977. // Check test-expr for canonical form, save upper-bound UB, flags for
  3978. // less/greater and for strict/non-strict comparison.
  3979. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3980. // var relational-op b
  3981. // b relational-op var
  3982. //
  3983. if (!S) {
  3984. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3985. return true;
  3986. }
  3987. S = getExprAsWritten(S);
  3988. SourceLocation CondLoc = S->getBeginLoc();
  3989. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3990. if (BO->isRelationalOp()) {
  3991. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  3992. return setUB(BO->getRHS(),
  3993. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3994. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3995. BO->getSourceRange(), BO->getOperatorLoc());
  3996. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  3997. return setUB(BO->getLHS(),
  3998. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3999. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4000. BO->getSourceRange(), BO->getOperatorLoc());
  4001. } else if (BO->getOpcode() == BO_NE)
  4002. return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
  4003. BO->getRHS() : BO->getLHS(),
  4004. /*LessOp=*/llvm::None,
  4005. /*StrictOp=*/true,
  4006. BO->getSourceRange(), BO->getOperatorLoc());
  4007. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4008. if (CE->getNumArgs() == 2) {
  4009. auto Op = CE->getOperator();
  4010. switch (Op) {
  4011. case OO_Greater:
  4012. case OO_GreaterEqual:
  4013. case OO_Less:
  4014. case OO_LessEqual:
  4015. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4016. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  4017. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4018. CE->getOperatorLoc());
  4019. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  4020. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  4021. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4022. CE->getOperatorLoc());
  4023. break;
  4024. case OO_ExclaimEqual:
  4025. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
  4026. CE->getArg(1) : CE->getArg(0),
  4027. /*LessOp=*/llvm::None,
  4028. /*StrictOp=*/true,
  4029. CE->getSourceRange(),
  4030. CE->getOperatorLoc());
  4031. break;
  4032. default:
  4033. break;
  4034. }
  4035. }
  4036. }
  4037. if (dependent() || SemaRef.CurContext->isDependentContext())
  4038. return false;
  4039. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  4040. << S->getSourceRange() << LCDecl;
  4041. return true;
  4042. }
  4043. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  4044. // RHS of canonical loop form increment can be:
  4045. // var + incr
  4046. // incr + var
  4047. // var - incr
  4048. //
  4049. RHS = RHS->IgnoreParenImpCasts();
  4050. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  4051. if (BO->isAdditiveOp()) {
  4052. bool IsAdd = BO->getOpcode() == BO_Add;
  4053. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4054. return setStep(BO->getRHS(), !IsAdd);
  4055. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  4056. return setStep(BO->getLHS(), /*Subtract=*/false);
  4057. }
  4058. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  4059. bool IsAdd = CE->getOperator() == OO_Plus;
  4060. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  4061. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4062. return setStep(CE->getArg(1), !IsAdd);
  4063. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  4064. return setStep(CE->getArg(0), /*Subtract=*/false);
  4065. }
  4066. }
  4067. if (dependent() || SemaRef.CurContext->isDependentContext())
  4068. return false;
  4069. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4070. << RHS->getSourceRange() << LCDecl;
  4071. return true;
  4072. }
  4073. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  4074. // Check incr-expr for canonical loop form and return true if it
  4075. // does not conform.
  4076. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4077. // ++var
  4078. // var++
  4079. // --var
  4080. // var--
  4081. // var += incr
  4082. // var -= incr
  4083. // var = var + incr
  4084. // var = incr + var
  4085. // var = var - incr
  4086. //
  4087. if (!S) {
  4088. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  4089. return true;
  4090. }
  4091. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4092. if (!ExprTemp->cleanupsHaveSideEffects())
  4093. S = ExprTemp->getSubExpr();
  4094. IncrementSrcRange = S->getSourceRange();
  4095. S = S->IgnoreParens();
  4096. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  4097. if (UO->isIncrementDecrementOp() &&
  4098. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  4099. return setStep(SemaRef
  4100. .ActOnIntegerConstant(UO->getBeginLoc(),
  4101. (UO->isDecrementOp() ? -1 : 1))
  4102. .get(),
  4103. /*Subtract=*/false);
  4104. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4105. switch (BO->getOpcode()) {
  4106. case BO_AddAssign:
  4107. case BO_SubAssign:
  4108. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4109. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  4110. break;
  4111. case BO_Assign:
  4112. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4113. return checkAndSetIncRHS(BO->getRHS());
  4114. break;
  4115. default:
  4116. break;
  4117. }
  4118. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4119. switch (CE->getOperator()) {
  4120. case OO_PlusPlus:
  4121. case OO_MinusMinus:
  4122. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4123. return setStep(SemaRef
  4124. .ActOnIntegerConstant(
  4125. CE->getBeginLoc(),
  4126. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  4127. .get(),
  4128. /*Subtract=*/false);
  4129. break;
  4130. case OO_PlusEqual:
  4131. case OO_MinusEqual:
  4132. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4133. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  4134. break;
  4135. case OO_Equal:
  4136. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4137. return checkAndSetIncRHS(CE->getArg(1));
  4138. break;
  4139. default:
  4140. break;
  4141. }
  4142. }
  4143. if (dependent() || SemaRef.CurContext->isDependentContext())
  4144. return false;
  4145. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4146. << S->getSourceRange() << LCDecl;
  4147. return true;
  4148. }
  4149. static ExprResult
  4150. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  4151. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4152. if (SemaRef.CurContext->isDependentContext())
  4153. return ExprResult(Capture);
  4154. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  4155. return SemaRef.PerformImplicitConversion(
  4156. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  4157. /*AllowExplicit=*/true);
  4158. auto I = Captures.find(Capture);
  4159. if (I != Captures.end())
  4160. return buildCapture(SemaRef, Capture, I->second);
  4161. DeclRefExpr *Ref = nullptr;
  4162. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  4163. Captures[Capture] = Ref;
  4164. return Res;
  4165. }
  4166. /// Build the expression to calculate the number of iterations.
  4167. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  4168. Scope *S, const bool LimitedType,
  4169. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4170. ExprResult Diff;
  4171. QualType VarType = LCDecl->getType().getNonReferenceType();
  4172. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4173. SemaRef.getLangOpts().CPlusPlus) {
  4174. // Upper - Lower
  4175. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  4176. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  4177. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  4178. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  4179. if (!Upper || !Lower)
  4180. return nullptr;
  4181. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4182. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4183. // BuildBinOp already emitted error, this one is to point user to upper
  4184. // and lower bound, and to tell what is passed to 'operator-'.
  4185. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4186. << Upper->getSourceRange() << Lower->getSourceRange();
  4187. return nullptr;
  4188. }
  4189. }
  4190. if (!Diff.isUsable())
  4191. return nullptr;
  4192. // Upper - Lower [- 1]
  4193. if (TestIsStrictOp)
  4194. Diff = SemaRef.BuildBinOp(
  4195. S, DefaultLoc, BO_Sub, Diff.get(),
  4196. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4197. if (!Diff.isUsable())
  4198. return nullptr;
  4199. // Upper - Lower [- 1] + Step
  4200. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4201. if (!NewStep.isUsable())
  4202. return nullptr;
  4203. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  4204. if (!Diff.isUsable())
  4205. return nullptr;
  4206. // Parentheses (for dumping/debugging purposes only).
  4207. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4208. if (!Diff.isUsable())
  4209. return nullptr;
  4210. // (Upper - Lower [- 1] + Step) / Step
  4211. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4212. if (!Diff.isUsable())
  4213. return nullptr;
  4214. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  4215. QualType Type = Diff.get()->getType();
  4216. ASTContext &C = SemaRef.Context;
  4217. bool UseVarType = VarType->hasIntegerRepresentation() &&
  4218. C.getTypeSize(Type) > C.getTypeSize(VarType);
  4219. if (!Type->isIntegerType() || UseVarType) {
  4220. unsigned NewSize =
  4221. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  4222. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  4223. : Type->hasSignedIntegerRepresentation();
  4224. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  4225. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  4226. Diff = SemaRef.PerformImplicitConversion(
  4227. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  4228. if (!Diff.isUsable())
  4229. return nullptr;
  4230. }
  4231. }
  4232. if (LimitedType) {
  4233. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  4234. if (NewSize != C.getTypeSize(Type)) {
  4235. if (NewSize < C.getTypeSize(Type)) {
  4236. assert(NewSize == 64 && "incorrect loop var size");
  4237. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  4238. << InitSrcRange << ConditionSrcRange;
  4239. }
  4240. QualType NewType = C.getIntTypeForBitwidth(
  4241. NewSize, Type->hasSignedIntegerRepresentation() ||
  4242. C.getTypeSize(Type) < NewSize);
  4243. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  4244. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  4245. Sema::AA_Converting, true);
  4246. if (!Diff.isUsable())
  4247. return nullptr;
  4248. }
  4249. }
  4250. }
  4251. return Diff.get();
  4252. }
  4253. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  4254. Scope *S, Expr *Cond,
  4255. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4256. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  4257. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4258. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4259. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  4260. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  4261. if (!NewLB.isUsable() || !NewUB.isUsable())
  4262. return nullptr;
  4263. ExprResult CondExpr =
  4264. SemaRef.BuildBinOp(S, DefaultLoc,
  4265. TestIsLessOp.getValue() ?
  4266. (TestIsStrictOp ? BO_LT : BO_LE) :
  4267. (TestIsStrictOp ? BO_GT : BO_GE),
  4268. NewLB.get(), NewUB.get());
  4269. if (CondExpr.isUsable()) {
  4270. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  4271. SemaRef.Context.BoolTy))
  4272. CondExpr = SemaRef.PerformImplicitConversion(
  4273. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  4274. /*AllowExplicit=*/true);
  4275. }
  4276. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4277. // Otherwise use original loop conditon and evaluate it in runtime.
  4278. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  4279. }
  4280. /// Build reference expression to the counter be used for codegen.
  4281. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  4282. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4283. DSAStackTy &DSA) const {
  4284. auto *VD = dyn_cast<VarDecl>(LCDecl);
  4285. if (!VD) {
  4286. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  4287. DeclRefExpr *Ref = buildDeclRefExpr(
  4288. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  4289. const DSAStackTy::DSAVarData Data =
  4290. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  4291. // If the loop control decl is explicitly marked as private, do not mark it
  4292. // as captured again.
  4293. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  4294. Captures.insert(std::make_pair(LCRef, Ref));
  4295. return Ref;
  4296. }
  4297. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  4298. DefaultLoc);
  4299. }
  4300. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  4301. if (LCDecl && !LCDecl->isInvalidDecl()) {
  4302. QualType Type = LCDecl->getType().getNonReferenceType();
  4303. VarDecl *PrivateVar = buildVarDecl(
  4304. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  4305. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  4306. isa<VarDecl>(LCDecl)
  4307. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  4308. : nullptr);
  4309. if (PrivateVar->isInvalidDecl())
  4310. return nullptr;
  4311. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  4312. }
  4313. return nullptr;
  4314. }
  4315. /// Build initialization of the counter to be used for codegen.
  4316. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  4317. /// Build step of the counter be used for codegen.
  4318. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  4319. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  4320. Scope *S, Expr *Counter,
  4321. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  4322. Expr *Inc, OverloadedOperatorKind OOK) {
  4323. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  4324. if (!Cnt)
  4325. return nullptr;
  4326. if (Inc) {
  4327. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  4328. "Expected only + or - operations for depend clauses.");
  4329. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  4330. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  4331. if (!Cnt)
  4332. return nullptr;
  4333. }
  4334. ExprResult Diff;
  4335. QualType VarType = LCDecl->getType().getNonReferenceType();
  4336. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4337. SemaRef.getLangOpts().CPlusPlus) {
  4338. // Upper - Lower
  4339. Expr *Upper =
  4340. TestIsLessOp.getValue() ? Cnt : tryBuildCapture(SemaRef, UB, Captures).get();
  4341. Expr *Lower =
  4342. TestIsLessOp.getValue() ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
  4343. if (!Upper || !Lower)
  4344. return nullptr;
  4345. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4346. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4347. // BuildBinOp already emitted error, this one is to point user to upper
  4348. // and lower bound, and to tell what is passed to 'operator-'.
  4349. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4350. << Upper->getSourceRange() << Lower->getSourceRange();
  4351. return nullptr;
  4352. }
  4353. }
  4354. if (!Diff.isUsable())
  4355. return nullptr;
  4356. // Parentheses (for dumping/debugging purposes only).
  4357. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4358. if (!Diff.isUsable())
  4359. return nullptr;
  4360. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4361. if (!NewStep.isUsable())
  4362. return nullptr;
  4363. // (Upper - Lower) / Step
  4364. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4365. if (!Diff.isUsable())
  4366. return nullptr;
  4367. return Diff.get();
  4368. }
  4369. /// Iteration space of a single for loop.
  4370. struct LoopIterationSpace final {
  4371. /// Condition of the loop.
  4372. Expr *PreCond = nullptr;
  4373. /// This expression calculates the number of iterations in the loop.
  4374. /// It is always possible to calculate it before starting the loop.
  4375. Expr *NumIterations = nullptr;
  4376. /// The loop counter variable.
  4377. Expr *CounterVar = nullptr;
  4378. /// Private loop counter variable.
  4379. Expr *PrivateCounterVar = nullptr;
  4380. /// This is initializer for the initial value of #CounterVar.
  4381. Expr *CounterInit = nullptr;
  4382. /// This is step for the #CounterVar used to generate its update:
  4383. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4384. Expr *CounterStep = nullptr;
  4385. /// Should step be subtracted?
  4386. bool Subtract = false;
  4387. /// Source range of the loop init.
  4388. SourceRange InitSrcRange;
  4389. /// Source range of the loop condition.
  4390. SourceRange CondSrcRange;
  4391. /// Source range of the loop increment.
  4392. SourceRange IncSrcRange;
  4393. };
  4394. } // namespace
  4395. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  4396. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  4397. assert(Init && "Expected loop in canonical form.");
  4398. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  4399. if (AssociatedLoops > 0 &&
  4400. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  4401. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  4402. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  4403. if (ValueDecl *D = ISC.getLoopDecl()) {
  4404. auto *VD = dyn_cast<VarDecl>(D);
  4405. if (!VD) {
  4406. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  4407. VD = Private;
  4408. } else {
  4409. DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  4410. /*WithInit=*/false);
  4411. VD = cast<VarDecl>(Ref->getDecl());
  4412. }
  4413. }
  4414. DSAStack->addLoopControlVariable(D, VD);
  4415. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  4416. if (LD != D->getCanonicalDecl()) {
  4417. DSAStack->resetPossibleLoopCounter();
  4418. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  4419. MarkDeclarationsReferencedInExpr(
  4420. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  4421. Var->getType().getNonLValueExprType(Context),
  4422. ForLoc, /*RefersToCapture=*/true));
  4423. }
  4424. }
  4425. }
  4426. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  4427. }
  4428. }
  4429. /// Called on a for stmt to check and extract its iteration space
  4430. /// for further processing (such as collapsing).
  4431. static bool checkOpenMPIterationSpace(
  4432. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  4433. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  4434. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  4435. Expr *OrderedLoopCountExpr,
  4436. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4437. LoopIterationSpace &ResultIterSpace,
  4438. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4439. // OpenMP [2.6, Canonical Loop Form]
  4440. // for (init-expr; test-expr; incr-expr) structured-block
  4441. auto *For = dyn_cast_or_null<ForStmt>(S);
  4442. if (!For) {
  4443. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  4444. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  4445. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  4446. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  4447. if (TotalNestedLoopCount > 1) {
  4448. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  4449. SemaRef.Diag(DSA.getConstructLoc(),
  4450. diag::note_omp_collapse_ordered_expr)
  4451. << 2 << CollapseLoopCountExpr->getSourceRange()
  4452. << OrderedLoopCountExpr->getSourceRange();
  4453. else if (CollapseLoopCountExpr)
  4454. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4455. diag::note_omp_collapse_ordered_expr)
  4456. << 0 << CollapseLoopCountExpr->getSourceRange();
  4457. else
  4458. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4459. diag::note_omp_collapse_ordered_expr)
  4460. << 1 << OrderedLoopCountExpr->getSourceRange();
  4461. }
  4462. return true;
  4463. }
  4464. assert(For->getBody());
  4465. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  4466. // Check init.
  4467. Stmt *Init = For->getInit();
  4468. if (ISC.checkAndSetInit(Init))
  4469. return true;
  4470. bool HasErrors = false;
  4471. // Check loop variable's type.
  4472. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  4473. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  4474. // OpenMP [2.6, Canonical Loop Form]
  4475. // Var is one of the following:
  4476. // A variable of signed or unsigned integer type.
  4477. // For C++, a variable of a random access iterator type.
  4478. // For C, a variable of a pointer type.
  4479. QualType VarType = LCDecl->getType().getNonReferenceType();
  4480. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  4481. !VarType->isPointerType() &&
  4482. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  4483. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  4484. << SemaRef.getLangOpts().CPlusPlus;
  4485. HasErrors = true;
  4486. }
  4487. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  4488. // a Construct
  4489. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4490. // parallel for construct is (are) private.
  4491. // The loop iteration variable in the associated for-loop of a simd
  4492. // construct with just one associated for-loop is linear with a
  4493. // constant-linear-step that is the increment of the associated for-loop.
  4494. // Exclude loop var from the list of variables with implicitly defined data
  4495. // sharing attributes.
  4496. VarsWithImplicitDSA.erase(LCDecl);
  4497. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  4498. // in a Construct, C/C++].
  4499. // The loop iteration variable in the associated for-loop of a simd
  4500. // construct with just one associated for-loop may be listed in a linear
  4501. // clause with a constant-linear-step that is the increment of the
  4502. // associated for-loop.
  4503. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4504. // parallel for construct may be listed in a private or lastprivate clause.
  4505. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  4506. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  4507. // declared in the loop and it is predetermined as a private.
  4508. OpenMPClauseKind PredeterminedCKind =
  4509. isOpenMPSimdDirective(DKind)
  4510. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  4511. : OMPC_private;
  4512. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4513. DVar.CKind != PredeterminedCKind) ||
  4514. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  4515. isOpenMPDistributeDirective(DKind)) &&
  4516. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4517. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  4518. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  4519. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  4520. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  4521. << getOpenMPClauseName(PredeterminedCKind);
  4522. if (DVar.RefExpr == nullptr)
  4523. DVar.CKind = PredeterminedCKind;
  4524. reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  4525. HasErrors = true;
  4526. } else if (LoopDeclRefExpr != nullptr) {
  4527. // Make the loop iteration variable private (for worksharing constructs),
  4528. // linear (for simd directives with the only one associated loop) or
  4529. // lastprivate (for simd directives with several collapsed or ordered
  4530. // loops).
  4531. if (DVar.CKind == OMPC_unknown)
  4532. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  4533. [](OpenMPDirectiveKind) -> bool { return true; },
  4534. /*FromParent=*/false);
  4535. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  4536. }
  4537. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  4538. // Check test-expr.
  4539. HasErrors |= ISC.checkAndSetCond(For->getCond());
  4540. // Check incr-expr.
  4541. HasErrors |= ISC.checkAndSetInc(For->getInc());
  4542. }
  4543. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  4544. return HasErrors;
  4545. // Build the loop's iteration space representation.
  4546. ResultIterSpace.PreCond =
  4547. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4548. ResultIterSpace.NumIterations = ISC.buildNumIterations(
  4549. DSA.getCurScope(),
  4550. (isOpenMPWorksharingDirective(DKind) ||
  4551. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4552. Captures);
  4553. ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
  4554. ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
  4555. ResultIterSpace.CounterInit = ISC.buildCounterInit();
  4556. ResultIterSpace.CounterStep = ISC.buildCounterStep();
  4557. ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
  4558. ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
  4559. ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
  4560. ResultIterSpace.Subtract = ISC.shouldSubtractStep();
  4561. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4562. ResultIterSpace.NumIterations == nullptr ||
  4563. ResultIterSpace.CounterVar == nullptr ||
  4564. ResultIterSpace.PrivateCounterVar == nullptr ||
  4565. ResultIterSpace.CounterInit == nullptr ||
  4566. ResultIterSpace.CounterStep == nullptr);
  4567. if (!HasErrors && DSA.isOrderedRegion()) {
  4568. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  4569. if (CurrentNestedLoopCount <
  4570. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  4571. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  4572. CurrentNestedLoopCount, ResultIterSpace.NumIterations);
  4573. DSA.getOrderedRegionParam().second->setLoopCounter(
  4574. CurrentNestedLoopCount, ResultIterSpace.CounterVar);
  4575. }
  4576. }
  4577. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  4578. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  4579. // Erroneous case - clause has some problems.
  4580. continue;
  4581. }
  4582. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  4583. Pair.second.size() <= CurrentNestedLoopCount) {
  4584. // Erroneous case - clause has some problems.
  4585. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  4586. continue;
  4587. }
  4588. Expr *CntValue;
  4589. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4590. CntValue = ISC.buildOrderedLoopData(
  4591. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4592. Pair.first->getDependencyLoc());
  4593. else
  4594. CntValue = ISC.buildOrderedLoopData(
  4595. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4596. Pair.first->getDependencyLoc(),
  4597. Pair.second[CurrentNestedLoopCount].first,
  4598. Pair.second[CurrentNestedLoopCount].second);
  4599. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  4600. }
  4601. }
  4602. return HasErrors;
  4603. }
  4604. /// Build 'VarRef = Start.
  4605. static ExprResult
  4606. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4607. ExprResult Start,
  4608. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4609. // Build 'VarRef = Start.
  4610. ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4611. if (!NewStart.isUsable())
  4612. return ExprError();
  4613. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4614. VarRef.get()->getType())) {
  4615. NewStart = SemaRef.PerformImplicitConversion(
  4616. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4617. /*AllowExplicit=*/true);
  4618. if (!NewStart.isUsable())
  4619. return ExprError();
  4620. }
  4621. ExprResult Init =
  4622. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4623. return Init;
  4624. }
  4625. /// Build 'VarRef = Start + Iter * Step'.
  4626. static ExprResult buildCounterUpdate(
  4627. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4628. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  4629. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  4630. // Add parentheses (for debugging purposes only).
  4631. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4632. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4633. !Step.isUsable())
  4634. return ExprError();
  4635. ExprResult NewStep = Step;
  4636. if (Captures)
  4637. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4638. if (NewStep.isInvalid())
  4639. return ExprError();
  4640. ExprResult Update =
  4641. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4642. if (!Update.isUsable())
  4643. return ExprError();
  4644. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4645. // 'VarRef = Start (+|-) Iter * Step'.
  4646. ExprResult NewStart = Start;
  4647. if (Captures)
  4648. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4649. if (NewStart.isInvalid())
  4650. return ExprError();
  4651. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4652. ExprResult SavedUpdate = Update;
  4653. ExprResult UpdateVal;
  4654. if (VarRef.get()->getType()->isOverloadableType() ||
  4655. NewStart.get()->getType()->isOverloadableType() ||
  4656. Update.get()->getType()->isOverloadableType()) {
  4657. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4658. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4659. Update =
  4660. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4661. if (Update.isUsable()) {
  4662. UpdateVal =
  4663. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4664. VarRef.get(), SavedUpdate.get());
  4665. if (UpdateVal.isUsable()) {
  4666. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4667. UpdateVal.get());
  4668. }
  4669. }
  4670. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4671. }
  4672. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4673. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4674. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4675. NewStart.get(), SavedUpdate.get());
  4676. if (!Update.isUsable())
  4677. return ExprError();
  4678. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4679. VarRef.get()->getType())) {
  4680. Update = SemaRef.PerformImplicitConversion(
  4681. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4682. if (!Update.isUsable())
  4683. return ExprError();
  4684. }
  4685. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4686. }
  4687. return Update;
  4688. }
  4689. /// Convert integer expression \a E to make it have at least \a Bits
  4690. /// bits.
  4691. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4692. if (E == nullptr)
  4693. return ExprError();
  4694. ASTContext &C = SemaRef.Context;
  4695. QualType OldType = E->getType();
  4696. unsigned HasBits = C.getTypeSize(OldType);
  4697. if (HasBits >= Bits)
  4698. return ExprResult(E);
  4699. // OK to convert to signed, because new type has more bits than old.
  4700. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4701. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4702. true);
  4703. }
  4704. /// Check if the given expression \a E is a constant integer that fits
  4705. /// into \a Bits bits.
  4706. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  4707. if (E == nullptr)
  4708. return false;
  4709. llvm::APSInt Result;
  4710. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4711. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4712. return false;
  4713. }
  4714. /// Build preinits statement for the given declarations.
  4715. static Stmt *buildPreInits(ASTContext &Context,
  4716. MutableArrayRef<Decl *> PreInits) {
  4717. if (!PreInits.empty()) {
  4718. return new (Context) DeclStmt(
  4719. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4720. SourceLocation(), SourceLocation());
  4721. }
  4722. return nullptr;
  4723. }
  4724. /// Build preinits statement for the given declarations.
  4725. static Stmt *
  4726. buildPreInits(ASTContext &Context,
  4727. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4728. if (!Captures.empty()) {
  4729. SmallVector<Decl *, 16> PreInits;
  4730. for (const auto &Pair : Captures)
  4731. PreInits.push_back(Pair.second->getDecl());
  4732. return buildPreInits(Context, PreInits);
  4733. }
  4734. return nullptr;
  4735. }
  4736. /// Build postupdate expression for the given list of postupdates expressions.
  4737. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4738. Expr *PostUpdate = nullptr;
  4739. if (!PostUpdates.empty()) {
  4740. for (Expr *E : PostUpdates) {
  4741. Expr *ConvE = S.BuildCStyleCastExpr(
  4742. E->getExprLoc(),
  4743. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4744. E->getExprLoc(), E)
  4745. .get();
  4746. PostUpdate = PostUpdate
  4747. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4748. PostUpdate, ConvE)
  4749. .get()
  4750. : ConvE;
  4751. }
  4752. }
  4753. return PostUpdate;
  4754. }
  4755. /// Called on a for stmt to check itself and nested loops (if any).
  4756. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4757. /// number of collapsed loops otherwise.
  4758. static unsigned
  4759. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4760. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4761. DSAStackTy &DSA,
  4762. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4763. OMPLoopDirective::HelperExprs &Built) {
  4764. unsigned NestedLoopCount = 1;
  4765. if (CollapseLoopCountExpr) {
  4766. // Found 'collapse' clause - calculate collapse number.
  4767. Expr::EvalResult Result;
  4768. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4769. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  4770. }
  4771. unsigned OrderedLoopCount = 1;
  4772. if (OrderedLoopCountExpr) {
  4773. // Found 'ordered' clause - calculate collapse number.
  4774. Expr::EvalResult EVResult;
  4775. if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
  4776. llvm::APSInt Result = EVResult.Val.getInt();
  4777. if (Result.getLimitedValue() < NestedLoopCount) {
  4778. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4779. diag::err_omp_wrong_ordered_loop_count)
  4780. << OrderedLoopCountExpr->getSourceRange();
  4781. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4782. diag::note_collapse_loop_count)
  4783. << CollapseLoopCountExpr->getSourceRange();
  4784. }
  4785. OrderedLoopCount = Result.getLimitedValue();
  4786. }
  4787. }
  4788. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4789. // 'for simd', etc.).
  4790. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  4791. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4792. IterSpaces.resize(std::max(OrderedLoopCount, NestedLoopCount));
  4793. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4794. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4795. if (checkOpenMPIterationSpace(
  4796. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  4797. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  4798. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  4799. Captures))
  4800. return 0;
  4801. // Move on to the next nested for loop, or to the loop body.
  4802. // OpenMP [2.8.1, simd construct, Restrictions]
  4803. // All loops associated with the construct must be perfectly nested; that
  4804. // is, there must be no intervening code nor any OpenMP directive between
  4805. // any two loops.
  4806. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4807. }
  4808. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  4809. if (checkOpenMPIterationSpace(
  4810. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  4811. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  4812. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  4813. Captures))
  4814. return 0;
  4815. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  4816. // Handle initialization of captured loop iterator variables.
  4817. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  4818. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  4819. Captures[DRE] = DRE;
  4820. }
  4821. }
  4822. // Move on to the next nested for loop, or to the loop body.
  4823. // OpenMP [2.8.1, simd construct, Restrictions]
  4824. // All loops associated with the construct must be perfectly nested; that
  4825. // is, there must be no intervening code nor any OpenMP directive between
  4826. // any two loops.
  4827. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4828. }
  4829. Built.clear(/* size */ NestedLoopCount);
  4830. if (SemaRef.CurContext->isDependentContext())
  4831. return NestedLoopCount;
  4832. // An example of what is generated for the following code:
  4833. //
  4834. // #pragma omp simd collapse(2) ordered(2)
  4835. // for (i = 0; i < NI; ++i)
  4836. // for (k = 0; k < NK; ++k)
  4837. // for (j = J0; j < NJ; j+=2) {
  4838. // <loop body>
  4839. // }
  4840. //
  4841. // We generate the code below.
  4842. // Note: the loop body may be outlined in CodeGen.
  4843. // Note: some counters may be C++ classes, operator- is used to find number of
  4844. // iterations and operator+= to calculate counter value.
  4845. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4846. // or i64 is currently supported).
  4847. //
  4848. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4849. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4850. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4851. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4852. // // similar updates for vars in clauses (e.g. 'linear')
  4853. // <loop body (using local i and j)>
  4854. // }
  4855. // i = NI; // assign final values of counters
  4856. // j = NJ;
  4857. //
  4858. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4859. // the iteration counts of the collapsed for loops.
  4860. // Precondition tests if there is at least one iteration (all conditions are
  4861. // true).
  4862. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4863. Expr *N0 = IterSpaces[0].NumIterations;
  4864. ExprResult LastIteration32 =
  4865. widenIterationCount(/*Bits=*/32,
  4866. SemaRef
  4867. .PerformImplicitConversion(
  4868. N0->IgnoreImpCasts(), N0->getType(),
  4869. Sema::AA_Converting, /*AllowExplicit=*/true)
  4870. .get(),
  4871. SemaRef);
  4872. ExprResult LastIteration64 = widenIterationCount(
  4873. /*Bits=*/64,
  4874. SemaRef
  4875. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  4876. Sema::AA_Converting,
  4877. /*AllowExplicit=*/true)
  4878. .get(),
  4879. SemaRef);
  4880. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4881. return NestedLoopCount;
  4882. ASTContext &C = SemaRef.Context;
  4883. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4884. Scope *CurScope = DSA.getCurScope();
  4885. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4886. if (PreCond.isUsable()) {
  4887. PreCond =
  4888. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4889. PreCond.get(), IterSpaces[Cnt].PreCond);
  4890. }
  4891. Expr *N = IterSpaces[Cnt].NumIterations;
  4892. SourceLocation Loc = N->getExprLoc();
  4893. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4894. if (LastIteration32.isUsable())
  4895. LastIteration32 = SemaRef.BuildBinOp(
  4896. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4897. SemaRef
  4898. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4899. Sema::AA_Converting,
  4900. /*AllowExplicit=*/true)
  4901. .get());
  4902. if (LastIteration64.isUsable())
  4903. LastIteration64 = SemaRef.BuildBinOp(
  4904. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4905. SemaRef
  4906. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4907. Sema::AA_Converting,
  4908. /*AllowExplicit=*/true)
  4909. .get());
  4910. }
  4911. // Choose either the 32-bit or 64-bit version.
  4912. ExprResult LastIteration = LastIteration64;
  4913. if (LastIteration32.isUsable() &&
  4914. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4915. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4916. fitsInto(
  4917. /*Bits=*/32,
  4918. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4919. LastIteration64.get(), SemaRef)))
  4920. LastIteration = LastIteration32;
  4921. QualType VType = LastIteration.get()->getType();
  4922. QualType RealVType = VType;
  4923. QualType StrideVType = VType;
  4924. if (isOpenMPTaskLoopDirective(DKind)) {
  4925. VType =
  4926. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4927. StrideVType =
  4928. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4929. }
  4930. if (!LastIteration.isUsable())
  4931. return 0;
  4932. // Save the number of iterations.
  4933. ExprResult NumIterations = LastIteration;
  4934. {
  4935. LastIteration = SemaRef.BuildBinOp(
  4936. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4937. LastIteration.get(),
  4938. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4939. if (!LastIteration.isUsable())
  4940. return 0;
  4941. }
  4942. // Calculate the last iteration number beforehand instead of doing this on
  4943. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4944. llvm::APSInt Result;
  4945. bool IsConstant =
  4946. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4947. ExprResult CalcLastIteration;
  4948. if (!IsConstant) {
  4949. ExprResult SaveRef =
  4950. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4951. LastIteration = SaveRef;
  4952. // Prepare SaveRef + 1.
  4953. NumIterations = SemaRef.BuildBinOp(
  4954. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4955. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4956. if (!NumIterations.isUsable())
  4957. return 0;
  4958. }
  4959. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4960. // Build variables passed into runtime, necessary for worksharing directives.
  4961. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4962. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4963. isOpenMPDistributeDirective(DKind)) {
  4964. // Lower bound variable, initialized with zero.
  4965. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4966. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4967. SemaRef.AddInitializerToDecl(LBDecl,
  4968. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4969. /*DirectInit*/ false);
  4970. // Upper bound variable, initialized with last iteration number.
  4971. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4972. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4973. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4974. /*DirectInit*/ false);
  4975. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4976. // This will be used to implement clause 'lastprivate'.
  4977. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4978. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4979. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4980. SemaRef.AddInitializerToDecl(ILDecl,
  4981. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4982. /*DirectInit*/ false);
  4983. // Stride variable returned by runtime (we initialize it to 1 by default).
  4984. VarDecl *STDecl =
  4985. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4986. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4987. SemaRef.AddInitializerToDecl(STDecl,
  4988. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4989. /*DirectInit*/ false);
  4990. // Build expression: UB = min(UB, LastIteration)
  4991. // It is necessary for CodeGen of directives with static scheduling.
  4992. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4993. UB.get(), LastIteration.get());
  4994. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4995. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  4996. LastIteration.get(), UB.get());
  4997. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4998. CondOp.get());
  4999. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  5000. // If we have a combined directive that combines 'distribute', 'for' or
  5001. // 'simd' we need to be able to access the bounds of the schedule of the
  5002. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  5003. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  5004. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5005. // Lower bound variable, initialized with zero.
  5006. VarDecl *CombLBDecl =
  5007. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  5008. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  5009. SemaRef.AddInitializerToDecl(
  5010. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5011. /*DirectInit*/ false);
  5012. // Upper bound variable, initialized with last iteration number.
  5013. VarDecl *CombUBDecl =
  5014. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  5015. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  5016. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  5017. /*DirectInit*/ false);
  5018. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  5019. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  5020. ExprResult CombCondOp =
  5021. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  5022. LastIteration.get(), CombUB.get());
  5023. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  5024. CombCondOp.get());
  5025. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  5026. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  5027. // We expect to have at least 2 more parameters than the 'parallel'
  5028. // directive does - the lower and upper bounds of the previous schedule.
  5029. assert(CD->getNumParams() >= 4 &&
  5030. "Unexpected number of parameters in loop combined directive");
  5031. // Set the proper type for the bounds given what we learned from the
  5032. // enclosed loops.
  5033. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  5034. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  5035. // Previous lower and upper bounds are obtained from the region
  5036. // parameters.
  5037. PrevLB =
  5038. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  5039. PrevUB =
  5040. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  5041. }
  5042. }
  5043. // Build the iteration variable and its initialization before loop.
  5044. ExprResult IV;
  5045. ExprResult Init, CombInit;
  5046. {
  5047. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  5048. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  5049. Expr *RHS =
  5050. (isOpenMPWorksharingDirective(DKind) ||
  5051. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5052. ? LB.get()
  5053. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5054. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  5055. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  5056. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5057. Expr *CombRHS =
  5058. (isOpenMPWorksharingDirective(DKind) ||
  5059. isOpenMPTaskLoopDirective(DKind) ||
  5060. isOpenMPDistributeDirective(DKind))
  5061. ? CombLB.get()
  5062. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5063. CombInit =
  5064. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  5065. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  5066. }
  5067. }
  5068. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  5069. SourceLocation CondLoc = AStmt->getBeginLoc();
  5070. ExprResult Cond =
  5071. (isOpenMPWorksharingDirective(DKind) ||
  5072. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5073. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  5074. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5075. NumIterations.get());
  5076. ExprResult CombDistCond;
  5077. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5078. CombDistCond =
  5079. SemaRef.BuildBinOp(
  5080. CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get());
  5081. }
  5082. ExprResult CombCond;
  5083. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5084. CombCond =
  5085. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  5086. }
  5087. // Loop increment (IV = IV + 1)
  5088. SourceLocation IncLoc = AStmt->getBeginLoc();
  5089. ExprResult Inc =
  5090. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  5091. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  5092. if (!Inc.isUsable())
  5093. return 0;
  5094. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  5095. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  5096. if (!Inc.isUsable())
  5097. return 0;
  5098. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  5099. // Used for directives with static scheduling.
  5100. // In combined construct, add combined version that use CombLB and CombUB
  5101. // base variables for the update
  5102. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  5103. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5104. isOpenMPDistributeDirective(DKind)) {
  5105. // LB + ST
  5106. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  5107. if (!NextLB.isUsable())
  5108. return 0;
  5109. // LB = LB + ST
  5110. NextLB =
  5111. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  5112. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  5113. if (!NextLB.isUsable())
  5114. return 0;
  5115. // UB + ST
  5116. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  5117. if (!NextUB.isUsable())
  5118. return 0;
  5119. // UB = UB + ST
  5120. NextUB =
  5121. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  5122. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  5123. if (!NextUB.isUsable())
  5124. return 0;
  5125. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5126. CombNextLB =
  5127. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  5128. if (!NextLB.isUsable())
  5129. return 0;
  5130. // LB = LB + ST
  5131. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  5132. CombNextLB.get());
  5133. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  5134. if (!CombNextLB.isUsable())
  5135. return 0;
  5136. // UB + ST
  5137. CombNextUB =
  5138. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  5139. if (!CombNextUB.isUsable())
  5140. return 0;
  5141. // UB = UB + ST
  5142. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  5143. CombNextUB.get());
  5144. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  5145. if (!CombNextUB.isUsable())
  5146. return 0;
  5147. }
  5148. }
  5149. // Create increment expression for distribute loop when combined in a same
  5150. // directive with for as IV = IV + ST; ensure upper bound expression based
  5151. // on PrevUB instead of NumIterations - used to implement 'for' when found
  5152. // in combination with 'distribute', like in 'distribute parallel for'
  5153. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  5154. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  5155. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5156. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  5157. assert(DistCond.isUsable() && "distribute cond expr was not built");
  5158. DistInc =
  5159. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  5160. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5161. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  5162. DistInc.get());
  5163. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  5164. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5165. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  5166. // construct
  5167. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  5168. ExprResult IsUBGreater =
  5169. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  5170. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5171. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  5172. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  5173. CondOp.get());
  5174. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  5175. // Build IV <= PrevUB to be used in parallel for is in combination with
  5176. // a distribute directive with schedule(static, 1)
  5177. ParForInDistCond =
  5178. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), PrevUB.get());
  5179. }
  5180. // Build updates and final values of the loop counters.
  5181. bool HasErrors = false;
  5182. Built.Counters.resize(NestedLoopCount);
  5183. Built.Inits.resize(NestedLoopCount);
  5184. Built.Updates.resize(NestedLoopCount);
  5185. Built.Finals.resize(NestedLoopCount);
  5186. {
  5187. ExprResult Div;
  5188. // Go from inner nested loop to outer.
  5189. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  5190. LoopIterationSpace &IS = IterSpaces[Cnt];
  5191. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  5192. // Build: Iter = (IV / Div) % IS.NumIters
  5193. // where Div is product of previous iterations' IS.NumIters.
  5194. ExprResult Iter;
  5195. if (Div.isUsable()) {
  5196. Iter =
  5197. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  5198. } else {
  5199. Iter = IV;
  5200. assert((Cnt == (int)NestedLoopCount - 1) &&
  5201. "unusable div expected on first iteration only");
  5202. }
  5203. if (Cnt != 0 && Iter.isUsable())
  5204. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  5205. IS.NumIterations);
  5206. if (!Iter.isUsable()) {
  5207. HasErrors = true;
  5208. break;
  5209. }
  5210. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  5211. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  5212. DeclRefExpr *CounterVar = buildDeclRefExpr(
  5213. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  5214. /*RefersToCapture=*/true);
  5215. ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  5216. IS.CounterInit, Captures);
  5217. if (!Init.isUsable()) {
  5218. HasErrors = true;
  5219. break;
  5220. }
  5221. ExprResult Update = buildCounterUpdate(
  5222. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  5223. IS.CounterStep, IS.Subtract, &Captures);
  5224. if (!Update.isUsable()) {
  5225. HasErrors = true;
  5226. break;
  5227. }
  5228. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  5229. ExprResult Final = buildCounterUpdate(
  5230. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  5231. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  5232. if (!Final.isUsable()) {
  5233. HasErrors = true;
  5234. break;
  5235. }
  5236. // Build Div for the next iteration: Div <- Div * IS.NumIters
  5237. if (Cnt != 0) {
  5238. if (Div.isUnset())
  5239. Div = IS.NumIterations;
  5240. else
  5241. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  5242. IS.NumIterations);
  5243. // Add parentheses (for debugging purposes only).
  5244. if (Div.isUsable())
  5245. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  5246. if (!Div.isUsable()) {
  5247. HasErrors = true;
  5248. break;
  5249. }
  5250. }
  5251. if (!Update.isUsable() || !Final.isUsable()) {
  5252. HasErrors = true;
  5253. break;
  5254. }
  5255. // Save results
  5256. Built.Counters[Cnt] = IS.CounterVar;
  5257. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  5258. Built.Inits[Cnt] = Init.get();
  5259. Built.Updates[Cnt] = Update.get();
  5260. Built.Finals[Cnt] = Final.get();
  5261. }
  5262. }
  5263. if (HasErrors)
  5264. return 0;
  5265. // Save results
  5266. Built.IterationVarRef = IV.get();
  5267. Built.LastIteration = LastIteration.get();
  5268. Built.NumIterations = NumIterations.get();
  5269. Built.CalcLastIteration =
  5270. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  5271. Built.PreCond = PreCond.get();
  5272. Built.PreInits = buildPreInits(C, Captures);
  5273. Built.Cond = Cond.get();
  5274. Built.Init = Init.get();
  5275. Built.Inc = Inc.get();
  5276. Built.LB = LB.get();
  5277. Built.UB = UB.get();
  5278. Built.IL = IL.get();
  5279. Built.ST = ST.get();
  5280. Built.EUB = EUB.get();
  5281. Built.NLB = NextLB.get();
  5282. Built.NUB = NextUB.get();
  5283. Built.PrevLB = PrevLB.get();
  5284. Built.PrevUB = PrevUB.get();
  5285. Built.DistInc = DistInc.get();
  5286. Built.PrevEUB = PrevEUB.get();
  5287. Built.DistCombinedFields.LB = CombLB.get();
  5288. Built.DistCombinedFields.UB = CombUB.get();
  5289. Built.DistCombinedFields.EUB = CombEUB.get();
  5290. Built.DistCombinedFields.Init = CombInit.get();
  5291. Built.DistCombinedFields.Cond = CombCond.get();
  5292. Built.DistCombinedFields.NLB = CombNextLB.get();
  5293. Built.DistCombinedFields.NUB = CombNextUB.get();
  5294. Built.DistCombinedFields.DistCond = CombDistCond.get();
  5295. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  5296. return NestedLoopCount;
  5297. }
  5298. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5299. auto CollapseClauses =
  5300. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  5301. if (CollapseClauses.begin() != CollapseClauses.end())
  5302. return (*CollapseClauses.begin())->getNumForLoops();
  5303. return nullptr;
  5304. }
  5305. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5306. auto OrderedClauses =
  5307. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  5308. if (OrderedClauses.begin() != OrderedClauses.end())
  5309. return (*OrderedClauses.begin())->getNumForLoops();
  5310. return nullptr;
  5311. }
  5312. static bool checkSimdlenSafelenSpecified(Sema &S,
  5313. const ArrayRef<OMPClause *> Clauses) {
  5314. const OMPSafelenClause *Safelen = nullptr;
  5315. const OMPSimdlenClause *Simdlen = nullptr;
  5316. for (const OMPClause *Clause : Clauses) {
  5317. if (Clause->getClauseKind() == OMPC_safelen)
  5318. Safelen = cast<OMPSafelenClause>(Clause);
  5319. else if (Clause->getClauseKind() == OMPC_simdlen)
  5320. Simdlen = cast<OMPSimdlenClause>(Clause);
  5321. if (Safelen && Simdlen)
  5322. break;
  5323. }
  5324. if (Simdlen && Safelen) {
  5325. const Expr *SimdlenLength = Simdlen->getSimdlen();
  5326. const Expr *SafelenLength = Safelen->getSafelen();
  5327. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  5328. SimdlenLength->isInstantiationDependent() ||
  5329. SimdlenLength->containsUnexpandedParameterPack())
  5330. return false;
  5331. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  5332. SafelenLength->isInstantiationDependent() ||
  5333. SafelenLength->containsUnexpandedParameterPack())
  5334. return false;
  5335. Expr::EvalResult SimdlenResult, SafelenResult;
  5336. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  5337. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  5338. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  5339. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  5340. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  5341. // If both simdlen and safelen clauses are specified, the value of the
  5342. // simdlen parameter must be less than or equal to the value of the safelen
  5343. // parameter.
  5344. if (SimdlenRes > SafelenRes) {
  5345. S.Diag(SimdlenLength->getExprLoc(),
  5346. diag::err_omp_wrong_simdlen_safelen_values)
  5347. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  5348. return true;
  5349. }
  5350. }
  5351. return false;
  5352. }
  5353. StmtResult
  5354. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5355. SourceLocation StartLoc, SourceLocation EndLoc,
  5356. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5357. if (!AStmt)
  5358. return StmtError();
  5359. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5360. OMPLoopDirective::HelperExprs B;
  5361. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5362. // define the nested loops number.
  5363. unsigned NestedLoopCount = checkOpenMPLoop(
  5364. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5365. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5366. if (NestedLoopCount == 0)
  5367. return StmtError();
  5368. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5369. "omp simd loop exprs were not built");
  5370. if (!CurContext->isDependentContext()) {
  5371. // Finalize the clauses that need pre-built expressions for CodeGen.
  5372. for (OMPClause *C : Clauses) {
  5373. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5374. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5375. B.NumIterations, *this, CurScope,
  5376. DSAStack))
  5377. return StmtError();
  5378. }
  5379. }
  5380. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5381. return StmtError();
  5382. setFunctionHasBranchProtectedScope();
  5383. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5384. Clauses, AStmt, B);
  5385. }
  5386. StmtResult
  5387. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5388. SourceLocation StartLoc, SourceLocation EndLoc,
  5389. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5390. if (!AStmt)
  5391. return StmtError();
  5392. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5393. OMPLoopDirective::HelperExprs B;
  5394. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5395. // define the nested loops number.
  5396. unsigned NestedLoopCount = checkOpenMPLoop(
  5397. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5398. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5399. if (NestedLoopCount == 0)
  5400. return StmtError();
  5401. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5402. "omp for loop exprs were not built");
  5403. if (!CurContext->isDependentContext()) {
  5404. // Finalize the clauses that need pre-built expressions for CodeGen.
  5405. for (OMPClause *C : Clauses) {
  5406. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5407. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5408. B.NumIterations, *this, CurScope,
  5409. DSAStack))
  5410. return StmtError();
  5411. }
  5412. }
  5413. setFunctionHasBranchProtectedScope();
  5414. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5415. Clauses, AStmt, B, DSAStack->isCancelRegion());
  5416. }
  5417. StmtResult Sema::ActOnOpenMPForSimdDirective(
  5418. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5419. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5420. if (!AStmt)
  5421. return StmtError();
  5422. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5423. OMPLoopDirective::HelperExprs B;
  5424. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5425. // define the nested loops number.
  5426. unsigned NestedLoopCount =
  5427. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  5428. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5429. VarsWithImplicitDSA, B);
  5430. if (NestedLoopCount == 0)
  5431. return StmtError();
  5432. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5433. "omp for simd loop exprs were not built");
  5434. if (!CurContext->isDependentContext()) {
  5435. // Finalize the clauses that need pre-built expressions for CodeGen.
  5436. for (OMPClause *C : Clauses) {
  5437. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5438. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5439. B.NumIterations, *this, CurScope,
  5440. DSAStack))
  5441. return StmtError();
  5442. }
  5443. }
  5444. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5445. return StmtError();
  5446. setFunctionHasBranchProtectedScope();
  5447. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5448. Clauses, AStmt, B);
  5449. }
  5450. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5451. Stmt *AStmt,
  5452. SourceLocation StartLoc,
  5453. SourceLocation EndLoc) {
  5454. if (!AStmt)
  5455. return StmtError();
  5456. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5457. auto BaseStmt = AStmt;
  5458. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5459. BaseStmt = CS->getCapturedStmt();
  5460. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5461. auto S = C->children();
  5462. if (S.begin() == S.end())
  5463. return StmtError();
  5464. // All associated statements must be '#pragma omp section' except for
  5465. // the first one.
  5466. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5467. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5468. if (SectionStmt)
  5469. Diag(SectionStmt->getBeginLoc(),
  5470. diag::err_omp_sections_substmt_not_section);
  5471. return StmtError();
  5472. }
  5473. cast<OMPSectionDirective>(SectionStmt)
  5474. ->setHasCancel(DSAStack->isCancelRegion());
  5475. }
  5476. } else {
  5477. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  5478. return StmtError();
  5479. }
  5480. setFunctionHasBranchProtectedScope();
  5481. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5482. DSAStack->isCancelRegion());
  5483. }
  5484. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  5485. SourceLocation StartLoc,
  5486. SourceLocation EndLoc) {
  5487. if (!AStmt)
  5488. return StmtError();
  5489. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5490. setFunctionHasBranchProtectedScope();
  5491. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  5492. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  5493. DSAStack->isCancelRegion());
  5494. }
  5495. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  5496. Stmt *AStmt,
  5497. SourceLocation StartLoc,
  5498. SourceLocation EndLoc) {
  5499. if (!AStmt)
  5500. return StmtError();
  5501. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5502. setFunctionHasBranchProtectedScope();
  5503. // OpenMP [2.7.3, single Construct, Restrictions]
  5504. // The copyprivate clause must not be used with the nowait clause.
  5505. const OMPClause *Nowait = nullptr;
  5506. const OMPClause *Copyprivate = nullptr;
  5507. for (const OMPClause *Clause : Clauses) {
  5508. if (Clause->getClauseKind() == OMPC_nowait)
  5509. Nowait = Clause;
  5510. else if (Clause->getClauseKind() == OMPC_copyprivate)
  5511. Copyprivate = Clause;
  5512. if (Copyprivate && Nowait) {
  5513. Diag(Copyprivate->getBeginLoc(),
  5514. diag::err_omp_single_copyprivate_with_nowait);
  5515. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  5516. return StmtError();
  5517. }
  5518. }
  5519. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5520. }
  5521. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  5522. SourceLocation StartLoc,
  5523. SourceLocation EndLoc) {
  5524. if (!AStmt)
  5525. return StmtError();
  5526. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5527. setFunctionHasBranchProtectedScope();
  5528. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  5529. }
  5530. StmtResult Sema::ActOnOpenMPCriticalDirective(
  5531. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  5532. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  5533. if (!AStmt)
  5534. return StmtError();
  5535. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5536. bool ErrorFound = false;
  5537. llvm::APSInt Hint;
  5538. SourceLocation HintLoc;
  5539. bool DependentHint = false;
  5540. for (const OMPClause *C : Clauses) {
  5541. if (C->getClauseKind() == OMPC_hint) {
  5542. if (!DirName.getName()) {
  5543. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  5544. ErrorFound = true;
  5545. }
  5546. Expr *E = cast<OMPHintClause>(C)->getHint();
  5547. if (E->isTypeDependent() || E->isValueDependent() ||
  5548. E->isInstantiationDependent()) {
  5549. DependentHint = true;
  5550. } else {
  5551. Hint = E->EvaluateKnownConstInt(Context);
  5552. HintLoc = C->getBeginLoc();
  5553. }
  5554. }
  5555. }
  5556. if (ErrorFound)
  5557. return StmtError();
  5558. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  5559. if (Pair.first && DirName.getName() && !DependentHint) {
  5560. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  5561. Diag(StartLoc, diag::err_omp_critical_with_hint);
  5562. if (HintLoc.isValid())
  5563. Diag(HintLoc, diag::note_omp_critical_hint_here)
  5564. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  5565. else
  5566. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  5567. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  5568. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  5569. << 1
  5570. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  5571. /*Radix=*/10, /*Signed=*/false);
  5572. } else {
  5573. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  5574. }
  5575. }
  5576. }
  5577. setFunctionHasBranchProtectedScope();
  5578. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5579. Clauses, AStmt);
  5580. if (!Pair.first && DirName.getName() && !DependentHint)
  5581. DSAStack->addCriticalWithHint(Dir, Hint);
  5582. return Dir;
  5583. }
  5584. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5585. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5586. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5587. if (!AStmt)
  5588. return StmtError();
  5589. auto *CS = cast<CapturedStmt>(AStmt);
  5590. // 1.2.2 OpenMP Language Terminology
  5591. // Structured block - An executable statement with a single entry at the
  5592. // top and a single exit at the bottom.
  5593. // The point of exit cannot be a branch out of the structured block.
  5594. // longjmp() and throw() must not violate the entry/exit criteria.
  5595. CS->getCapturedDecl()->setNothrow();
  5596. OMPLoopDirective::HelperExprs B;
  5597. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5598. // define the nested loops number.
  5599. unsigned NestedLoopCount =
  5600. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5601. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5602. VarsWithImplicitDSA, B);
  5603. if (NestedLoopCount == 0)
  5604. return StmtError();
  5605. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5606. "omp parallel for loop exprs were not built");
  5607. if (!CurContext->isDependentContext()) {
  5608. // Finalize the clauses that need pre-built expressions for CodeGen.
  5609. for (OMPClause *C : Clauses) {
  5610. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5611. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5612. B.NumIterations, *this, CurScope,
  5613. DSAStack))
  5614. return StmtError();
  5615. }
  5616. }
  5617. setFunctionHasBranchProtectedScope();
  5618. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5619. NestedLoopCount, Clauses, AStmt, B,
  5620. DSAStack->isCancelRegion());
  5621. }
  5622. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5623. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5624. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5625. if (!AStmt)
  5626. return StmtError();
  5627. auto *CS = cast<CapturedStmt>(AStmt);
  5628. // 1.2.2 OpenMP Language Terminology
  5629. // Structured block - An executable statement with a single entry at the
  5630. // top and a single exit at the bottom.
  5631. // The point of exit cannot be a branch out of the structured block.
  5632. // longjmp() and throw() must not violate the entry/exit criteria.
  5633. CS->getCapturedDecl()->setNothrow();
  5634. OMPLoopDirective::HelperExprs B;
  5635. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5636. // define the nested loops number.
  5637. unsigned NestedLoopCount =
  5638. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5639. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5640. VarsWithImplicitDSA, B);
  5641. if (NestedLoopCount == 0)
  5642. return StmtError();
  5643. if (!CurContext->isDependentContext()) {
  5644. // Finalize the clauses that need pre-built expressions for CodeGen.
  5645. for (OMPClause *C : Clauses) {
  5646. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5647. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5648. B.NumIterations, *this, CurScope,
  5649. DSAStack))
  5650. return StmtError();
  5651. }
  5652. }
  5653. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5654. return StmtError();
  5655. setFunctionHasBranchProtectedScope();
  5656. return OMPParallelForSimdDirective::Create(
  5657. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5658. }
  5659. StmtResult
  5660. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5661. Stmt *AStmt, SourceLocation StartLoc,
  5662. SourceLocation EndLoc) {
  5663. if (!AStmt)
  5664. return StmtError();
  5665. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5666. auto BaseStmt = AStmt;
  5667. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5668. BaseStmt = CS->getCapturedStmt();
  5669. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5670. auto S = C->children();
  5671. if (S.begin() == S.end())
  5672. return StmtError();
  5673. // All associated statements must be '#pragma omp section' except for
  5674. // the first one.
  5675. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5676. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5677. if (SectionStmt)
  5678. Diag(SectionStmt->getBeginLoc(),
  5679. diag::err_omp_parallel_sections_substmt_not_section);
  5680. return StmtError();
  5681. }
  5682. cast<OMPSectionDirective>(SectionStmt)
  5683. ->setHasCancel(DSAStack->isCancelRegion());
  5684. }
  5685. } else {
  5686. Diag(AStmt->getBeginLoc(),
  5687. diag::err_omp_parallel_sections_not_compound_stmt);
  5688. return StmtError();
  5689. }
  5690. setFunctionHasBranchProtectedScope();
  5691. return OMPParallelSectionsDirective::Create(
  5692. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5693. }
  5694. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5695. Stmt *AStmt, SourceLocation StartLoc,
  5696. SourceLocation EndLoc) {
  5697. if (!AStmt)
  5698. return StmtError();
  5699. auto *CS = cast<CapturedStmt>(AStmt);
  5700. // 1.2.2 OpenMP Language Terminology
  5701. // Structured block - An executable statement with a single entry at the
  5702. // top and a single exit at the bottom.
  5703. // The point of exit cannot be a branch out of the structured block.
  5704. // longjmp() and throw() must not violate the entry/exit criteria.
  5705. CS->getCapturedDecl()->setNothrow();
  5706. setFunctionHasBranchProtectedScope();
  5707. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5708. DSAStack->isCancelRegion());
  5709. }
  5710. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5711. SourceLocation EndLoc) {
  5712. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5713. }
  5714. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5715. SourceLocation EndLoc) {
  5716. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5717. }
  5718. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5719. SourceLocation EndLoc) {
  5720. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5721. }
  5722. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5723. Stmt *AStmt,
  5724. SourceLocation StartLoc,
  5725. SourceLocation EndLoc) {
  5726. if (!AStmt)
  5727. return StmtError();
  5728. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5729. setFunctionHasBranchProtectedScope();
  5730. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5731. AStmt,
  5732. DSAStack->getTaskgroupReductionRef());
  5733. }
  5734. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5735. SourceLocation StartLoc,
  5736. SourceLocation EndLoc) {
  5737. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5738. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5739. }
  5740. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5741. Stmt *AStmt,
  5742. SourceLocation StartLoc,
  5743. SourceLocation EndLoc) {
  5744. const OMPClause *DependFound = nullptr;
  5745. const OMPClause *DependSourceClause = nullptr;
  5746. const OMPClause *DependSinkClause = nullptr;
  5747. bool ErrorFound = false;
  5748. const OMPThreadsClause *TC = nullptr;
  5749. const OMPSIMDClause *SC = nullptr;
  5750. for (const OMPClause *C : Clauses) {
  5751. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5752. DependFound = C;
  5753. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5754. if (DependSourceClause) {
  5755. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  5756. << getOpenMPDirectiveName(OMPD_ordered)
  5757. << getOpenMPClauseName(OMPC_depend) << 2;
  5758. ErrorFound = true;
  5759. } else {
  5760. DependSourceClause = C;
  5761. }
  5762. if (DependSinkClause) {
  5763. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  5764. << 0;
  5765. ErrorFound = true;
  5766. }
  5767. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5768. if (DependSourceClause) {
  5769. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  5770. << 1;
  5771. ErrorFound = true;
  5772. }
  5773. DependSinkClause = C;
  5774. }
  5775. } else if (C->getClauseKind() == OMPC_threads) {
  5776. TC = cast<OMPThreadsClause>(C);
  5777. } else if (C->getClauseKind() == OMPC_simd) {
  5778. SC = cast<OMPSIMDClause>(C);
  5779. }
  5780. }
  5781. if (!ErrorFound && !SC &&
  5782. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5783. // OpenMP [2.8.1,simd Construct, Restrictions]
  5784. // An ordered construct with the simd clause is the only OpenMP construct
  5785. // that can appear in the simd region.
  5786. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5787. ErrorFound = true;
  5788. } else if (DependFound && (TC || SC)) {
  5789. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  5790. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5791. ErrorFound = true;
  5792. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  5793. Diag(DependFound->getBeginLoc(),
  5794. diag::err_omp_ordered_directive_without_param);
  5795. ErrorFound = true;
  5796. } else if (TC || Clauses.empty()) {
  5797. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  5798. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  5799. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5800. << (TC != nullptr);
  5801. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  5802. ErrorFound = true;
  5803. }
  5804. }
  5805. if ((!AStmt && !DependFound) || ErrorFound)
  5806. return StmtError();
  5807. if (AStmt) {
  5808. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5809. setFunctionHasBranchProtectedScope();
  5810. }
  5811. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5812. }
  5813. namespace {
  5814. /// Helper class for checking expression in 'omp atomic [update]'
  5815. /// construct.
  5816. class OpenMPAtomicUpdateChecker {
  5817. /// Error results for atomic update expressions.
  5818. enum ExprAnalysisErrorCode {
  5819. /// A statement is not an expression statement.
  5820. NotAnExpression,
  5821. /// Expression is not builtin binary or unary operation.
  5822. NotABinaryOrUnaryExpression,
  5823. /// Unary operation is not post-/pre- increment/decrement operation.
  5824. NotAnUnaryIncDecExpression,
  5825. /// An expression is not of scalar type.
  5826. NotAScalarType,
  5827. /// A binary operation is not an assignment operation.
  5828. NotAnAssignmentOp,
  5829. /// RHS part of the binary operation is not a binary expression.
  5830. NotABinaryExpression,
  5831. /// RHS part is not additive/multiplicative/shift/biwise binary
  5832. /// expression.
  5833. NotABinaryOperator,
  5834. /// RHS binary operation does not have reference to the updated LHS
  5835. /// part.
  5836. NotAnUpdateExpression,
  5837. /// No errors is found.
  5838. NoError
  5839. };
  5840. /// Reference to Sema.
  5841. Sema &SemaRef;
  5842. /// A location for note diagnostics (when error is found).
  5843. SourceLocation NoteLoc;
  5844. /// 'x' lvalue part of the source atomic expression.
  5845. Expr *X;
  5846. /// 'expr' rvalue part of the source atomic expression.
  5847. Expr *E;
  5848. /// Helper expression of the form
  5849. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5850. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5851. Expr *UpdateExpr;
  5852. /// Is 'x' a LHS in a RHS part of full update expression. It is
  5853. /// important for non-associative operations.
  5854. bool IsXLHSInRHSPart;
  5855. BinaryOperatorKind Op;
  5856. SourceLocation OpLoc;
  5857. /// true if the source expression is a postfix unary operation, false
  5858. /// if it is a prefix unary operation.
  5859. bool IsPostfixUpdate;
  5860. public:
  5861. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5862. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5863. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5864. /// Check specified statement that it is suitable for 'atomic update'
  5865. /// constructs and extract 'x', 'expr' and Operation from the original
  5866. /// expression. If DiagId and NoteId == 0, then only check is performed
  5867. /// without error notification.
  5868. /// \param DiagId Diagnostic which should be emitted if error is found.
  5869. /// \param NoteId Diagnostic note for the main error message.
  5870. /// \return true if statement is not an update expression, false otherwise.
  5871. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5872. /// Return the 'x' lvalue part of the source atomic expression.
  5873. Expr *getX() const { return X; }
  5874. /// Return the 'expr' rvalue part of the source atomic expression.
  5875. Expr *getExpr() const { return E; }
  5876. /// Return the update expression used in calculation of the updated
  5877. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5878. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5879. Expr *getUpdateExpr() const { return UpdateExpr; }
  5880. /// Return true if 'x' is LHS in RHS part of full update expression,
  5881. /// false otherwise.
  5882. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5883. /// true if the source expression is a postfix unary operation, false
  5884. /// if it is a prefix unary operation.
  5885. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5886. private:
  5887. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5888. unsigned NoteId = 0);
  5889. };
  5890. } // namespace
  5891. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5892. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5893. ExprAnalysisErrorCode ErrorFound = NoError;
  5894. SourceLocation ErrorLoc, NoteLoc;
  5895. SourceRange ErrorRange, NoteRange;
  5896. // Allowed constructs are:
  5897. // x = x binop expr;
  5898. // x = expr binop x;
  5899. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5900. X = AtomicBinOp->getLHS();
  5901. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5902. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5903. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5904. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5905. AtomicInnerBinOp->isBitwiseOp()) {
  5906. Op = AtomicInnerBinOp->getOpcode();
  5907. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5908. Expr *LHS = AtomicInnerBinOp->getLHS();
  5909. Expr *RHS = AtomicInnerBinOp->getRHS();
  5910. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5911. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5912. /*Canonical=*/true);
  5913. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5914. /*Canonical=*/true);
  5915. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5916. /*Canonical=*/true);
  5917. if (XId == LHSId) {
  5918. E = RHS;
  5919. IsXLHSInRHSPart = true;
  5920. } else if (XId == RHSId) {
  5921. E = LHS;
  5922. IsXLHSInRHSPart = false;
  5923. } else {
  5924. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5925. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5926. NoteLoc = X->getExprLoc();
  5927. NoteRange = X->getSourceRange();
  5928. ErrorFound = NotAnUpdateExpression;
  5929. }
  5930. } else {
  5931. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5932. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5933. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5934. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5935. ErrorFound = NotABinaryOperator;
  5936. }
  5937. } else {
  5938. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5939. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5940. ErrorFound = NotABinaryExpression;
  5941. }
  5942. } else {
  5943. ErrorLoc = AtomicBinOp->getExprLoc();
  5944. ErrorRange = AtomicBinOp->getSourceRange();
  5945. NoteLoc = AtomicBinOp->getOperatorLoc();
  5946. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5947. ErrorFound = NotAnAssignmentOp;
  5948. }
  5949. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5950. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5951. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5952. return true;
  5953. }
  5954. if (SemaRef.CurContext->isDependentContext())
  5955. E = X = UpdateExpr = nullptr;
  5956. return ErrorFound != NoError;
  5957. }
  5958. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5959. unsigned NoteId) {
  5960. ExprAnalysisErrorCode ErrorFound = NoError;
  5961. SourceLocation ErrorLoc, NoteLoc;
  5962. SourceRange ErrorRange, NoteRange;
  5963. // Allowed constructs are:
  5964. // x++;
  5965. // x--;
  5966. // ++x;
  5967. // --x;
  5968. // x binop= expr;
  5969. // x = x binop expr;
  5970. // x = expr binop x;
  5971. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5972. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5973. if (AtomicBody->getType()->isScalarType() ||
  5974. AtomicBody->isInstantiationDependent()) {
  5975. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5976. AtomicBody->IgnoreParenImpCasts())) {
  5977. // Check for Compound Assignment Operation
  5978. Op = BinaryOperator::getOpForCompoundAssignment(
  5979. AtomicCompAssignOp->getOpcode());
  5980. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5981. E = AtomicCompAssignOp->getRHS();
  5982. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5983. IsXLHSInRHSPart = true;
  5984. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5985. AtomicBody->IgnoreParenImpCasts())) {
  5986. // Check for Binary Operation
  5987. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5988. return true;
  5989. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5990. AtomicBody->IgnoreParenImpCasts())) {
  5991. // Check for Unary Operation
  5992. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5993. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5994. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5995. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5996. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5997. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5998. IsXLHSInRHSPart = true;
  5999. } else {
  6000. ErrorFound = NotAnUnaryIncDecExpression;
  6001. ErrorLoc = AtomicUnaryOp->getExprLoc();
  6002. ErrorRange = AtomicUnaryOp->getSourceRange();
  6003. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  6004. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6005. }
  6006. } else if (!AtomicBody->isInstantiationDependent()) {
  6007. ErrorFound = NotABinaryOrUnaryExpression;
  6008. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  6009. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  6010. }
  6011. } else {
  6012. ErrorFound = NotAScalarType;
  6013. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  6014. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6015. }
  6016. } else {
  6017. ErrorFound = NotAnExpression;
  6018. NoteLoc = ErrorLoc = S->getBeginLoc();
  6019. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6020. }
  6021. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6022. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6023. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6024. return true;
  6025. }
  6026. if (SemaRef.CurContext->isDependentContext())
  6027. E = X = UpdateExpr = nullptr;
  6028. if (ErrorFound == NoError && E && X) {
  6029. // Build an update expression of form 'OpaqueValueExpr(x) binop
  6030. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  6031. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  6032. auto *OVEX = new (SemaRef.getASTContext())
  6033. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  6034. auto *OVEExpr = new (SemaRef.getASTContext())
  6035. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  6036. ExprResult Update =
  6037. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  6038. IsXLHSInRHSPart ? OVEExpr : OVEX);
  6039. if (Update.isInvalid())
  6040. return true;
  6041. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  6042. Sema::AA_Casting);
  6043. if (Update.isInvalid())
  6044. return true;
  6045. UpdateExpr = Update.get();
  6046. }
  6047. return ErrorFound != NoError;
  6048. }
  6049. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  6050. Stmt *AStmt,
  6051. SourceLocation StartLoc,
  6052. SourceLocation EndLoc) {
  6053. if (!AStmt)
  6054. return StmtError();
  6055. auto *CS = cast<CapturedStmt>(AStmt);
  6056. // 1.2.2 OpenMP Language Terminology
  6057. // Structured block - An executable statement with a single entry at the
  6058. // top and a single exit at the bottom.
  6059. // The point of exit cannot be a branch out of the structured block.
  6060. // longjmp() and throw() must not violate the entry/exit criteria.
  6061. OpenMPClauseKind AtomicKind = OMPC_unknown;
  6062. SourceLocation AtomicKindLoc;
  6063. for (const OMPClause *C : Clauses) {
  6064. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  6065. C->getClauseKind() == OMPC_update ||
  6066. C->getClauseKind() == OMPC_capture) {
  6067. if (AtomicKind != OMPC_unknown) {
  6068. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  6069. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  6070. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  6071. << getOpenMPClauseName(AtomicKind);
  6072. } else {
  6073. AtomicKind = C->getClauseKind();
  6074. AtomicKindLoc = C->getBeginLoc();
  6075. }
  6076. }
  6077. }
  6078. Stmt *Body = CS->getCapturedStmt();
  6079. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  6080. Body = EWC->getSubExpr();
  6081. Expr *X = nullptr;
  6082. Expr *V = nullptr;
  6083. Expr *E = nullptr;
  6084. Expr *UE = nullptr;
  6085. bool IsXLHSInRHSPart = false;
  6086. bool IsPostfixUpdate = false;
  6087. // OpenMP [2.12.6, atomic Construct]
  6088. // In the next expressions:
  6089. // * x and v (as applicable) are both l-value expressions with scalar type.
  6090. // * During the execution of an atomic region, multiple syntactic
  6091. // occurrences of x must designate the same storage location.
  6092. // * Neither of v and expr (as applicable) may access the storage location
  6093. // designated by x.
  6094. // * Neither of x and expr (as applicable) may access the storage location
  6095. // designated by v.
  6096. // * expr is an expression with scalar type.
  6097. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  6098. // * binop, binop=, ++, and -- are not overloaded operators.
  6099. // * The expression x binop expr must be numerically equivalent to x binop
  6100. // (expr). This requirement is satisfied if the operators in expr have
  6101. // precedence greater than binop, or by using parentheses around expr or
  6102. // subexpressions of expr.
  6103. // * The expression expr binop x must be numerically equivalent to (expr)
  6104. // binop x. This requirement is satisfied if the operators in expr have
  6105. // precedence equal to or greater than binop, or by using parentheses around
  6106. // expr or subexpressions of expr.
  6107. // * For forms that allow multiple occurrences of x, the number of times
  6108. // that x is evaluated is unspecified.
  6109. if (AtomicKind == OMPC_read) {
  6110. enum {
  6111. NotAnExpression,
  6112. NotAnAssignmentOp,
  6113. NotAScalarType,
  6114. NotAnLValue,
  6115. NoError
  6116. } ErrorFound = NoError;
  6117. SourceLocation ErrorLoc, NoteLoc;
  6118. SourceRange ErrorRange, NoteRange;
  6119. // If clause is read:
  6120. // v = x;
  6121. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6122. const auto *AtomicBinOp =
  6123. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6124. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6125. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6126. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  6127. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6128. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  6129. if (!X->isLValue() || !V->isLValue()) {
  6130. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  6131. ErrorFound = NotAnLValue;
  6132. ErrorLoc = AtomicBinOp->getExprLoc();
  6133. ErrorRange = AtomicBinOp->getSourceRange();
  6134. NoteLoc = NotLValueExpr->getExprLoc();
  6135. NoteRange = NotLValueExpr->getSourceRange();
  6136. }
  6137. } else if (!X->isInstantiationDependent() ||
  6138. !V->isInstantiationDependent()) {
  6139. const Expr *NotScalarExpr =
  6140. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6141. ? V
  6142. : X;
  6143. ErrorFound = NotAScalarType;
  6144. ErrorLoc = AtomicBinOp->getExprLoc();
  6145. ErrorRange = AtomicBinOp->getSourceRange();
  6146. NoteLoc = NotScalarExpr->getExprLoc();
  6147. NoteRange = NotScalarExpr->getSourceRange();
  6148. }
  6149. } else if (!AtomicBody->isInstantiationDependent()) {
  6150. ErrorFound = NotAnAssignmentOp;
  6151. ErrorLoc = AtomicBody->getExprLoc();
  6152. ErrorRange = AtomicBody->getSourceRange();
  6153. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6154. : AtomicBody->getExprLoc();
  6155. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6156. : AtomicBody->getSourceRange();
  6157. }
  6158. } else {
  6159. ErrorFound = NotAnExpression;
  6160. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6161. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6162. }
  6163. if (ErrorFound != NoError) {
  6164. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  6165. << ErrorRange;
  6166. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6167. << NoteRange;
  6168. return StmtError();
  6169. }
  6170. if (CurContext->isDependentContext())
  6171. V = X = nullptr;
  6172. } else if (AtomicKind == OMPC_write) {
  6173. enum {
  6174. NotAnExpression,
  6175. NotAnAssignmentOp,
  6176. NotAScalarType,
  6177. NotAnLValue,
  6178. NoError
  6179. } ErrorFound = NoError;
  6180. SourceLocation ErrorLoc, NoteLoc;
  6181. SourceRange ErrorRange, NoteRange;
  6182. // If clause is write:
  6183. // x = expr;
  6184. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6185. const auto *AtomicBinOp =
  6186. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6187. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6188. X = AtomicBinOp->getLHS();
  6189. E = AtomicBinOp->getRHS();
  6190. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6191. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  6192. if (!X->isLValue()) {
  6193. ErrorFound = NotAnLValue;
  6194. ErrorLoc = AtomicBinOp->getExprLoc();
  6195. ErrorRange = AtomicBinOp->getSourceRange();
  6196. NoteLoc = X->getExprLoc();
  6197. NoteRange = X->getSourceRange();
  6198. }
  6199. } else if (!X->isInstantiationDependent() ||
  6200. !E->isInstantiationDependent()) {
  6201. const Expr *NotScalarExpr =
  6202. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6203. ? E
  6204. : X;
  6205. ErrorFound = NotAScalarType;
  6206. ErrorLoc = AtomicBinOp->getExprLoc();
  6207. ErrorRange = AtomicBinOp->getSourceRange();
  6208. NoteLoc = NotScalarExpr->getExprLoc();
  6209. NoteRange = NotScalarExpr->getSourceRange();
  6210. }
  6211. } else if (!AtomicBody->isInstantiationDependent()) {
  6212. ErrorFound = NotAnAssignmentOp;
  6213. ErrorLoc = AtomicBody->getExprLoc();
  6214. ErrorRange = AtomicBody->getSourceRange();
  6215. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6216. : AtomicBody->getExprLoc();
  6217. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6218. : AtomicBody->getSourceRange();
  6219. }
  6220. } else {
  6221. ErrorFound = NotAnExpression;
  6222. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6223. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6224. }
  6225. if (ErrorFound != NoError) {
  6226. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  6227. << ErrorRange;
  6228. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6229. << NoteRange;
  6230. return StmtError();
  6231. }
  6232. if (CurContext->isDependentContext())
  6233. E = X = nullptr;
  6234. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  6235. // If clause is update:
  6236. // x++;
  6237. // x--;
  6238. // ++x;
  6239. // --x;
  6240. // x binop= expr;
  6241. // x = x binop expr;
  6242. // x = expr binop x;
  6243. OpenMPAtomicUpdateChecker Checker(*this);
  6244. if (Checker.checkStatement(
  6245. Body, (AtomicKind == OMPC_update)
  6246. ? diag::err_omp_atomic_update_not_expression_statement
  6247. : diag::err_omp_atomic_not_expression_statement,
  6248. diag::note_omp_atomic_update))
  6249. return StmtError();
  6250. if (!CurContext->isDependentContext()) {
  6251. E = Checker.getExpr();
  6252. X = Checker.getX();
  6253. UE = Checker.getUpdateExpr();
  6254. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6255. }
  6256. } else if (AtomicKind == OMPC_capture) {
  6257. enum {
  6258. NotAnAssignmentOp,
  6259. NotACompoundStatement,
  6260. NotTwoSubstatements,
  6261. NotASpecificExpression,
  6262. NoError
  6263. } ErrorFound = NoError;
  6264. SourceLocation ErrorLoc, NoteLoc;
  6265. SourceRange ErrorRange, NoteRange;
  6266. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6267. // If clause is a capture:
  6268. // v = x++;
  6269. // v = x--;
  6270. // v = ++x;
  6271. // v = --x;
  6272. // v = x binop= expr;
  6273. // v = x = x binop expr;
  6274. // v = x = expr binop x;
  6275. const auto *AtomicBinOp =
  6276. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6277. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6278. V = AtomicBinOp->getLHS();
  6279. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6280. OpenMPAtomicUpdateChecker Checker(*this);
  6281. if (Checker.checkStatement(
  6282. Body, diag::err_omp_atomic_capture_not_expression_statement,
  6283. diag::note_omp_atomic_update))
  6284. return StmtError();
  6285. E = Checker.getExpr();
  6286. X = Checker.getX();
  6287. UE = Checker.getUpdateExpr();
  6288. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6289. IsPostfixUpdate = Checker.isPostfixUpdate();
  6290. } else if (!AtomicBody->isInstantiationDependent()) {
  6291. ErrorLoc = AtomicBody->getExprLoc();
  6292. ErrorRange = AtomicBody->getSourceRange();
  6293. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6294. : AtomicBody->getExprLoc();
  6295. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6296. : AtomicBody->getSourceRange();
  6297. ErrorFound = NotAnAssignmentOp;
  6298. }
  6299. if (ErrorFound != NoError) {
  6300. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  6301. << ErrorRange;
  6302. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6303. return StmtError();
  6304. }
  6305. if (CurContext->isDependentContext())
  6306. UE = V = E = X = nullptr;
  6307. } else {
  6308. // If clause is a capture:
  6309. // { v = x; x = expr; }
  6310. // { v = x; x++; }
  6311. // { v = x; x--; }
  6312. // { v = x; ++x; }
  6313. // { v = x; --x; }
  6314. // { v = x; x binop= expr; }
  6315. // { v = x; x = x binop expr; }
  6316. // { v = x; x = expr binop x; }
  6317. // { x++; v = x; }
  6318. // { x--; v = x; }
  6319. // { ++x; v = x; }
  6320. // { --x; v = x; }
  6321. // { x binop= expr; v = x; }
  6322. // { x = x binop expr; v = x; }
  6323. // { x = expr binop x; v = x; }
  6324. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  6325. // Check that this is { expr1; expr2; }
  6326. if (CS->size() == 2) {
  6327. Stmt *First = CS->body_front();
  6328. Stmt *Second = CS->body_back();
  6329. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  6330. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  6331. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  6332. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  6333. // Need to find what subexpression is 'v' and what is 'x'.
  6334. OpenMPAtomicUpdateChecker Checker(*this);
  6335. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  6336. BinaryOperator *BinOp = nullptr;
  6337. if (IsUpdateExprFound) {
  6338. BinOp = dyn_cast<BinaryOperator>(First);
  6339. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6340. }
  6341. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6342. // { v = x; x++; }
  6343. // { v = x; x--; }
  6344. // { v = x; ++x; }
  6345. // { v = x; --x; }
  6346. // { v = x; x binop= expr; }
  6347. // { v = x; x = x binop expr; }
  6348. // { v = x; x = expr binop x; }
  6349. // Check that the first expression has form v = x.
  6350. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6351. llvm::FoldingSetNodeID XId, PossibleXId;
  6352. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6353. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6354. IsUpdateExprFound = XId == PossibleXId;
  6355. if (IsUpdateExprFound) {
  6356. V = BinOp->getLHS();
  6357. X = Checker.getX();
  6358. E = Checker.getExpr();
  6359. UE = Checker.getUpdateExpr();
  6360. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6361. IsPostfixUpdate = true;
  6362. }
  6363. }
  6364. if (!IsUpdateExprFound) {
  6365. IsUpdateExprFound = !Checker.checkStatement(First);
  6366. BinOp = nullptr;
  6367. if (IsUpdateExprFound) {
  6368. BinOp = dyn_cast<BinaryOperator>(Second);
  6369. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6370. }
  6371. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6372. // { x++; v = x; }
  6373. // { x--; v = x; }
  6374. // { ++x; v = x; }
  6375. // { --x; v = x; }
  6376. // { x binop= expr; v = x; }
  6377. // { x = x binop expr; v = x; }
  6378. // { x = expr binop x; v = x; }
  6379. // Check that the second expression has form v = x.
  6380. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6381. llvm::FoldingSetNodeID XId, PossibleXId;
  6382. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6383. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6384. IsUpdateExprFound = XId == PossibleXId;
  6385. if (IsUpdateExprFound) {
  6386. V = BinOp->getLHS();
  6387. X = Checker.getX();
  6388. E = Checker.getExpr();
  6389. UE = Checker.getUpdateExpr();
  6390. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6391. IsPostfixUpdate = false;
  6392. }
  6393. }
  6394. }
  6395. if (!IsUpdateExprFound) {
  6396. // { v = x; x = expr; }
  6397. auto *FirstExpr = dyn_cast<Expr>(First);
  6398. auto *SecondExpr = dyn_cast<Expr>(Second);
  6399. if (!FirstExpr || !SecondExpr ||
  6400. !(FirstExpr->isInstantiationDependent() ||
  6401. SecondExpr->isInstantiationDependent())) {
  6402. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  6403. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  6404. ErrorFound = NotAnAssignmentOp;
  6405. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  6406. : First->getBeginLoc();
  6407. NoteRange = ErrorRange = FirstBinOp
  6408. ? FirstBinOp->getSourceRange()
  6409. : SourceRange(ErrorLoc, ErrorLoc);
  6410. } else {
  6411. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  6412. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  6413. ErrorFound = NotAnAssignmentOp;
  6414. NoteLoc = ErrorLoc = SecondBinOp
  6415. ? SecondBinOp->getOperatorLoc()
  6416. : Second->getBeginLoc();
  6417. NoteRange = ErrorRange =
  6418. SecondBinOp ? SecondBinOp->getSourceRange()
  6419. : SourceRange(ErrorLoc, ErrorLoc);
  6420. } else {
  6421. Expr *PossibleXRHSInFirst =
  6422. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  6423. Expr *PossibleXLHSInSecond =
  6424. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  6425. llvm::FoldingSetNodeID X1Id, X2Id;
  6426. PossibleXRHSInFirst->Profile(X1Id, Context,
  6427. /*Canonical=*/true);
  6428. PossibleXLHSInSecond->Profile(X2Id, Context,
  6429. /*Canonical=*/true);
  6430. IsUpdateExprFound = X1Id == X2Id;
  6431. if (IsUpdateExprFound) {
  6432. V = FirstBinOp->getLHS();
  6433. X = SecondBinOp->getLHS();
  6434. E = SecondBinOp->getRHS();
  6435. UE = nullptr;
  6436. IsXLHSInRHSPart = false;
  6437. IsPostfixUpdate = true;
  6438. } else {
  6439. ErrorFound = NotASpecificExpression;
  6440. ErrorLoc = FirstBinOp->getExprLoc();
  6441. ErrorRange = FirstBinOp->getSourceRange();
  6442. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  6443. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  6444. }
  6445. }
  6446. }
  6447. }
  6448. }
  6449. } else {
  6450. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6451. NoteRange = ErrorRange =
  6452. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6453. ErrorFound = NotTwoSubstatements;
  6454. }
  6455. } else {
  6456. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6457. NoteRange = ErrorRange =
  6458. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6459. ErrorFound = NotACompoundStatement;
  6460. }
  6461. if (ErrorFound != NoError) {
  6462. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  6463. << ErrorRange;
  6464. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6465. return StmtError();
  6466. }
  6467. if (CurContext->isDependentContext())
  6468. UE = V = E = X = nullptr;
  6469. }
  6470. }
  6471. setFunctionHasBranchProtectedScope();
  6472. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6473. X, V, E, UE, IsXLHSInRHSPart,
  6474. IsPostfixUpdate);
  6475. }
  6476. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  6477. Stmt *AStmt,
  6478. SourceLocation StartLoc,
  6479. SourceLocation EndLoc) {
  6480. if (!AStmt)
  6481. return StmtError();
  6482. auto *CS = cast<CapturedStmt>(AStmt);
  6483. // 1.2.2 OpenMP Language Terminology
  6484. // Structured block - An executable statement with a single entry at the
  6485. // top and a single exit at the bottom.
  6486. // The point of exit cannot be a branch out of the structured block.
  6487. // longjmp() and throw() must not violate the entry/exit criteria.
  6488. CS->getCapturedDecl()->setNothrow();
  6489. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  6490. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6491. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6492. // 1.2.2 OpenMP Language Terminology
  6493. // Structured block - An executable statement with a single entry at the
  6494. // top and a single exit at the bottom.
  6495. // The point of exit cannot be a branch out of the structured block.
  6496. // longjmp() and throw() must not violate the entry/exit criteria.
  6497. CS->getCapturedDecl()->setNothrow();
  6498. }
  6499. // OpenMP [2.16, Nesting of Regions]
  6500. // If specified, a teams construct must be contained within a target
  6501. // construct. That target construct must contain no statements or directives
  6502. // outside of the teams construct.
  6503. if (DSAStack->hasInnerTeamsRegion()) {
  6504. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  6505. bool OMPTeamsFound = true;
  6506. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  6507. auto I = CS->body_begin();
  6508. while (I != CS->body_end()) {
  6509. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  6510. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  6511. OMPTeamsFound = false;
  6512. break;
  6513. }
  6514. ++I;
  6515. }
  6516. assert(I != CS->body_end() && "Not found statement");
  6517. S = *I;
  6518. } else {
  6519. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  6520. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  6521. }
  6522. if (!OMPTeamsFound) {
  6523. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  6524. Diag(DSAStack->getInnerTeamsRegionLoc(),
  6525. diag::note_omp_nested_teams_construct_here);
  6526. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  6527. << isa<OMPExecutableDirective>(S);
  6528. return StmtError();
  6529. }
  6530. }
  6531. setFunctionHasBranchProtectedScope();
  6532. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6533. }
  6534. StmtResult
  6535. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  6536. Stmt *AStmt, SourceLocation StartLoc,
  6537. SourceLocation EndLoc) {
  6538. if (!AStmt)
  6539. return StmtError();
  6540. auto *CS = cast<CapturedStmt>(AStmt);
  6541. // 1.2.2 OpenMP Language Terminology
  6542. // Structured block - An executable statement with a single entry at the
  6543. // top and a single exit at the bottom.
  6544. // The point of exit cannot be a branch out of the structured block.
  6545. // longjmp() and throw() must not violate the entry/exit criteria.
  6546. CS->getCapturedDecl()->setNothrow();
  6547. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  6548. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6549. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6550. // 1.2.2 OpenMP Language Terminology
  6551. // Structured block - An executable statement with a single entry at the
  6552. // top and a single exit at the bottom.
  6553. // The point of exit cannot be a branch out of the structured block.
  6554. // longjmp() and throw() must not violate the entry/exit criteria.
  6555. CS->getCapturedDecl()->setNothrow();
  6556. }
  6557. setFunctionHasBranchProtectedScope();
  6558. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6559. AStmt);
  6560. }
  6561. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  6562. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6563. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6564. if (!AStmt)
  6565. return StmtError();
  6566. auto *CS = cast<CapturedStmt>(AStmt);
  6567. // 1.2.2 OpenMP Language Terminology
  6568. // Structured block - An executable statement with a single entry at the
  6569. // top and a single exit at the bottom.
  6570. // The point of exit cannot be a branch out of the structured block.
  6571. // longjmp() and throw() must not violate the entry/exit criteria.
  6572. CS->getCapturedDecl()->setNothrow();
  6573. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6574. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6575. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6576. // 1.2.2 OpenMP Language Terminology
  6577. // Structured block - An executable statement with a single entry at the
  6578. // top and a single exit at the bottom.
  6579. // The point of exit cannot be a branch out of the structured block.
  6580. // longjmp() and throw() must not violate the entry/exit criteria.
  6581. CS->getCapturedDecl()->setNothrow();
  6582. }
  6583. OMPLoopDirective::HelperExprs B;
  6584. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6585. // define the nested loops number.
  6586. unsigned NestedLoopCount =
  6587. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  6588. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6589. VarsWithImplicitDSA, B);
  6590. if (NestedLoopCount == 0)
  6591. return StmtError();
  6592. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6593. "omp target parallel for loop exprs were not built");
  6594. if (!CurContext->isDependentContext()) {
  6595. // Finalize the clauses that need pre-built expressions for CodeGen.
  6596. for (OMPClause *C : Clauses) {
  6597. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6598. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6599. B.NumIterations, *this, CurScope,
  6600. DSAStack))
  6601. return StmtError();
  6602. }
  6603. }
  6604. setFunctionHasBranchProtectedScope();
  6605. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6606. NestedLoopCount, Clauses, AStmt,
  6607. B, DSAStack->isCancelRegion());
  6608. }
  6609. /// Check for existence of a map clause in the list of clauses.
  6610. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6611. const OpenMPClauseKind K) {
  6612. return llvm::any_of(
  6613. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6614. }
  6615. template <typename... Params>
  6616. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6617. const Params... ClauseTypes) {
  6618. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6619. }
  6620. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6621. Stmt *AStmt,
  6622. SourceLocation StartLoc,
  6623. SourceLocation EndLoc) {
  6624. if (!AStmt)
  6625. return StmtError();
  6626. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6627. // OpenMP [2.10.1, Restrictions, p. 97]
  6628. // At least one map clause must appear on the directive.
  6629. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6630. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6631. << "'map' or 'use_device_ptr'"
  6632. << getOpenMPDirectiveName(OMPD_target_data);
  6633. return StmtError();
  6634. }
  6635. setFunctionHasBranchProtectedScope();
  6636. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6637. AStmt);
  6638. }
  6639. StmtResult
  6640. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6641. SourceLocation StartLoc,
  6642. SourceLocation EndLoc, Stmt *AStmt) {
  6643. if (!AStmt)
  6644. return StmtError();
  6645. auto *CS = cast<CapturedStmt>(AStmt);
  6646. // 1.2.2 OpenMP Language Terminology
  6647. // Structured block - An executable statement with a single entry at the
  6648. // top and a single exit at the bottom.
  6649. // The point of exit cannot be a branch out of the structured block.
  6650. // longjmp() and throw() must not violate the entry/exit criteria.
  6651. CS->getCapturedDecl()->setNothrow();
  6652. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6653. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6654. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6655. // 1.2.2 OpenMP Language Terminology
  6656. // Structured block - An executable statement with a single entry at the
  6657. // top and a single exit at the bottom.
  6658. // The point of exit cannot be a branch out of the structured block.
  6659. // longjmp() and throw() must not violate the entry/exit criteria.
  6660. CS->getCapturedDecl()->setNothrow();
  6661. }
  6662. // OpenMP [2.10.2, Restrictions, p. 99]
  6663. // At least one map clause must appear on the directive.
  6664. if (!hasClauses(Clauses, OMPC_map)) {
  6665. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6666. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6667. return StmtError();
  6668. }
  6669. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6670. AStmt);
  6671. }
  6672. StmtResult
  6673. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6674. SourceLocation StartLoc,
  6675. SourceLocation EndLoc, Stmt *AStmt) {
  6676. if (!AStmt)
  6677. return StmtError();
  6678. auto *CS = cast<CapturedStmt>(AStmt);
  6679. // 1.2.2 OpenMP Language Terminology
  6680. // Structured block - An executable statement with a single entry at the
  6681. // top and a single exit at the bottom.
  6682. // The point of exit cannot be a branch out of the structured block.
  6683. // longjmp() and throw() must not violate the entry/exit criteria.
  6684. CS->getCapturedDecl()->setNothrow();
  6685. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6686. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6687. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6688. // 1.2.2 OpenMP Language Terminology
  6689. // Structured block - An executable statement with a single entry at the
  6690. // top and a single exit at the bottom.
  6691. // The point of exit cannot be a branch out of the structured block.
  6692. // longjmp() and throw() must not violate the entry/exit criteria.
  6693. CS->getCapturedDecl()->setNothrow();
  6694. }
  6695. // OpenMP [2.10.3, Restrictions, p. 102]
  6696. // At least one map clause must appear on the directive.
  6697. if (!hasClauses(Clauses, OMPC_map)) {
  6698. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6699. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6700. return StmtError();
  6701. }
  6702. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6703. AStmt);
  6704. }
  6705. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6706. SourceLocation StartLoc,
  6707. SourceLocation EndLoc,
  6708. Stmt *AStmt) {
  6709. if (!AStmt)
  6710. return StmtError();
  6711. auto *CS = cast<CapturedStmt>(AStmt);
  6712. // 1.2.2 OpenMP Language Terminology
  6713. // Structured block - An executable statement with a single entry at the
  6714. // top and a single exit at the bottom.
  6715. // The point of exit cannot be a branch out of the structured block.
  6716. // longjmp() and throw() must not violate the entry/exit criteria.
  6717. CS->getCapturedDecl()->setNothrow();
  6718. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6719. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6720. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6721. // 1.2.2 OpenMP Language Terminology
  6722. // Structured block - An executable statement with a single entry at the
  6723. // top and a single exit at the bottom.
  6724. // The point of exit cannot be a branch out of the structured block.
  6725. // longjmp() and throw() must not violate the entry/exit criteria.
  6726. CS->getCapturedDecl()->setNothrow();
  6727. }
  6728. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6729. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6730. return StmtError();
  6731. }
  6732. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6733. AStmt);
  6734. }
  6735. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6736. Stmt *AStmt, SourceLocation StartLoc,
  6737. SourceLocation EndLoc) {
  6738. if (!AStmt)
  6739. return StmtError();
  6740. auto *CS = cast<CapturedStmt>(AStmt);
  6741. // 1.2.2 OpenMP Language Terminology
  6742. // Structured block - An executable statement with a single entry at the
  6743. // top and a single exit at the bottom.
  6744. // The point of exit cannot be a branch out of the structured block.
  6745. // longjmp() and throw() must not violate the entry/exit criteria.
  6746. CS->getCapturedDecl()->setNothrow();
  6747. setFunctionHasBranchProtectedScope();
  6748. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6749. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6750. }
  6751. StmtResult
  6752. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6753. SourceLocation EndLoc,
  6754. OpenMPDirectiveKind CancelRegion) {
  6755. if (DSAStack->isParentNowaitRegion()) {
  6756. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6757. return StmtError();
  6758. }
  6759. if (DSAStack->isParentOrderedRegion()) {
  6760. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6761. return StmtError();
  6762. }
  6763. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6764. CancelRegion);
  6765. }
  6766. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6767. SourceLocation StartLoc,
  6768. SourceLocation EndLoc,
  6769. OpenMPDirectiveKind CancelRegion) {
  6770. if (DSAStack->isParentNowaitRegion()) {
  6771. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6772. return StmtError();
  6773. }
  6774. if (DSAStack->isParentOrderedRegion()) {
  6775. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6776. return StmtError();
  6777. }
  6778. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6779. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6780. CancelRegion);
  6781. }
  6782. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6783. ArrayRef<OMPClause *> Clauses) {
  6784. const OMPClause *PrevClause = nullptr;
  6785. bool ErrorFound = false;
  6786. for (const OMPClause *C : Clauses) {
  6787. if (C->getClauseKind() == OMPC_grainsize ||
  6788. C->getClauseKind() == OMPC_num_tasks) {
  6789. if (!PrevClause)
  6790. PrevClause = C;
  6791. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6792. S.Diag(C->getBeginLoc(),
  6793. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6794. << getOpenMPClauseName(C->getClauseKind())
  6795. << getOpenMPClauseName(PrevClause->getClauseKind());
  6796. S.Diag(PrevClause->getBeginLoc(),
  6797. diag::note_omp_previous_grainsize_num_tasks)
  6798. << getOpenMPClauseName(PrevClause->getClauseKind());
  6799. ErrorFound = true;
  6800. }
  6801. }
  6802. }
  6803. return ErrorFound;
  6804. }
  6805. static bool checkReductionClauseWithNogroup(Sema &S,
  6806. ArrayRef<OMPClause *> Clauses) {
  6807. const OMPClause *ReductionClause = nullptr;
  6808. const OMPClause *NogroupClause = nullptr;
  6809. for (const OMPClause *C : Clauses) {
  6810. if (C->getClauseKind() == OMPC_reduction) {
  6811. ReductionClause = C;
  6812. if (NogroupClause)
  6813. break;
  6814. continue;
  6815. }
  6816. if (C->getClauseKind() == OMPC_nogroup) {
  6817. NogroupClause = C;
  6818. if (ReductionClause)
  6819. break;
  6820. continue;
  6821. }
  6822. }
  6823. if (ReductionClause && NogroupClause) {
  6824. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  6825. << SourceRange(NogroupClause->getBeginLoc(),
  6826. NogroupClause->getEndLoc());
  6827. return true;
  6828. }
  6829. return false;
  6830. }
  6831. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6832. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6833. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6834. if (!AStmt)
  6835. return StmtError();
  6836. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6837. OMPLoopDirective::HelperExprs B;
  6838. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6839. // define the nested loops number.
  6840. unsigned NestedLoopCount =
  6841. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6842. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6843. VarsWithImplicitDSA, B);
  6844. if (NestedLoopCount == 0)
  6845. return StmtError();
  6846. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6847. "omp for loop exprs were not built");
  6848. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6849. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6850. // not appear on the same taskloop directive.
  6851. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6852. return StmtError();
  6853. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6854. // If a reduction clause is present on the taskloop directive, the nogroup
  6855. // clause must not be specified.
  6856. if (checkReductionClauseWithNogroup(*this, Clauses))
  6857. return StmtError();
  6858. setFunctionHasBranchProtectedScope();
  6859. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6860. NestedLoopCount, Clauses, AStmt, B);
  6861. }
  6862. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6863. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6864. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6865. if (!AStmt)
  6866. return StmtError();
  6867. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6868. OMPLoopDirective::HelperExprs B;
  6869. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6870. // define the nested loops number.
  6871. unsigned NestedLoopCount =
  6872. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6873. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6874. VarsWithImplicitDSA, B);
  6875. if (NestedLoopCount == 0)
  6876. return StmtError();
  6877. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6878. "omp for loop exprs were not built");
  6879. if (!CurContext->isDependentContext()) {
  6880. // Finalize the clauses that need pre-built expressions for CodeGen.
  6881. for (OMPClause *C : Clauses) {
  6882. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6883. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6884. B.NumIterations, *this, CurScope,
  6885. DSAStack))
  6886. return StmtError();
  6887. }
  6888. }
  6889. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6890. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6891. // not appear on the same taskloop directive.
  6892. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6893. return StmtError();
  6894. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6895. // If a reduction clause is present on the taskloop directive, the nogroup
  6896. // clause must not be specified.
  6897. if (checkReductionClauseWithNogroup(*this, Clauses))
  6898. return StmtError();
  6899. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6900. return StmtError();
  6901. setFunctionHasBranchProtectedScope();
  6902. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6903. NestedLoopCount, Clauses, AStmt, B);
  6904. }
  6905. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6906. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6907. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6908. if (!AStmt)
  6909. return StmtError();
  6910. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6911. OMPLoopDirective::HelperExprs B;
  6912. // In presence of clause 'collapse' with number of loops, it will
  6913. // define the nested loops number.
  6914. unsigned NestedLoopCount =
  6915. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6916. nullptr /*ordered not a clause on distribute*/, AStmt,
  6917. *this, *DSAStack, VarsWithImplicitDSA, B);
  6918. if (NestedLoopCount == 0)
  6919. return StmtError();
  6920. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6921. "omp for loop exprs were not built");
  6922. setFunctionHasBranchProtectedScope();
  6923. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6924. NestedLoopCount, Clauses, AStmt, B);
  6925. }
  6926. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6927. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6928. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6929. if (!AStmt)
  6930. return StmtError();
  6931. auto *CS = cast<CapturedStmt>(AStmt);
  6932. // 1.2.2 OpenMP Language Terminology
  6933. // Structured block - An executable statement with a single entry at the
  6934. // top and a single exit at the bottom.
  6935. // The point of exit cannot be a branch out of the structured block.
  6936. // longjmp() and throw() must not violate the entry/exit criteria.
  6937. CS->getCapturedDecl()->setNothrow();
  6938. for (int ThisCaptureLevel =
  6939. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  6940. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6941. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6942. // 1.2.2 OpenMP Language Terminology
  6943. // Structured block - An executable statement with a single entry at the
  6944. // top and a single exit at the bottom.
  6945. // The point of exit cannot be a branch out of the structured block.
  6946. // longjmp() and throw() must not violate the entry/exit criteria.
  6947. CS->getCapturedDecl()->setNothrow();
  6948. }
  6949. OMPLoopDirective::HelperExprs B;
  6950. // In presence of clause 'collapse' with number of loops, it will
  6951. // define the nested loops number.
  6952. unsigned NestedLoopCount = checkOpenMPLoop(
  6953. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6954. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6955. VarsWithImplicitDSA, B);
  6956. if (NestedLoopCount == 0)
  6957. return StmtError();
  6958. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6959. "omp for loop exprs were not built");
  6960. setFunctionHasBranchProtectedScope();
  6961. return OMPDistributeParallelForDirective::Create(
  6962. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6963. DSAStack->isCancelRegion());
  6964. }
  6965. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6966. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6967. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6968. if (!AStmt)
  6969. return StmtError();
  6970. auto *CS = cast<CapturedStmt>(AStmt);
  6971. // 1.2.2 OpenMP Language Terminology
  6972. // Structured block - An executable statement with a single entry at the
  6973. // top and a single exit at the bottom.
  6974. // The point of exit cannot be a branch out of the structured block.
  6975. // longjmp() and throw() must not violate the entry/exit criteria.
  6976. CS->getCapturedDecl()->setNothrow();
  6977. for (int ThisCaptureLevel =
  6978. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  6979. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6980. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6981. // 1.2.2 OpenMP Language Terminology
  6982. // Structured block - An executable statement with a single entry at the
  6983. // top and a single exit at the bottom.
  6984. // The point of exit cannot be a branch out of the structured block.
  6985. // longjmp() and throw() must not violate the entry/exit criteria.
  6986. CS->getCapturedDecl()->setNothrow();
  6987. }
  6988. OMPLoopDirective::HelperExprs B;
  6989. // In presence of clause 'collapse' with number of loops, it will
  6990. // define the nested loops number.
  6991. unsigned NestedLoopCount = checkOpenMPLoop(
  6992. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6993. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6994. VarsWithImplicitDSA, B);
  6995. if (NestedLoopCount == 0)
  6996. return StmtError();
  6997. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6998. "omp for loop exprs were not built");
  6999. if (!CurContext->isDependentContext()) {
  7000. // Finalize the clauses that need pre-built expressions for CodeGen.
  7001. for (OMPClause *C : Clauses) {
  7002. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7003. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7004. B.NumIterations, *this, CurScope,
  7005. DSAStack))
  7006. return StmtError();
  7007. }
  7008. }
  7009. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7010. return StmtError();
  7011. setFunctionHasBranchProtectedScope();
  7012. return OMPDistributeParallelForSimdDirective::Create(
  7013. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7014. }
  7015. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  7016. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7017. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7018. if (!AStmt)
  7019. return StmtError();
  7020. auto *CS = cast<CapturedStmt>(AStmt);
  7021. // 1.2.2 OpenMP Language Terminology
  7022. // Structured block - An executable statement with a single entry at the
  7023. // top and a single exit at the bottom.
  7024. // The point of exit cannot be a branch out of the structured block.
  7025. // longjmp() and throw() must not violate the entry/exit criteria.
  7026. CS->getCapturedDecl()->setNothrow();
  7027. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  7028. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7029. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7030. // 1.2.2 OpenMP Language Terminology
  7031. // Structured block - An executable statement with a single entry at the
  7032. // top and a single exit at the bottom.
  7033. // The point of exit cannot be a branch out of the structured block.
  7034. // longjmp() and throw() must not violate the entry/exit criteria.
  7035. CS->getCapturedDecl()->setNothrow();
  7036. }
  7037. OMPLoopDirective::HelperExprs B;
  7038. // In presence of clause 'collapse' with number of loops, it will
  7039. // define the nested loops number.
  7040. unsigned NestedLoopCount =
  7041. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  7042. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7043. *DSAStack, VarsWithImplicitDSA, B);
  7044. if (NestedLoopCount == 0)
  7045. return StmtError();
  7046. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7047. "omp for loop exprs were not built");
  7048. if (!CurContext->isDependentContext()) {
  7049. // Finalize the clauses that need pre-built expressions for CodeGen.
  7050. for (OMPClause *C : Clauses) {
  7051. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7052. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7053. B.NumIterations, *this, CurScope,
  7054. DSAStack))
  7055. return StmtError();
  7056. }
  7057. }
  7058. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7059. return StmtError();
  7060. setFunctionHasBranchProtectedScope();
  7061. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  7062. NestedLoopCount, Clauses, AStmt, B);
  7063. }
  7064. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  7065. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7066. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7067. if (!AStmt)
  7068. return StmtError();
  7069. auto *CS = cast<CapturedStmt>(AStmt);
  7070. // 1.2.2 OpenMP Language Terminology
  7071. // Structured block - An executable statement with a single entry at the
  7072. // top and a single exit at the bottom.
  7073. // The point of exit cannot be a branch out of the structured block.
  7074. // longjmp() and throw() must not violate the entry/exit criteria.
  7075. CS->getCapturedDecl()->setNothrow();
  7076. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  7077. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7078. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7079. // 1.2.2 OpenMP Language Terminology
  7080. // Structured block - An executable statement with a single entry at the
  7081. // top and a single exit at the bottom.
  7082. // The point of exit cannot be a branch out of the structured block.
  7083. // longjmp() and throw() must not violate the entry/exit criteria.
  7084. CS->getCapturedDecl()->setNothrow();
  7085. }
  7086. OMPLoopDirective::HelperExprs B;
  7087. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7088. // define the nested loops number.
  7089. unsigned NestedLoopCount = checkOpenMPLoop(
  7090. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7091. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7092. VarsWithImplicitDSA, B);
  7093. if (NestedLoopCount == 0)
  7094. return StmtError();
  7095. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7096. "omp target parallel for simd loop exprs were not built");
  7097. if (!CurContext->isDependentContext()) {
  7098. // Finalize the clauses that need pre-built expressions for CodeGen.
  7099. for (OMPClause *C : Clauses) {
  7100. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7101. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7102. B.NumIterations, *this, CurScope,
  7103. DSAStack))
  7104. return StmtError();
  7105. }
  7106. }
  7107. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7108. return StmtError();
  7109. setFunctionHasBranchProtectedScope();
  7110. return OMPTargetParallelForSimdDirective::Create(
  7111. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7112. }
  7113. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  7114. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7115. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7116. if (!AStmt)
  7117. return StmtError();
  7118. auto *CS = cast<CapturedStmt>(AStmt);
  7119. // 1.2.2 OpenMP Language Terminology
  7120. // Structured block - An executable statement with a single entry at the
  7121. // top and a single exit at the bottom.
  7122. // The point of exit cannot be a branch out of the structured block.
  7123. // longjmp() and throw() must not violate the entry/exit criteria.
  7124. CS->getCapturedDecl()->setNothrow();
  7125. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  7126. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7127. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7128. // 1.2.2 OpenMP Language Terminology
  7129. // Structured block - An executable statement with a single entry at the
  7130. // top and a single exit at the bottom.
  7131. // The point of exit cannot be a branch out of the structured block.
  7132. // longjmp() and throw() must not violate the entry/exit criteria.
  7133. CS->getCapturedDecl()->setNothrow();
  7134. }
  7135. OMPLoopDirective::HelperExprs B;
  7136. // In presence of clause 'collapse' with number of loops, it will define the
  7137. // nested loops number.
  7138. unsigned NestedLoopCount =
  7139. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  7140. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7141. VarsWithImplicitDSA, B);
  7142. if (NestedLoopCount == 0)
  7143. return StmtError();
  7144. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7145. "omp target simd loop exprs were not built");
  7146. if (!CurContext->isDependentContext()) {
  7147. // Finalize the clauses that need pre-built expressions for CodeGen.
  7148. for (OMPClause *C : Clauses) {
  7149. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7150. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7151. B.NumIterations, *this, CurScope,
  7152. DSAStack))
  7153. return StmtError();
  7154. }
  7155. }
  7156. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7157. return StmtError();
  7158. setFunctionHasBranchProtectedScope();
  7159. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  7160. NestedLoopCount, Clauses, AStmt, B);
  7161. }
  7162. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  7163. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7164. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7165. if (!AStmt)
  7166. return StmtError();
  7167. auto *CS = cast<CapturedStmt>(AStmt);
  7168. // 1.2.2 OpenMP Language Terminology
  7169. // Structured block - An executable statement with a single entry at the
  7170. // top and a single exit at the bottom.
  7171. // The point of exit cannot be a branch out of the structured block.
  7172. // longjmp() and throw() must not violate the entry/exit criteria.
  7173. CS->getCapturedDecl()->setNothrow();
  7174. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  7175. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7176. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7177. // 1.2.2 OpenMP Language Terminology
  7178. // Structured block - An executable statement with a single entry at the
  7179. // top and a single exit at the bottom.
  7180. // The point of exit cannot be a branch out of the structured block.
  7181. // longjmp() and throw() must not violate the entry/exit criteria.
  7182. CS->getCapturedDecl()->setNothrow();
  7183. }
  7184. OMPLoopDirective::HelperExprs B;
  7185. // In presence of clause 'collapse' with number of loops, it will
  7186. // define the nested loops number.
  7187. unsigned NestedLoopCount =
  7188. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  7189. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7190. *DSAStack, VarsWithImplicitDSA, B);
  7191. if (NestedLoopCount == 0)
  7192. return StmtError();
  7193. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7194. "omp teams distribute loop exprs were not built");
  7195. setFunctionHasBranchProtectedScope();
  7196. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7197. return OMPTeamsDistributeDirective::Create(
  7198. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7199. }
  7200. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  7201. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7202. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7203. if (!AStmt)
  7204. return StmtError();
  7205. auto *CS = cast<CapturedStmt>(AStmt);
  7206. // 1.2.2 OpenMP Language Terminology
  7207. // Structured block - An executable statement with a single entry at the
  7208. // top and a single exit at the bottom.
  7209. // The point of exit cannot be a branch out of the structured block.
  7210. // longjmp() and throw() must not violate the entry/exit criteria.
  7211. CS->getCapturedDecl()->setNothrow();
  7212. for (int ThisCaptureLevel =
  7213. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  7214. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7215. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7216. // 1.2.2 OpenMP Language Terminology
  7217. // Structured block - An executable statement with a single entry at the
  7218. // top and a single exit at the bottom.
  7219. // The point of exit cannot be a branch out of the structured block.
  7220. // longjmp() and throw() must not violate the entry/exit criteria.
  7221. CS->getCapturedDecl()->setNothrow();
  7222. }
  7223. OMPLoopDirective::HelperExprs B;
  7224. // In presence of clause 'collapse' with number of loops, it will
  7225. // define the nested loops number.
  7226. unsigned NestedLoopCount = checkOpenMPLoop(
  7227. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7228. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7229. VarsWithImplicitDSA, B);
  7230. if (NestedLoopCount == 0)
  7231. return StmtError();
  7232. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7233. "omp teams distribute simd loop exprs were not built");
  7234. if (!CurContext->isDependentContext()) {
  7235. // Finalize the clauses that need pre-built expressions for CodeGen.
  7236. for (OMPClause *C : Clauses) {
  7237. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7238. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7239. B.NumIterations, *this, CurScope,
  7240. DSAStack))
  7241. return StmtError();
  7242. }
  7243. }
  7244. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7245. return StmtError();
  7246. setFunctionHasBranchProtectedScope();
  7247. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7248. return OMPTeamsDistributeSimdDirective::Create(
  7249. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7250. }
  7251. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  7252. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7253. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7254. if (!AStmt)
  7255. return StmtError();
  7256. auto *CS = cast<CapturedStmt>(AStmt);
  7257. // 1.2.2 OpenMP Language Terminology
  7258. // Structured block - An executable statement with a single entry at the
  7259. // top and a single exit at the bottom.
  7260. // The point of exit cannot be a branch out of the structured block.
  7261. // longjmp() and throw() must not violate the entry/exit criteria.
  7262. CS->getCapturedDecl()->setNothrow();
  7263. for (int ThisCaptureLevel =
  7264. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  7265. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7266. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7267. // 1.2.2 OpenMP Language Terminology
  7268. // Structured block - An executable statement with a single entry at the
  7269. // top and a single exit at the bottom.
  7270. // The point of exit cannot be a branch out of the structured block.
  7271. // longjmp() and throw() must not violate the entry/exit criteria.
  7272. CS->getCapturedDecl()->setNothrow();
  7273. }
  7274. OMPLoopDirective::HelperExprs B;
  7275. // In presence of clause 'collapse' with number of loops, it will
  7276. // define the nested loops number.
  7277. unsigned NestedLoopCount = checkOpenMPLoop(
  7278. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7279. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7280. VarsWithImplicitDSA, B);
  7281. if (NestedLoopCount == 0)
  7282. return StmtError();
  7283. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7284. "omp for loop exprs were not built");
  7285. if (!CurContext->isDependentContext()) {
  7286. // Finalize the clauses that need pre-built expressions for CodeGen.
  7287. for (OMPClause *C : Clauses) {
  7288. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7289. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7290. B.NumIterations, *this, CurScope,
  7291. DSAStack))
  7292. return StmtError();
  7293. }
  7294. }
  7295. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7296. return StmtError();
  7297. setFunctionHasBranchProtectedScope();
  7298. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7299. return OMPTeamsDistributeParallelForSimdDirective::Create(
  7300. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7301. }
  7302. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  7303. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7304. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7305. if (!AStmt)
  7306. return StmtError();
  7307. auto *CS = cast<CapturedStmt>(AStmt);
  7308. // 1.2.2 OpenMP Language Terminology
  7309. // Structured block - An executable statement with a single entry at the
  7310. // top and a single exit at the bottom.
  7311. // The point of exit cannot be a branch out of the structured block.
  7312. // longjmp() and throw() must not violate the entry/exit criteria.
  7313. CS->getCapturedDecl()->setNothrow();
  7314. for (int ThisCaptureLevel =
  7315. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  7316. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7317. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7318. // 1.2.2 OpenMP Language Terminology
  7319. // Structured block - An executable statement with a single entry at the
  7320. // top and a single exit at the bottom.
  7321. // The point of exit cannot be a branch out of the structured block.
  7322. // longjmp() and throw() must not violate the entry/exit criteria.
  7323. CS->getCapturedDecl()->setNothrow();
  7324. }
  7325. OMPLoopDirective::HelperExprs B;
  7326. // In presence of clause 'collapse' with number of loops, it will
  7327. // define the nested loops number.
  7328. unsigned NestedLoopCount = checkOpenMPLoop(
  7329. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7330. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7331. VarsWithImplicitDSA, B);
  7332. if (NestedLoopCount == 0)
  7333. return StmtError();
  7334. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7335. "omp for loop exprs were not built");
  7336. setFunctionHasBranchProtectedScope();
  7337. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7338. return OMPTeamsDistributeParallelForDirective::Create(
  7339. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7340. DSAStack->isCancelRegion());
  7341. }
  7342. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7343. Stmt *AStmt,
  7344. SourceLocation StartLoc,
  7345. SourceLocation EndLoc) {
  7346. if (!AStmt)
  7347. return StmtError();
  7348. auto *CS = cast<CapturedStmt>(AStmt);
  7349. // 1.2.2 OpenMP Language Terminology
  7350. // Structured block - An executable statement with a single entry at the
  7351. // top and a single exit at the bottom.
  7352. // The point of exit cannot be a branch out of the structured block.
  7353. // longjmp() and throw() must not violate the entry/exit criteria.
  7354. CS->getCapturedDecl()->setNothrow();
  7355. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  7356. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7357. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7358. // 1.2.2 OpenMP Language Terminology
  7359. // Structured block - An executable statement with a single entry at the
  7360. // top and a single exit at the bottom.
  7361. // The point of exit cannot be a branch out of the structured block.
  7362. // longjmp() and throw() must not violate the entry/exit criteria.
  7363. CS->getCapturedDecl()->setNothrow();
  7364. }
  7365. setFunctionHasBranchProtectedScope();
  7366. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7367. AStmt);
  7368. }
  7369. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  7370. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7371. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7372. if (!AStmt)
  7373. return StmtError();
  7374. auto *CS = cast<CapturedStmt>(AStmt);
  7375. // 1.2.2 OpenMP Language Terminology
  7376. // Structured block - An executable statement with a single entry at the
  7377. // top and a single exit at the bottom.
  7378. // The point of exit cannot be a branch out of the structured block.
  7379. // longjmp() and throw() must not violate the entry/exit criteria.
  7380. CS->getCapturedDecl()->setNothrow();
  7381. for (int ThisCaptureLevel =
  7382. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  7383. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7384. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7385. // 1.2.2 OpenMP Language Terminology
  7386. // Structured block - An executable statement with a single entry at the
  7387. // top and a single exit at the bottom.
  7388. // The point of exit cannot be a branch out of the structured block.
  7389. // longjmp() and throw() must not violate the entry/exit criteria.
  7390. CS->getCapturedDecl()->setNothrow();
  7391. }
  7392. OMPLoopDirective::HelperExprs B;
  7393. // In presence of clause 'collapse' with number of loops, it will
  7394. // define the nested loops number.
  7395. unsigned NestedLoopCount = checkOpenMPLoop(
  7396. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  7397. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7398. VarsWithImplicitDSA, B);
  7399. if (NestedLoopCount == 0)
  7400. return StmtError();
  7401. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7402. "omp target teams distribute loop exprs were not built");
  7403. setFunctionHasBranchProtectedScope();
  7404. return OMPTargetTeamsDistributeDirective::Create(
  7405. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7406. }
  7407. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  7408. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7409. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7410. if (!AStmt)
  7411. return StmtError();
  7412. auto *CS = cast<CapturedStmt>(AStmt);
  7413. // 1.2.2 OpenMP Language Terminology
  7414. // Structured block - An executable statement with a single entry at the
  7415. // top and a single exit at the bottom.
  7416. // The point of exit cannot be a branch out of the structured block.
  7417. // longjmp() and throw() must not violate the entry/exit criteria.
  7418. CS->getCapturedDecl()->setNothrow();
  7419. for (int ThisCaptureLevel =
  7420. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  7421. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7422. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7423. // 1.2.2 OpenMP Language Terminology
  7424. // Structured block - An executable statement with a single entry at the
  7425. // top and a single exit at the bottom.
  7426. // The point of exit cannot be a branch out of the structured block.
  7427. // longjmp() and throw() must not violate the entry/exit criteria.
  7428. CS->getCapturedDecl()->setNothrow();
  7429. }
  7430. OMPLoopDirective::HelperExprs B;
  7431. // In presence of clause 'collapse' with number of loops, it will
  7432. // define the nested loops number.
  7433. unsigned NestedLoopCount = checkOpenMPLoop(
  7434. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7435. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7436. VarsWithImplicitDSA, B);
  7437. if (NestedLoopCount == 0)
  7438. return StmtError();
  7439. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7440. "omp target teams distribute parallel for loop exprs were not built");
  7441. if (!CurContext->isDependentContext()) {
  7442. // Finalize the clauses that need pre-built expressions for CodeGen.
  7443. for (OMPClause *C : Clauses) {
  7444. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7445. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7446. B.NumIterations, *this, CurScope,
  7447. DSAStack))
  7448. return StmtError();
  7449. }
  7450. }
  7451. setFunctionHasBranchProtectedScope();
  7452. return OMPTargetTeamsDistributeParallelForDirective::Create(
  7453. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7454. DSAStack->isCancelRegion());
  7455. }
  7456. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  7457. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7458. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7459. if (!AStmt)
  7460. return StmtError();
  7461. auto *CS = cast<CapturedStmt>(AStmt);
  7462. // 1.2.2 OpenMP Language Terminology
  7463. // Structured block - An executable statement with a single entry at the
  7464. // top and a single exit at the bottom.
  7465. // The point of exit cannot be a branch out of the structured block.
  7466. // longjmp() and throw() must not violate the entry/exit criteria.
  7467. CS->getCapturedDecl()->setNothrow();
  7468. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  7469. OMPD_target_teams_distribute_parallel_for_simd);
  7470. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7471. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7472. // 1.2.2 OpenMP Language Terminology
  7473. // Structured block - An executable statement with a single entry at the
  7474. // top and a single exit at the bottom.
  7475. // The point of exit cannot be a branch out of the structured block.
  7476. // longjmp() and throw() must not violate the entry/exit criteria.
  7477. CS->getCapturedDecl()->setNothrow();
  7478. }
  7479. OMPLoopDirective::HelperExprs B;
  7480. // In presence of clause 'collapse' with number of loops, it will
  7481. // define the nested loops number.
  7482. unsigned NestedLoopCount =
  7483. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  7484. getCollapseNumberExpr(Clauses),
  7485. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7486. *DSAStack, VarsWithImplicitDSA, B);
  7487. if (NestedLoopCount == 0)
  7488. return StmtError();
  7489. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7490. "omp target teams distribute parallel for simd loop exprs were not "
  7491. "built");
  7492. if (!CurContext->isDependentContext()) {
  7493. // Finalize the clauses that need pre-built expressions for CodeGen.
  7494. for (OMPClause *C : Clauses) {
  7495. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7496. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7497. B.NumIterations, *this, CurScope,
  7498. DSAStack))
  7499. return StmtError();
  7500. }
  7501. }
  7502. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7503. return StmtError();
  7504. setFunctionHasBranchProtectedScope();
  7505. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  7506. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7507. }
  7508. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  7509. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7510. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7511. if (!AStmt)
  7512. return StmtError();
  7513. auto *CS = cast<CapturedStmt>(AStmt);
  7514. // 1.2.2 OpenMP Language Terminology
  7515. // Structured block - An executable statement with a single entry at the
  7516. // top and a single exit at the bottom.
  7517. // The point of exit cannot be a branch out of the structured block.
  7518. // longjmp() and throw() must not violate the entry/exit criteria.
  7519. CS->getCapturedDecl()->setNothrow();
  7520. for (int ThisCaptureLevel =
  7521. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  7522. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7523. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7524. // 1.2.2 OpenMP Language Terminology
  7525. // Structured block - An executable statement with a single entry at the
  7526. // top and a single exit at the bottom.
  7527. // The point of exit cannot be a branch out of the structured block.
  7528. // longjmp() and throw() must not violate the entry/exit criteria.
  7529. CS->getCapturedDecl()->setNothrow();
  7530. }
  7531. OMPLoopDirective::HelperExprs B;
  7532. // In presence of clause 'collapse' with number of loops, it will
  7533. // define the nested loops number.
  7534. unsigned NestedLoopCount = checkOpenMPLoop(
  7535. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7536. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7537. VarsWithImplicitDSA, B);
  7538. if (NestedLoopCount == 0)
  7539. return StmtError();
  7540. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7541. "omp target teams distribute simd loop exprs were not built");
  7542. if (!CurContext->isDependentContext()) {
  7543. // Finalize the clauses that need pre-built expressions for CodeGen.
  7544. for (OMPClause *C : Clauses) {
  7545. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7546. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7547. B.NumIterations, *this, CurScope,
  7548. DSAStack))
  7549. return StmtError();
  7550. }
  7551. }
  7552. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7553. return StmtError();
  7554. setFunctionHasBranchProtectedScope();
  7555. return OMPTargetTeamsDistributeSimdDirective::Create(
  7556. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7557. }
  7558. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  7559. SourceLocation StartLoc,
  7560. SourceLocation LParenLoc,
  7561. SourceLocation EndLoc) {
  7562. OMPClause *Res = nullptr;
  7563. switch (Kind) {
  7564. case OMPC_final:
  7565. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  7566. break;
  7567. case OMPC_num_threads:
  7568. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7569. break;
  7570. case OMPC_safelen:
  7571. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7572. break;
  7573. case OMPC_simdlen:
  7574. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7575. break;
  7576. case OMPC_collapse:
  7577. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  7578. break;
  7579. case OMPC_ordered:
  7580. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  7581. break;
  7582. case OMPC_device:
  7583. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  7584. break;
  7585. case OMPC_num_teams:
  7586. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7587. break;
  7588. case OMPC_thread_limit:
  7589. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  7590. break;
  7591. case OMPC_priority:
  7592. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  7593. break;
  7594. case OMPC_grainsize:
  7595. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  7596. break;
  7597. case OMPC_num_tasks:
  7598. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  7599. break;
  7600. case OMPC_hint:
  7601. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  7602. break;
  7603. case OMPC_if:
  7604. case OMPC_default:
  7605. case OMPC_proc_bind:
  7606. case OMPC_schedule:
  7607. case OMPC_private:
  7608. case OMPC_firstprivate:
  7609. case OMPC_lastprivate:
  7610. case OMPC_shared:
  7611. case OMPC_reduction:
  7612. case OMPC_task_reduction:
  7613. case OMPC_in_reduction:
  7614. case OMPC_linear:
  7615. case OMPC_aligned:
  7616. case OMPC_copyin:
  7617. case OMPC_copyprivate:
  7618. case OMPC_nowait:
  7619. case OMPC_untied:
  7620. case OMPC_mergeable:
  7621. case OMPC_threadprivate:
  7622. case OMPC_flush:
  7623. case OMPC_read:
  7624. case OMPC_write:
  7625. case OMPC_update:
  7626. case OMPC_capture:
  7627. case OMPC_seq_cst:
  7628. case OMPC_depend:
  7629. case OMPC_threads:
  7630. case OMPC_simd:
  7631. case OMPC_map:
  7632. case OMPC_nogroup:
  7633. case OMPC_dist_schedule:
  7634. case OMPC_defaultmap:
  7635. case OMPC_unknown:
  7636. case OMPC_uniform:
  7637. case OMPC_to:
  7638. case OMPC_from:
  7639. case OMPC_use_device_ptr:
  7640. case OMPC_is_device_ptr:
  7641. case OMPC_unified_address:
  7642. case OMPC_unified_shared_memory:
  7643. case OMPC_reverse_offload:
  7644. case OMPC_dynamic_allocators:
  7645. case OMPC_atomic_default_mem_order:
  7646. llvm_unreachable("Clause is not allowed.");
  7647. }
  7648. return Res;
  7649. }
  7650. // An OpenMP directive such as 'target parallel' has two captured regions:
  7651. // for the 'target' and 'parallel' respectively. This function returns
  7652. // the region in which to capture expressions associated with a clause.
  7653. // A return value of OMPD_unknown signifies that the expression should not
  7654. // be captured.
  7655. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7656. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7657. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7658. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7659. switch (CKind) {
  7660. case OMPC_if:
  7661. switch (DKind) {
  7662. case OMPD_target_parallel:
  7663. case OMPD_target_parallel_for:
  7664. case OMPD_target_parallel_for_simd:
  7665. // If this clause applies to the nested 'parallel' region, capture within
  7666. // the 'target' region, otherwise do not capture.
  7667. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7668. CaptureRegion = OMPD_target;
  7669. break;
  7670. case OMPD_target_teams_distribute_parallel_for:
  7671. case OMPD_target_teams_distribute_parallel_for_simd:
  7672. // If this clause applies to the nested 'parallel' region, capture within
  7673. // the 'teams' region, otherwise do not capture.
  7674. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7675. CaptureRegion = OMPD_teams;
  7676. break;
  7677. case OMPD_teams_distribute_parallel_for:
  7678. case OMPD_teams_distribute_parallel_for_simd:
  7679. CaptureRegion = OMPD_teams;
  7680. break;
  7681. case OMPD_target_update:
  7682. case OMPD_target_enter_data:
  7683. case OMPD_target_exit_data:
  7684. CaptureRegion = OMPD_task;
  7685. break;
  7686. case OMPD_cancel:
  7687. case OMPD_parallel:
  7688. case OMPD_parallel_sections:
  7689. case OMPD_parallel_for:
  7690. case OMPD_parallel_for_simd:
  7691. case OMPD_target:
  7692. case OMPD_target_simd:
  7693. case OMPD_target_teams:
  7694. case OMPD_target_teams_distribute:
  7695. case OMPD_target_teams_distribute_simd:
  7696. case OMPD_distribute_parallel_for:
  7697. case OMPD_distribute_parallel_for_simd:
  7698. case OMPD_task:
  7699. case OMPD_taskloop:
  7700. case OMPD_taskloop_simd:
  7701. case OMPD_target_data:
  7702. // Do not capture if-clause expressions.
  7703. break;
  7704. case OMPD_threadprivate:
  7705. case OMPD_taskyield:
  7706. case OMPD_barrier:
  7707. case OMPD_taskwait:
  7708. case OMPD_cancellation_point:
  7709. case OMPD_flush:
  7710. case OMPD_declare_reduction:
  7711. case OMPD_declare_simd:
  7712. case OMPD_declare_target:
  7713. case OMPD_end_declare_target:
  7714. case OMPD_teams:
  7715. case OMPD_simd:
  7716. case OMPD_for:
  7717. case OMPD_for_simd:
  7718. case OMPD_sections:
  7719. case OMPD_section:
  7720. case OMPD_single:
  7721. case OMPD_master:
  7722. case OMPD_critical:
  7723. case OMPD_taskgroup:
  7724. case OMPD_distribute:
  7725. case OMPD_ordered:
  7726. case OMPD_atomic:
  7727. case OMPD_distribute_simd:
  7728. case OMPD_teams_distribute:
  7729. case OMPD_teams_distribute_simd:
  7730. case OMPD_requires:
  7731. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7732. case OMPD_unknown:
  7733. llvm_unreachable("Unknown OpenMP directive");
  7734. }
  7735. break;
  7736. case OMPC_num_threads:
  7737. switch (DKind) {
  7738. case OMPD_target_parallel:
  7739. case OMPD_target_parallel_for:
  7740. case OMPD_target_parallel_for_simd:
  7741. CaptureRegion = OMPD_target;
  7742. break;
  7743. case OMPD_teams_distribute_parallel_for:
  7744. case OMPD_teams_distribute_parallel_for_simd:
  7745. case OMPD_target_teams_distribute_parallel_for:
  7746. case OMPD_target_teams_distribute_parallel_for_simd:
  7747. CaptureRegion = OMPD_teams;
  7748. break;
  7749. case OMPD_parallel:
  7750. case OMPD_parallel_sections:
  7751. case OMPD_parallel_for:
  7752. case OMPD_parallel_for_simd:
  7753. case OMPD_distribute_parallel_for:
  7754. case OMPD_distribute_parallel_for_simd:
  7755. // Do not capture num_threads-clause expressions.
  7756. break;
  7757. case OMPD_target_data:
  7758. case OMPD_target_enter_data:
  7759. case OMPD_target_exit_data:
  7760. case OMPD_target_update:
  7761. case OMPD_target:
  7762. case OMPD_target_simd:
  7763. case OMPD_target_teams:
  7764. case OMPD_target_teams_distribute:
  7765. case OMPD_target_teams_distribute_simd:
  7766. case OMPD_cancel:
  7767. case OMPD_task:
  7768. case OMPD_taskloop:
  7769. case OMPD_taskloop_simd:
  7770. case OMPD_threadprivate:
  7771. case OMPD_taskyield:
  7772. case OMPD_barrier:
  7773. case OMPD_taskwait:
  7774. case OMPD_cancellation_point:
  7775. case OMPD_flush:
  7776. case OMPD_declare_reduction:
  7777. case OMPD_declare_simd:
  7778. case OMPD_declare_target:
  7779. case OMPD_end_declare_target:
  7780. case OMPD_teams:
  7781. case OMPD_simd:
  7782. case OMPD_for:
  7783. case OMPD_for_simd:
  7784. case OMPD_sections:
  7785. case OMPD_section:
  7786. case OMPD_single:
  7787. case OMPD_master:
  7788. case OMPD_critical:
  7789. case OMPD_taskgroup:
  7790. case OMPD_distribute:
  7791. case OMPD_ordered:
  7792. case OMPD_atomic:
  7793. case OMPD_distribute_simd:
  7794. case OMPD_teams_distribute:
  7795. case OMPD_teams_distribute_simd:
  7796. case OMPD_requires:
  7797. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7798. case OMPD_unknown:
  7799. llvm_unreachable("Unknown OpenMP directive");
  7800. }
  7801. break;
  7802. case OMPC_num_teams:
  7803. switch (DKind) {
  7804. case OMPD_target_teams:
  7805. case OMPD_target_teams_distribute:
  7806. case OMPD_target_teams_distribute_simd:
  7807. case OMPD_target_teams_distribute_parallel_for:
  7808. case OMPD_target_teams_distribute_parallel_for_simd:
  7809. CaptureRegion = OMPD_target;
  7810. break;
  7811. case OMPD_teams_distribute_parallel_for:
  7812. case OMPD_teams_distribute_parallel_for_simd:
  7813. case OMPD_teams:
  7814. case OMPD_teams_distribute:
  7815. case OMPD_teams_distribute_simd:
  7816. // Do not capture num_teams-clause expressions.
  7817. break;
  7818. case OMPD_distribute_parallel_for:
  7819. case OMPD_distribute_parallel_for_simd:
  7820. case OMPD_task:
  7821. case OMPD_taskloop:
  7822. case OMPD_taskloop_simd:
  7823. case OMPD_target_data:
  7824. case OMPD_target_enter_data:
  7825. case OMPD_target_exit_data:
  7826. case OMPD_target_update:
  7827. case OMPD_cancel:
  7828. case OMPD_parallel:
  7829. case OMPD_parallel_sections:
  7830. case OMPD_parallel_for:
  7831. case OMPD_parallel_for_simd:
  7832. case OMPD_target:
  7833. case OMPD_target_simd:
  7834. case OMPD_target_parallel:
  7835. case OMPD_target_parallel_for:
  7836. case OMPD_target_parallel_for_simd:
  7837. case OMPD_threadprivate:
  7838. case OMPD_taskyield:
  7839. case OMPD_barrier:
  7840. case OMPD_taskwait:
  7841. case OMPD_cancellation_point:
  7842. case OMPD_flush:
  7843. case OMPD_declare_reduction:
  7844. case OMPD_declare_simd:
  7845. case OMPD_declare_target:
  7846. case OMPD_end_declare_target:
  7847. case OMPD_simd:
  7848. case OMPD_for:
  7849. case OMPD_for_simd:
  7850. case OMPD_sections:
  7851. case OMPD_section:
  7852. case OMPD_single:
  7853. case OMPD_master:
  7854. case OMPD_critical:
  7855. case OMPD_taskgroup:
  7856. case OMPD_distribute:
  7857. case OMPD_ordered:
  7858. case OMPD_atomic:
  7859. case OMPD_distribute_simd:
  7860. case OMPD_requires:
  7861. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7862. case OMPD_unknown:
  7863. llvm_unreachable("Unknown OpenMP directive");
  7864. }
  7865. break;
  7866. case OMPC_thread_limit:
  7867. switch (DKind) {
  7868. case OMPD_target_teams:
  7869. case OMPD_target_teams_distribute:
  7870. case OMPD_target_teams_distribute_simd:
  7871. case OMPD_target_teams_distribute_parallel_for:
  7872. case OMPD_target_teams_distribute_parallel_for_simd:
  7873. CaptureRegion = OMPD_target;
  7874. break;
  7875. case OMPD_teams_distribute_parallel_for:
  7876. case OMPD_teams_distribute_parallel_for_simd:
  7877. case OMPD_teams:
  7878. case OMPD_teams_distribute:
  7879. case OMPD_teams_distribute_simd:
  7880. // Do not capture thread_limit-clause expressions.
  7881. break;
  7882. case OMPD_distribute_parallel_for:
  7883. case OMPD_distribute_parallel_for_simd:
  7884. case OMPD_task:
  7885. case OMPD_taskloop:
  7886. case OMPD_taskloop_simd:
  7887. case OMPD_target_data:
  7888. case OMPD_target_enter_data:
  7889. case OMPD_target_exit_data:
  7890. case OMPD_target_update:
  7891. case OMPD_cancel:
  7892. case OMPD_parallel:
  7893. case OMPD_parallel_sections:
  7894. case OMPD_parallel_for:
  7895. case OMPD_parallel_for_simd:
  7896. case OMPD_target:
  7897. case OMPD_target_simd:
  7898. case OMPD_target_parallel:
  7899. case OMPD_target_parallel_for:
  7900. case OMPD_target_parallel_for_simd:
  7901. case OMPD_threadprivate:
  7902. case OMPD_taskyield:
  7903. case OMPD_barrier:
  7904. case OMPD_taskwait:
  7905. case OMPD_cancellation_point:
  7906. case OMPD_flush:
  7907. case OMPD_declare_reduction:
  7908. case OMPD_declare_simd:
  7909. case OMPD_declare_target:
  7910. case OMPD_end_declare_target:
  7911. case OMPD_simd:
  7912. case OMPD_for:
  7913. case OMPD_for_simd:
  7914. case OMPD_sections:
  7915. case OMPD_section:
  7916. case OMPD_single:
  7917. case OMPD_master:
  7918. case OMPD_critical:
  7919. case OMPD_taskgroup:
  7920. case OMPD_distribute:
  7921. case OMPD_ordered:
  7922. case OMPD_atomic:
  7923. case OMPD_distribute_simd:
  7924. case OMPD_requires:
  7925. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7926. case OMPD_unknown:
  7927. llvm_unreachable("Unknown OpenMP directive");
  7928. }
  7929. break;
  7930. case OMPC_schedule:
  7931. switch (DKind) {
  7932. case OMPD_parallel_for:
  7933. case OMPD_parallel_for_simd:
  7934. case OMPD_distribute_parallel_for:
  7935. case OMPD_distribute_parallel_for_simd:
  7936. case OMPD_teams_distribute_parallel_for:
  7937. case OMPD_teams_distribute_parallel_for_simd:
  7938. case OMPD_target_parallel_for:
  7939. case OMPD_target_parallel_for_simd:
  7940. case OMPD_target_teams_distribute_parallel_for:
  7941. case OMPD_target_teams_distribute_parallel_for_simd:
  7942. CaptureRegion = OMPD_parallel;
  7943. break;
  7944. case OMPD_for:
  7945. case OMPD_for_simd:
  7946. // Do not capture schedule-clause expressions.
  7947. break;
  7948. case OMPD_task:
  7949. case OMPD_taskloop:
  7950. case OMPD_taskloop_simd:
  7951. case OMPD_target_data:
  7952. case OMPD_target_enter_data:
  7953. case OMPD_target_exit_data:
  7954. case OMPD_target_update:
  7955. case OMPD_teams:
  7956. case OMPD_teams_distribute:
  7957. case OMPD_teams_distribute_simd:
  7958. case OMPD_target_teams_distribute:
  7959. case OMPD_target_teams_distribute_simd:
  7960. case OMPD_target:
  7961. case OMPD_target_simd:
  7962. case OMPD_target_parallel:
  7963. case OMPD_cancel:
  7964. case OMPD_parallel:
  7965. case OMPD_parallel_sections:
  7966. case OMPD_threadprivate:
  7967. case OMPD_taskyield:
  7968. case OMPD_barrier:
  7969. case OMPD_taskwait:
  7970. case OMPD_cancellation_point:
  7971. case OMPD_flush:
  7972. case OMPD_declare_reduction:
  7973. case OMPD_declare_simd:
  7974. case OMPD_declare_target:
  7975. case OMPD_end_declare_target:
  7976. case OMPD_simd:
  7977. case OMPD_sections:
  7978. case OMPD_section:
  7979. case OMPD_single:
  7980. case OMPD_master:
  7981. case OMPD_critical:
  7982. case OMPD_taskgroup:
  7983. case OMPD_distribute:
  7984. case OMPD_ordered:
  7985. case OMPD_atomic:
  7986. case OMPD_distribute_simd:
  7987. case OMPD_target_teams:
  7988. case OMPD_requires:
  7989. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7990. case OMPD_unknown:
  7991. llvm_unreachable("Unknown OpenMP directive");
  7992. }
  7993. break;
  7994. case OMPC_dist_schedule:
  7995. switch (DKind) {
  7996. case OMPD_teams_distribute_parallel_for:
  7997. case OMPD_teams_distribute_parallel_for_simd:
  7998. case OMPD_teams_distribute:
  7999. case OMPD_teams_distribute_simd:
  8000. case OMPD_target_teams_distribute_parallel_for:
  8001. case OMPD_target_teams_distribute_parallel_for_simd:
  8002. case OMPD_target_teams_distribute:
  8003. case OMPD_target_teams_distribute_simd:
  8004. CaptureRegion = OMPD_teams;
  8005. break;
  8006. case OMPD_distribute_parallel_for:
  8007. case OMPD_distribute_parallel_for_simd:
  8008. case OMPD_distribute:
  8009. case OMPD_distribute_simd:
  8010. // Do not capture thread_limit-clause expressions.
  8011. break;
  8012. case OMPD_parallel_for:
  8013. case OMPD_parallel_for_simd:
  8014. case OMPD_target_parallel_for_simd:
  8015. case OMPD_target_parallel_for:
  8016. case OMPD_task:
  8017. case OMPD_taskloop:
  8018. case OMPD_taskloop_simd:
  8019. case OMPD_target_data:
  8020. case OMPD_target_enter_data:
  8021. case OMPD_target_exit_data:
  8022. case OMPD_target_update:
  8023. case OMPD_teams:
  8024. case OMPD_target:
  8025. case OMPD_target_simd:
  8026. case OMPD_target_parallel:
  8027. case OMPD_cancel:
  8028. case OMPD_parallel:
  8029. case OMPD_parallel_sections:
  8030. case OMPD_threadprivate:
  8031. case OMPD_taskyield:
  8032. case OMPD_barrier:
  8033. case OMPD_taskwait:
  8034. case OMPD_cancellation_point:
  8035. case OMPD_flush:
  8036. case OMPD_declare_reduction:
  8037. case OMPD_declare_simd:
  8038. case OMPD_declare_target:
  8039. case OMPD_end_declare_target:
  8040. case OMPD_simd:
  8041. case OMPD_for:
  8042. case OMPD_for_simd:
  8043. case OMPD_sections:
  8044. case OMPD_section:
  8045. case OMPD_single:
  8046. case OMPD_master:
  8047. case OMPD_critical:
  8048. case OMPD_taskgroup:
  8049. case OMPD_ordered:
  8050. case OMPD_atomic:
  8051. case OMPD_target_teams:
  8052. case OMPD_requires:
  8053. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8054. case OMPD_unknown:
  8055. llvm_unreachable("Unknown OpenMP directive");
  8056. }
  8057. break;
  8058. case OMPC_device:
  8059. switch (DKind) {
  8060. case OMPD_target_update:
  8061. case OMPD_target_enter_data:
  8062. case OMPD_target_exit_data:
  8063. case OMPD_target:
  8064. case OMPD_target_simd:
  8065. case OMPD_target_teams:
  8066. case OMPD_target_parallel:
  8067. case OMPD_target_teams_distribute:
  8068. case OMPD_target_teams_distribute_simd:
  8069. case OMPD_target_parallel_for:
  8070. case OMPD_target_parallel_for_simd:
  8071. case OMPD_target_teams_distribute_parallel_for:
  8072. case OMPD_target_teams_distribute_parallel_for_simd:
  8073. CaptureRegion = OMPD_task;
  8074. break;
  8075. case OMPD_target_data:
  8076. // Do not capture device-clause expressions.
  8077. break;
  8078. case OMPD_teams_distribute_parallel_for:
  8079. case OMPD_teams_distribute_parallel_for_simd:
  8080. case OMPD_teams:
  8081. case OMPD_teams_distribute:
  8082. case OMPD_teams_distribute_simd:
  8083. case OMPD_distribute_parallel_for:
  8084. case OMPD_distribute_parallel_for_simd:
  8085. case OMPD_task:
  8086. case OMPD_taskloop:
  8087. case OMPD_taskloop_simd:
  8088. case OMPD_cancel:
  8089. case OMPD_parallel:
  8090. case OMPD_parallel_sections:
  8091. case OMPD_parallel_for:
  8092. case OMPD_parallel_for_simd:
  8093. case OMPD_threadprivate:
  8094. case OMPD_taskyield:
  8095. case OMPD_barrier:
  8096. case OMPD_taskwait:
  8097. case OMPD_cancellation_point:
  8098. case OMPD_flush:
  8099. case OMPD_declare_reduction:
  8100. case OMPD_declare_simd:
  8101. case OMPD_declare_target:
  8102. case OMPD_end_declare_target:
  8103. case OMPD_simd:
  8104. case OMPD_for:
  8105. case OMPD_for_simd:
  8106. case OMPD_sections:
  8107. case OMPD_section:
  8108. case OMPD_single:
  8109. case OMPD_master:
  8110. case OMPD_critical:
  8111. case OMPD_taskgroup:
  8112. case OMPD_distribute:
  8113. case OMPD_ordered:
  8114. case OMPD_atomic:
  8115. case OMPD_distribute_simd:
  8116. case OMPD_requires:
  8117. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8118. case OMPD_unknown:
  8119. llvm_unreachable("Unknown OpenMP directive");
  8120. }
  8121. break;
  8122. case OMPC_firstprivate:
  8123. case OMPC_lastprivate:
  8124. case OMPC_reduction:
  8125. case OMPC_task_reduction:
  8126. case OMPC_in_reduction:
  8127. case OMPC_linear:
  8128. case OMPC_default:
  8129. case OMPC_proc_bind:
  8130. case OMPC_final:
  8131. case OMPC_safelen:
  8132. case OMPC_simdlen:
  8133. case OMPC_collapse:
  8134. case OMPC_private:
  8135. case OMPC_shared:
  8136. case OMPC_aligned:
  8137. case OMPC_copyin:
  8138. case OMPC_copyprivate:
  8139. case OMPC_ordered:
  8140. case OMPC_nowait:
  8141. case OMPC_untied:
  8142. case OMPC_mergeable:
  8143. case OMPC_threadprivate:
  8144. case OMPC_flush:
  8145. case OMPC_read:
  8146. case OMPC_write:
  8147. case OMPC_update:
  8148. case OMPC_capture:
  8149. case OMPC_seq_cst:
  8150. case OMPC_depend:
  8151. case OMPC_threads:
  8152. case OMPC_simd:
  8153. case OMPC_map:
  8154. case OMPC_priority:
  8155. case OMPC_grainsize:
  8156. case OMPC_nogroup:
  8157. case OMPC_num_tasks:
  8158. case OMPC_hint:
  8159. case OMPC_defaultmap:
  8160. case OMPC_unknown:
  8161. case OMPC_uniform:
  8162. case OMPC_to:
  8163. case OMPC_from:
  8164. case OMPC_use_device_ptr:
  8165. case OMPC_is_device_ptr:
  8166. case OMPC_unified_address:
  8167. case OMPC_unified_shared_memory:
  8168. case OMPC_reverse_offload:
  8169. case OMPC_dynamic_allocators:
  8170. case OMPC_atomic_default_mem_order:
  8171. llvm_unreachable("Unexpected OpenMP clause.");
  8172. }
  8173. return CaptureRegion;
  8174. }
  8175. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  8176. Expr *Condition, SourceLocation StartLoc,
  8177. SourceLocation LParenLoc,
  8178. SourceLocation NameModifierLoc,
  8179. SourceLocation ColonLoc,
  8180. SourceLocation EndLoc) {
  8181. Expr *ValExpr = Condition;
  8182. Stmt *HelperValStmt = nullptr;
  8183. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  8184. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8185. !Condition->isInstantiationDependent() &&
  8186. !Condition->containsUnexpandedParameterPack()) {
  8187. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8188. if (Val.isInvalid())
  8189. return nullptr;
  8190. ValExpr = Val.get();
  8191. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8192. CaptureRegion =
  8193. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  8194. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8195. ValExpr = MakeFullExpr(ValExpr).get();
  8196. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8197. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8198. HelperValStmt = buildPreInits(Context, Captures);
  8199. }
  8200. }
  8201. return new (Context)
  8202. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  8203. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  8204. }
  8205. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  8206. SourceLocation StartLoc,
  8207. SourceLocation LParenLoc,
  8208. SourceLocation EndLoc) {
  8209. Expr *ValExpr = Condition;
  8210. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8211. !Condition->isInstantiationDependent() &&
  8212. !Condition->containsUnexpandedParameterPack()) {
  8213. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8214. if (Val.isInvalid())
  8215. return nullptr;
  8216. ValExpr = MakeFullExpr(Val.get()).get();
  8217. }
  8218. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8219. }
  8220. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  8221. Expr *Op) {
  8222. if (!Op)
  8223. return ExprError();
  8224. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  8225. public:
  8226. IntConvertDiagnoser()
  8227. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  8228. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  8229. QualType T) override {
  8230. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  8231. }
  8232. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  8233. QualType T) override {
  8234. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  8235. }
  8236. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  8237. QualType T,
  8238. QualType ConvTy) override {
  8239. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  8240. }
  8241. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  8242. QualType ConvTy) override {
  8243. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8244. << ConvTy->isEnumeralType() << ConvTy;
  8245. }
  8246. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  8247. QualType T) override {
  8248. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  8249. }
  8250. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  8251. QualType ConvTy) override {
  8252. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8253. << ConvTy->isEnumeralType() << ConvTy;
  8254. }
  8255. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  8256. QualType) override {
  8257. llvm_unreachable("conversion functions are permitted");
  8258. }
  8259. } ConvertDiagnoser;
  8260. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  8261. }
  8262. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  8263. OpenMPClauseKind CKind,
  8264. bool StrictlyPositive) {
  8265. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  8266. !ValExpr->isInstantiationDependent()) {
  8267. SourceLocation Loc = ValExpr->getExprLoc();
  8268. ExprResult Value =
  8269. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  8270. if (Value.isInvalid())
  8271. return false;
  8272. ValExpr = Value.get();
  8273. // The expression must evaluate to a non-negative integer value.
  8274. llvm::APSInt Result;
  8275. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  8276. Result.isSigned() &&
  8277. !((!StrictlyPositive && Result.isNonNegative()) ||
  8278. (StrictlyPositive && Result.isStrictlyPositive()))) {
  8279. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  8280. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8281. << ValExpr->getSourceRange();
  8282. return false;
  8283. }
  8284. }
  8285. return true;
  8286. }
  8287. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  8288. SourceLocation StartLoc,
  8289. SourceLocation LParenLoc,
  8290. SourceLocation EndLoc) {
  8291. Expr *ValExpr = NumThreads;
  8292. Stmt *HelperValStmt = nullptr;
  8293. // OpenMP [2.5, Restrictions]
  8294. // The num_threads expression must evaluate to a positive integer value.
  8295. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  8296. /*StrictlyPositive=*/true))
  8297. return nullptr;
  8298. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8299. OpenMPDirectiveKind CaptureRegion =
  8300. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  8301. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8302. ValExpr = MakeFullExpr(ValExpr).get();
  8303. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8304. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8305. HelperValStmt = buildPreInits(Context, Captures);
  8306. }
  8307. return new (Context) OMPNumThreadsClause(
  8308. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  8309. }
  8310. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  8311. OpenMPClauseKind CKind,
  8312. bool StrictlyPositive) {
  8313. if (!E)
  8314. return ExprError();
  8315. if (E->isValueDependent() || E->isTypeDependent() ||
  8316. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  8317. return E;
  8318. llvm::APSInt Result;
  8319. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  8320. if (ICE.isInvalid())
  8321. return ExprError();
  8322. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  8323. (!StrictlyPositive && !Result.isNonNegative())) {
  8324. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  8325. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8326. << E->getSourceRange();
  8327. return ExprError();
  8328. }
  8329. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  8330. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  8331. << E->getSourceRange();
  8332. return ExprError();
  8333. }
  8334. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  8335. DSAStack->setAssociatedLoops(Result.getExtValue());
  8336. else if (CKind == OMPC_ordered)
  8337. DSAStack->setAssociatedLoops(Result.getExtValue());
  8338. return ICE;
  8339. }
  8340. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  8341. SourceLocation LParenLoc,
  8342. SourceLocation EndLoc) {
  8343. // OpenMP [2.8.1, simd construct, Description]
  8344. // The parameter of the safelen clause must be a constant
  8345. // positive integer expression.
  8346. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  8347. if (Safelen.isInvalid())
  8348. return nullptr;
  8349. return new (Context)
  8350. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  8351. }
  8352. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  8353. SourceLocation LParenLoc,
  8354. SourceLocation EndLoc) {
  8355. // OpenMP [2.8.1, simd construct, Description]
  8356. // The parameter of the simdlen clause must be a constant
  8357. // positive integer expression.
  8358. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  8359. if (Simdlen.isInvalid())
  8360. return nullptr;
  8361. return new (Context)
  8362. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  8363. }
  8364. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  8365. SourceLocation StartLoc,
  8366. SourceLocation LParenLoc,
  8367. SourceLocation EndLoc) {
  8368. // OpenMP [2.7.1, loop construct, Description]
  8369. // OpenMP [2.8.1, simd construct, Description]
  8370. // OpenMP [2.9.6, distribute construct, Description]
  8371. // The parameter of the collapse clause must be a constant
  8372. // positive integer expression.
  8373. ExprResult NumForLoopsResult =
  8374. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  8375. if (NumForLoopsResult.isInvalid())
  8376. return nullptr;
  8377. return new (Context)
  8378. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  8379. }
  8380. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  8381. SourceLocation EndLoc,
  8382. SourceLocation LParenLoc,
  8383. Expr *NumForLoops) {
  8384. // OpenMP [2.7.1, loop construct, Description]
  8385. // OpenMP [2.8.1, simd construct, Description]
  8386. // OpenMP [2.9.6, distribute construct, Description]
  8387. // The parameter of the ordered clause must be a constant
  8388. // positive integer expression if any.
  8389. if (NumForLoops && LParenLoc.isValid()) {
  8390. ExprResult NumForLoopsResult =
  8391. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  8392. if (NumForLoopsResult.isInvalid())
  8393. return nullptr;
  8394. NumForLoops = NumForLoopsResult.get();
  8395. } else {
  8396. NumForLoops = nullptr;
  8397. }
  8398. auto *Clause = OMPOrderedClause::Create(
  8399. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  8400. StartLoc, LParenLoc, EndLoc);
  8401. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  8402. return Clause;
  8403. }
  8404. OMPClause *Sema::ActOnOpenMPSimpleClause(
  8405. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  8406. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8407. OMPClause *Res = nullptr;
  8408. switch (Kind) {
  8409. case OMPC_default:
  8410. Res =
  8411. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  8412. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8413. break;
  8414. case OMPC_proc_bind:
  8415. Res = ActOnOpenMPProcBindClause(
  8416. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  8417. LParenLoc, EndLoc);
  8418. break;
  8419. case OMPC_atomic_default_mem_order:
  8420. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  8421. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  8422. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8423. break;
  8424. case OMPC_if:
  8425. case OMPC_final:
  8426. case OMPC_num_threads:
  8427. case OMPC_safelen:
  8428. case OMPC_simdlen:
  8429. case OMPC_collapse:
  8430. case OMPC_schedule:
  8431. case OMPC_private:
  8432. case OMPC_firstprivate:
  8433. case OMPC_lastprivate:
  8434. case OMPC_shared:
  8435. case OMPC_reduction:
  8436. case OMPC_task_reduction:
  8437. case OMPC_in_reduction:
  8438. case OMPC_linear:
  8439. case OMPC_aligned:
  8440. case OMPC_copyin:
  8441. case OMPC_copyprivate:
  8442. case OMPC_ordered:
  8443. case OMPC_nowait:
  8444. case OMPC_untied:
  8445. case OMPC_mergeable:
  8446. case OMPC_threadprivate:
  8447. case OMPC_flush:
  8448. case OMPC_read:
  8449. case OMPC_write:
  8450. case OMPC_update:
  8451. case OMPC_capture:
  8452. case OMPC_seq_cst:
  8453. case OMPC_depend:
  8454. case OMPC_device:
  8455. case OMPC_threads:
  8456. case OMPC_simd:
  8457. case OMPC_map:
  8458. case OMPC_num_teams:
  8459. case OMPC_thread_limit:
  8460. case OMPC_priority:
  8461. case OMPC_grainsize:
  8462. case OMPC_nogroup:
  8463. case OMPC_num_tasks:
  8464. case OMPC_hint:
  8465. case OMPC_dist_schedule:
  8466. case OMPC_defaultmap:
  8467. case OMPC_unknown:
  8468. case OMPC_uniform:
  8469. case OMPC_to:
  8470. case OMPC_from:
  8471. case OMPC_use_device_ptr:
  8472. case OMPC_is_device_ptr:
  8473. case OMPC_unified_address:
  8474. case OMPC_unified_shared_memory:
  8475. case OMPC_reverse_offload:
  8476. case OMPC_dynamic_allocators:
  8477. llvm_unreachable("Clause is not allowed.");
  8478. }
  8479. return Res;
  8480. }
  8481. static std::string
  8482. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  8483. ArrayRef<unsigned> Exclude = llvm::None) {
  8484. SmallString<256> Buffer;
  8485. llvm::raw_svector_ostream Out(Buffer);
  8486. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  8487. unsigned Skipped = Exclude.size();
  8488. auto S = Exclude.begin(), E = Exclude.end();
  8489. for (unsigned I = First; I < Last; ++I) {
  8490. if (std::find(S, E, I) != E) {
  8491. --Skipped;
  8492. continue;
  8493. }
  8494. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  8495. if (I == Bound - Skipped)
  8496. Out << " or ";
  8497. else if (I != Bound + 1 - Skipped)
  8498. Out << ", ";
  8499. }
  8500. return Out.str();
  8501. }
  8502. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  8503. SourceLocation KindKwLoc,
  8504. SourceLocation StartLoc,
  8505. SourceLocation LParenLoc,
  8506. SourceLocation EndLoc) {
  8507. if (Kind == OMPC_DEFAULT_unknown) {
  8508. static_assert(OMPC_DEFAULT_unknown > 0,
  8509. "OMPC_DEFAULT_unknown not greater than 0");
  8510. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8511. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  8512. /*Last=*/OMPC_DEFAULT_unknown)
  8513. << getOpenMPClauseName(OMPC_default);
  8514. return nullptr;
  8515. }
  8516. switch (Kind) {
  8517. case OMPC_DEFAULT_none:
  8518. DSAStack->setDefaultDSANone(KindKwLoc);
  8519. break;
  8520. case OMPC_DEFAULT_shared:
  8521. DSAStack->setDefaultDSAShared(KindKwLoc);
  8522. break;
  8523. case OMPC_DEFAULT_unknown:
  8524. llvm_unreachable("Clause kind is not allowed.");
  8525. break;
  8526. }
  8527. return new (Context)
  8528. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8529. }
  8530. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  8531. SourceLocation KindKwLoc,
  8532. SourceLocation StartLoc,
  8533. SourceLocation LParenLoc,
  8534. SourceLocation EndLoc) {
  8535. if (Kind == OMPC_PROC_BIND_unknown) {
  8536. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8537. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  8538. /*Last=*/OMPC_PROC_BIND_unknown)
  8539. << getOpenMPClauseName(OMPC_proc_bind);
  8540. return nullptr;
  8541. }
  8542. return new (Context)
  8543. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8544. }
  8545. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  8546. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  8547. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8548. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  8549. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8550. << getListOfPossibleValues(
  8551. OMPC_atomic_default_mem_order, /*First=*/0,
  8552. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  8553. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  8554. return nullptr;
  8555. }
  8556. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  8557. LParenLoc, EndLoc);
  8558. }
  8559. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  8560. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  8561. SourceLocation StartLoc, SourceLocation LParenLoc,
  8562. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  8563. SourceLocation EndLoc) {
  8564. OMPClause *Res = nullptr;
  8565. switch (Kind) {
  8566. case OMPC_schedule:
  8567. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  8568. assert(Argument.size() == NumberOfElements &&
  8569. ArgumentLoc.size() == NumberOfElements);
  8570. Res = ActOnOpenMPScheduleClause(
  8571. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  8572. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  8573. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  8574. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  8575. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  8576. break;
  8577. case OMPC_if:
  8578. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  8579. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  8580. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  8581. DelimLoc, EndLoc);
  8582. break;
  8583. case OMPC_dist_schedule:
  8584. Res = ActOnOpenMPDistScheduleClause(
  8585. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  8586. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  8587. break;
  8588. case OMPC_defaultmap:
  8589. enum { Modifier, DefaultmapKind };
  8590. Res = ActOnOpenMPDefaultmapClause(
  8591. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  8592. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  8593. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  8594. EndLoc);
  8595. break;
  8596. case OMPC_final:
  8597. case OMPC_num_threads:
  8598. case OMPC_safelen:
  8599. case OMPC_simdlen:
  8600. case OMPC_collapse:
  8601. case OMPC_default:
  8602. case OMPC_proc_bind:
  8603. case OMPC_private:
  8604. case OMPC_firstprivate:
  8605. case OMPC_lastprivate:
  8606. case OMPC_shared:
  8607. case OMPC_reduction:
  8608. case OMPC_task_reduction:
  8609. case OMPC_in_reduction:
  8610. case OMPC_linear:
  8611. case OMPC_aligned:
  8612. case OMPC_copyin:
  8613. case OMPC_copyprivate:
  8614. case OMPC_ordered:
  8615. case OMPC_nowait:
  8616. case OMPC_untied:
  8617. case OMPC_mergeable:
  8618. case OMPC_threadprivate:
  8619. case OMPC_flush:
  8620. case OMPC_read:
  8621. case OMPC_write:
  8622. case OMPC_update:
  8623. case OMPC_capture:
  8624. case OMPC_seq_cst:
  8625. case OMPC_depend:
  8626. case OMPC_device:
  8627. case OMPC_threads:
  8628. case OMPC_simd:
  8629. case OMPC_map:
  8630. case OMPC_num_teams:
  8631. case OMPC_thread_limit:
  8632. case OMPC_priority:
  8633. case OMPC_grainsize:
  8634. case OMPC_nogroup:
  8635. case OMPC_num_tasks:
  8636. case OMPC_hint:
  8637. case OMPC_unknown:
  8638. case OMPC_uniform:
  8639. case OMPC_to:
  8640. case OMPC_from:
  8641. case OMPC_use_device_ptr:
  8642. case OMPC_is_device_ptr:
  8643. case OMPC_unified_address:
  8644. case OMPC_unified_shared_memory:
  8645. case OMPC_reverse_offload:
  8646. case OMPC_dynamic_allocators:
  8647. case OMPC_atomic_default_mem_order:
  8648. llvm_unreachable("Clause is not allowed.");
  8649. }
  8650. return Res;
  8651. }
  8652. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  8653. OpenMPScheduleClauseModifier M2,
  8654. SourceLocation M1Loc, SourceLocation M2Loc) {
  8655. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  8656. SmallVector<unsigned, 2> Excluded;
  8657. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  8658. Excluded.push_back(M2);
  8659. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  8660. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  8661. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  8662. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  8663. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  8664. << getListOfPossibleValues(OMPC_schedule,
  8665. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  8666. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8667. Excluded)
  8668. << getOpenMPClauseName(OMPC_schedule);
  8669. return true;
  8670. }
  8671. return false;
  8672. }
  8673. OMPClause *Sema::ActOnOpenMPScheduleClause(
  8674. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  8675. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8676. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  8677. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  8678. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  8679. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  8680. return nullptr;
  8681. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8682. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  8683. // but not both.
  8684. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  8685. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  8686. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  8687. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  8688. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  8689. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  8690. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  8691. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  8692. return nullptr;
  8693. }
  8694. if (Kind == OMPC_SCHEDULE_unknown) {
  8695. std::string Values;
  8696. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  8697. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  8698. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8699. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8700. Exclude);
  8701. } else {
  8702. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8703. /*Last=*/OMPC_SCHEDULE_unknown);
  8704. }
  8705. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8706. << Values << getOpenMPClauseName(OMPC_schedule);
  8707. return nullptr;
  8708. }
  8709. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8710. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8711. // schedule(guided).
  8712. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8713. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8714. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8715. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8716. diag::err_omp_schedule_nonmonotonic_static);
  8717. return nullptr;
  8718. }
  8719. Expr *ValExpr = ChunkSize;
  8720. Stmt *HelperValStmt = nullptr;
  8721. if (ChunkSize) {
  8722. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8723. !ChunkSize->isInstantiationDependent() &&
  8724. !ChunkSize->containsUnexpandedParameterPack()) {
  8725. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  8726. ExprResult Val =
  8727. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8728. if (Val.isInvalid())
  8729. return nullptr;
  8730. ValExpr = Val.get();
  8731. // OpenMP [2.7.1, Restrictions]
  8732. // chunk_size must be a loop invariant integer expression with a positive
  8733. // value.
  8734. llvm::APSInt Result;
  8735. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8736. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8737. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8738. << "schedule" << 1 << ChunkSize->getSourceRange();
  8739. return nullptr;
  8740. }
  8741. } else if (getOpenMPCaptureRegionForClause(
  8742. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8743. OMPD_unknown &&
  8744. !CurContext->isDependentContext()) {
  8745. ValExpr = MakeFullExpr(ValExpr).get();
  8746. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8747. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8748. HelperValStmt = buildPreInits(Context, Captures);
  8749. }
  8750. }
  8751. }
  8752. return new (Context)
  8753. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8754. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8755. }
  8756. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8757. SourceLocation StartLoc,
  8758. SourceLocation EndLoc) {
  8759. OMPClause *Res = nullptr;
  8760. switch (Kind) {
  8761. case OMPC_ordered:
  8762. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8763. break;
  8764. case OMPC_nowait:
  8765. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8766. break;
  8767. case OMPC_untied:
  8768. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8769. break;
  8770. case OMPC_mergeable:
  8771. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8772. break;
  8773. case OMPC_read:
  8774. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8775. break;
  8776. case OMPC_write:
  8777. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8778. break;
  8779. case OMPC_update:
  8780. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8781. break;
  8782. case OMPC_capture:
  8783. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8784. break;
  8785. case OMPC_seq_cst:
  8786. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8787. break;
  8788. case OMPC_threads:
  8789. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8790. break;
  8791. case OMPC_simd:
  8792. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8793. break;
  8794. case OMPC_nogroup:
  8795. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8796. break;
  8797. case OMPC_unified_address:
  8798. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  8799. break;
  8800. case OMPC_unified_shared_memory:
  8801. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  8802. break;
  8803. case OMPC_reverse_offload:
  8804. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  8805. break;
  8806. case OMPC_dynamic_allocators:
  8807. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  8808. break;
  8809. case OMPC_if:
  8810. case OMPC_final:
  8811. case OMPC_num_threads:
  8812. case OMPC_safelen:
  8813. case OMPC_simdlen:
  8814. case OMPC_collapse:
  8815. case OMPC_schedule:
  8816. case OMPC_private:
  8817. case OMPC_firstprivate:
  8818. case OMPC_lastprivate:
  8819. case OMPC_shared:
  8820. case OMPC_reduction:
  8821. case OMPC_task_reduction:
  8822. case OMPC_in_reduction:
  8823. case OMPC_linear:
  8824. case OMPC_aligned:
  8825. case OMPC_copyin:
  8826. case OMPC_copyprivate:
  8827. case OMPC_default:
  8828. case OMPC_proc_bind:
  8829. case OMPC_threadprivate:
  8830. case OMPC_flush:
  8831. case OMPC_depend:
  8832. case OMPC_device:
  8833. case OMPC_map:
  8834. case OMPC_num_teams:
  8835. case OMPC_thread_limit:
  8836. case OMPC_priority:
  8837. case OMPC_grainsize:
  8838. case OMPC_num_tasks:
  8839. case OMPC_hint:
  8840. case OMPC_dist_schedule:
  8841. case OMPC_defaultmap:
  8842. case OMPC_unknown:
  8843. case OMPC_uniform:
  8844. case OMPC_to:
  8845. case OMPC_from:
  8846. case OMPC_use_device_ptr:
  8847. case OMPC_is_device_ptr:
  8848. case OMPC_atomic_default_mem_order:
  8849. llvm_unreachable("Clause is not allowed.");
  8850. }
  8851. return Res;
  8852. }
  8853. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  8854. SourceLocation EndLoc) {
  8855. DSAStack->setNowaitRegion();
  8856. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  8857. }
  8858. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  8859. SourceLocation EndLoc) {
  8860. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  8861. }
  8862. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  8863. SourceLocation EndLoc) {
  8864. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  8865. }
  8866. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  8867. SourceLocation EndLoc) {
  8868. return new (Context) OMPReadClause(StartLoc, EndLoc);
  8869. }
  8870. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  8871. SourceLocation EndLoc) {
  8872. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  8873. }
  8874. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  8875. SourceLocation EndLoc) {
  8876. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  8877. }
  8878. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  8879. SourceLocation EndLoc) {
  8880. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  8881. }
  8882. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  8883. SourceLocation EndLoc) {
  8884. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  8885. }
  8886. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  8887. SourceLocation EndLoc) {
  8888. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  8889. }
  8890. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  8891. SourceLocation EndLoc) {
  8892. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  8893. }
  8894. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  8895. SourceLocation EndLoc) {
  8896. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  8897. }
  8898. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  8899. SourceLocation EndLoc) {
  8900. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  8901. }
  8902. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  8903. SourceLocation EndLoc) {
  8904. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  8905. }
  8906. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  8907. SourceLocation EndLoc) {
  8908. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  8909. }
  8910. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  8911. SourceLocation EndLoc) {
  8912. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  8913. }
  8914. OMPClause *Sema::ActOnOpenMPVarListClause(
  8915. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  8916. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  8917. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  8918. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  8919. OpenMPLinearClauseKind LinKind,
  8920. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  8921. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  8922. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8923. SourceLocation DepLinMapLoc) {
  8924. OMPClause *Res = nullptr;
  8925. switch (Kind) {
  8926. case OMPC_private:
  8927. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8928. break;
  8929. case OMPC_firstprivate:
  8930. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8931. break;
  8932. case OMPC_lastprivate:
  8933. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8934. break;
  8935. case OMPC_shared:
  8936. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  8937. break;
  8938. case OMPC_reduction:
  8939. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8940. EndLoc, ReductionIdScopeSpec, ReductionId);
  8941. break;
  8942. case OMPC_task_reduction:
  8943. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8944. EndLoc, ReductionIdScopeSpec,
  8945. ReductionId);
  8946. break;
  8947. case OMPC_in_reduction:
  8948. Res =
  8949. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8950. EndLoc, ReductionIdScopeSpec, ReductionId);
  8951. break;
  8952. case OMPC_linear:
  8953. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  8954. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  8955. break;
  8956. case OMPC_aligned:
  8957. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  8958. ColonLoc, EndLoc);
  8959. break;
  8960. case OMPC_copyin:
  8961. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  8962. break;
  8963. case OMPC_copyprivate:
  8964. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8965. break;
  8966. case OMPC_flush:
  8967. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  8968. break;
  8969. case OMPC_depend:
  8970. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  8971. StartLoc, LParenLoc, EndLoc);
  8972. break;
  8973. case OMPC_map:
  8974. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc, MapType,
  8975. IsMapTypeImplicit, DepLinMapLoc, ColonLoc,
  8976. VarList, StartLoc, LParenLoc, EndLoc);
  8977. break;
  8978. case OMPC_to:
  8979. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  8980. break;
  8981. case OMPC_from:
  8982. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  8983. break;
  8984. case OMPC_use_device_ptr:
  8985. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8986. break;
  8987. case OMPC_is_device_ptr:
  8988. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8989. break;
  8990. case OMPC_if:
  8991. case OMPC_final:
  8992. case OMPC_num_threads:
  8993. case OMPC_safelen:
  8994. case OMPC_simdlen:
  8995. case OMPC_collapse:
  8996. case OMPC_default:
  8997. case OMPC_proc_bind:
  8998. case OMPC_schedule:
  8999. case OMPC_ordered:
  9000. case OMPC_nowait:
  9001. case OMPC_untied:
  9002. case OMPC_mergeable:
  9003. case OMPC_threadprivate:
  9004. case OMPC_read:
  9005. case OMPC_write:
  9006. case OMPC_update:
  9007. case OMPC_capture:
  9008. case OMPC_seq_cst:
  9009. case OMPC_device:
  9010. case OMPC_threads:
  9011. case OMPC_simd:
  9012. case OMPC_num_teams:
  9013. case OMPC_thread_limit:
  9014. case OMPC_priority:
  9015. case OMPC_grainsize:
  9016. case OMPC_nogroup:
  9017. case OMPC_num_tasks:
  9018. case OMPC_hint:
  9019. case OMPC_dist_schedule:
  9020. case OMPC_defaultmap:
  9021. case OMPC_unknown:
  9022. case OMPC_uniform:
  9023. case OMPC_unified_address:
  9024. case OMPC_unified_shared_memory:
  9025. case OMPC_reverse_offload:
  9026. case OMPC_dynamic_allocators:
  9027. case OMPC_atomic_default_mem_order:
  9028. llvm_unreachable("Clause is not allowed.");
  9029. }
  9030. return Res;
  9031. }
  9032. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  9033. ExprObjectKind OK, SourceLocation Loc) {
  9034. ExprResult Res = BuildDeclRefExpr(
  9035. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  9036. if (!Res.isUsable())
  9037. return ExprError();
  9038. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  9039. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  9040. if (!Res.isUsable())
  9041. return ExprError();
  9042. }
  9043. if (VK != VK_LValue && Res.get()->isGLValue()) {
  9044. Res = DefaultLvalueConversion(Res.get());
  9045. if (!Res.isUsable())
  9046. return ExprError();
  9047. }
  9048. return Res;
  9049. }
  9050. static std::pair<ValueDecl *, bool>
  9051. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  9052. SourceRange &ERange, bool AllowArraySection = false) {
  9053. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  9054. RefExpr->containsUnexpandedParameterPack())
  9055. return std::make_pair(nullptr, true);
  9056. // OpenMP [3.1, C/C++]
  9057. // A list item is a variable name.
  9058. // OpenMP [2.9.3.3, Restrictions, p.1]
  9059. // A variable that is part of another variable (as an array or
  9060. // structure element) cannot appear in a private clause.
  9061. RefExpr = RefExpr->IgnoreParens();
  9062. enum {
  9063. NoArrayExpr = -1,
  9064. ArraySubscript = 0,
  9065. OMPArraySection = 1
  9066. } IsArrayExpr = NoArrayExpr;
  9067. if (AllowArraySection) {
  9068. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  9069. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  9070. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9071. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9072. RefExpr = Base;
  9073. IsArrayExpr = ArraySubscript;
  9074. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  9075. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9076. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  9077. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9078. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9079. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9080. RefExpr = Base;
  9081. IsArrayExpr = OMPArraySection;
  9082. }
  9083. }
  9084. ELoc = RefExpr->getExprLoc();
  9085. ERange = RefExpr->getSourceRange();
  9086. RefExpr = RefExpr->IgnoreParenImpCasts();
  9087. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  9088. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  9089. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  9090. (S.getCurrentThisType().isNull() || !ME ||
  9091. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  9092. !isa<FieldDecl>(ME->getMemberDecl()))) {
  9093. if (IsArrayExpr != NoArrayExpr) {
  9094. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  9095. << ERange;
  9096. } else {
  9097. S.Diag(ELoc,
  9098. AllowArraySection
  9099. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  9100. : diag::err_omp_expected_var_name_member_expr)
  9101. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  9102. }
  9103. return std::make_pair(nullptr, false);
  9104. }
  9105. return std::make_pair(
  9106. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  9107. }
  9108. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  9109. SourceLocation StartLoc,
  9110. SourceLocation LParenLoc,
  9111. SourceLocation EndLoc) {
  9112. SmallVector<Expr *, 8> Vars;
  9113. SmallVector<Expr *, 8> PrivateCopies;
  9114. for (Expr *RefExpr : VarList) {
  9115. assert(RefExpr && "NULL expr in OpenMP private clause.");
  9116. SourceLocation ELoc;
  9117. SourceRange ERange;
  9118. Expr *SimpleRefExpr = RefExpr;
  9119. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9120. if (Res.second) {
  9121. // It will be analyzed later.
  9122. Vars.push_back(RefExpr);
  9123. PrivateCopies.push_back(nullptr);
  9124. }
  9125. ValueDecl *D = Res.first;
  9126. if (!D)
  9127. continue;
  9128. QualType Type = D->getType();
  9129. auto *VD = dyn_cast<VarDecl>(D);
  9130. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9131. // A variable that appears in a private clause must not have an incomplete
  9132. // type or a reference type.
  9133. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  9134. continue;
  9135. Type = Type.getNonReferenceType();
  9136. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9137. // in a Construct]
  9138. // Variables with the predetermined data-sharing attributes may not be
  9139. // listed in data-sharing attributes clauses, except for the cases
  9140. // listed below. For these exceptions only, listing a predetermined
  9141. // variable in a data-sharing attribute clause is allowed and overrides
  9142. // the variable's predetermined data-sharing attributes.
  9143. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9144. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  9145. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9146. << getOpenMPClauseName(OMPC_private);
  9147. reportOriginalDsa(*this, DSAStack, D, DVar);
  9148. continue;
  9149. }
  9150. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9151. // Variably modified types are not supported for tasks.
  9152. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9153. isOpenMPTaskingDirective(CurrDir)) {
  9154. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9155. << getOpenMPClauseName(OMPC_private) << Type
  9156. << getOpenMPDirectiveName(CurrDir);
  9157. bool IsDecl =
  9158. !VD ||
  9159. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9160. Diag(D->getLocation(),
  9161. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9162. << D;
  9163. continue;
  9164. }
  9165. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9166. // A list item cannot appear in both a map clause and a data-sharing
  9167. // attribute clause on the same construct
  9168. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9169. OpenMPClauseKind ConflictKind;
  9170. if (DSAStack->checkMappableExprComponentListsForDecl(
  9171. VD, /*CurrentRegionOnly=*/true,
  9172. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9173. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  9174. ConflictKind = WhereFoundClauseKind;
  9175. return true;
  9176. })) {
  9177. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9178. << getOpenMPClauseName(OMPC_private)
  9179. << getOpenMPClauseName(ConflictKind)
  9180. << getOpenMPDirectiveName(CurrDir);
  9181. reportOriginalDsa(*this, DSAStack, D, DVar);
  9182. continue;
  9183. }
  9184. }
  9185. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  9186. // A variable of class type (or array thereof) that appears in a private
  9187. // clause requires an accessible, unambiguous default constructor for the
  9188. // class type.
  9189. // Generate helper private variable and initialize it with the default
  9190. // value. The address of the original variable is replaced by the address of
  9191. // the new private variable in CodeGen. This new variable is not added to
  9192. // IdResolver, so the code in the OpenMP region uses original variable for
  9193. // proper diagnostics.
  9194. Type = Type.getUnqualifiedType();
  9195. VarDecl *VDPrivate =
  9196. buildVarDecl(*this, ELoc, Type, D->getName(),
  9197. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9198. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9199. ActOnUninitializedDecl(VDPrivate);
  9200. if (VDPrivate->isInvalidDecl())
  9201. continue;
  9202. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9203. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  9204. DeclRefExpr *Ref = nullptr;
  9205. if (!VD && !CurContext->isDependentContext())
  9206. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9207. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  9208. Vars.push_back((VD || CurContext->isDependentContext())
  9209. ? RefExpr->IgnoreParens()
  9210. : Ref);
  9211. PrivateCopies.push_back(VDPrivateRefExpr);
  9212. }
  9213. if (Vars.empty())
  9214. return nullptr;
  9215. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  9216. PrivateCopies);
  9217. }
  9218. namespace {
  9219. class DiagsUninitializedSeveretyRAII {
  9220. private:
  9221. DiagnosticsEngine &Diags;
  9222. SourceLocation SavedLoc;
  9223. bool IsIgnored = false;
  9224. public:
  9225. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  9226. bool IsIgnored)
  9227. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  9228. if (!IsIgnored) {
  9229. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  9230. /*Map*/ diag::Severity::Ignored, Loc);
  9231. }
  9232. }
  9233. ~DiagsUninitializedSeveretyRAII() {
  9234. if (!IsIgnored)
  9235. Diags.popMappings(SavedLoc);
  9236. }
  9237. };
  9238. }
  9239. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  9240. SourceLocation StartLoc,
  9241. SourceLocation LParenLoc,
  9242. SourceLocation EndLoc) {
  9243. SmallVector<Expr *, 8> Vars;
  9244. SmallVector<Expr *, 8> PrivateCopies;
  9245. SmallVector<Expr *, 8> Inits;
  9246. SmallVector<Decl *, 4> ExprCaptures;
  9247. bool IsImplicitClause =
  9248. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  9249. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  9250. for (Expr *RefExpr : VarList) {
  9251. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  9252. SourceLocation ELoc;
  9253. SourceRange ERange;
  9254. Expr *SimpleRefExpr = RefExpr;
  9255. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9256. if (Res.second) {
  9257. // It will be analyzed later.
  9258. Vars.push_back(RefExpr);
  9259. PrivateCopies.push_back(nullptr);
  9260. Inits.push_back(nullptr);
  9261. }
  9262. ValueDecl *D = Res.first;
  9263. if (!D)
  9264. continue;
  9265. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  9266. QualType Type = D->getType();
  9267. auto *VD = dyn_cast<VarDecl>(D);
  9268. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9269. // A variable that appears in a private clause must not have an incomplete
  9270. // type or a reference type.
  9271. if (RequireCompleteType(ELoc, Type,
  9272. diag::err_omp_firstprivate_incomplete_type))
  9273. continue;
  9274. Type = Type.getNonReferenceType();
  9275. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  9276. // A variable of class type (or array thereof) that appears in a private
  9277. // clause requires an accessible, unambiguous copy constructor for the
  9278. // class type.
  9279. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  9280. // If an implicit firstprivate variable found it was checked already.
  9281. DSAStackTy::DSAVarData TopDVar;
  9282. if (!IsImplicitClause) {
  9283. DSAStackTy::DSAVarData DVar =
  9284. DSAStack->getTopDSA(D, /*FromParent=*/false);
  9285. TopDVar = DVar;
  9286. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9287. bool IsConstant = ElemType.isConstant(Context);
  9288. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  9289. // A list item that specifies a given variable may not appear in more
  9290. // than one clause on the same directive, except that a variable may be
  9291. // specified in both firstprivate and lastprivate clauses.
  9292. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9293. // A list item may appear in a firstprivate or lastprivate clause but not
  9294. // both.
  9295. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  9296. (isOpenMPDistributeDirective(CurrDir) ||
  9297. DVar.CKind != OMPC_lastprivate) &&
  9298. DVar.RefExpr) {
  9299. Diag(ELoc, diag::err_omp_wrong_dsa)
  9300. << getOpenMPClauseName(DVar.CKind)
  9301. << getOpenMPClauseName(OMPC_firstprivate);
  9302. reportOriginalDsa(*this, DSAStack, D, DVar);
  9303. continue;
  9304. }
  9305. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9306. // in a Construct]
  9307. // Variables with the predetermined data-sharing attributes may not be
  9308. // listed in data-sharing attributes clauses, except for the cases
  9309. // listed below. For these exceptions only, listing a predetermined
  9310. // variable in a data-sharing attribute clause is allowed and overrides
  9311. // the variable's predetermined data-sharing attributes.
  9312. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9313. // in a Construct, C/C++, p.2]
  9314. // Variables with const-qualified type having no mutable member may be
  9315. // listed in a firstprivate clause, even if they are static data members.
  9316. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  9317. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  9318. Diag(ELoc, diag::err_omp_wrong_dsa)
  9319. << getOpenMPClauseName(DVar.CKind)
  9320. << getOpenMPClauseName(OMPC_firstprivate);
  9321. reportOriginalDsa(*this, DSAStack, D, DVar);
  9322. continue;
  9323. }
  9324. // OpenMP [2.9.3.4, Restrictions, p.2]
  9325. // A list item that is private within a parallel region must not appear
  9326. // in a firstprivate clause on a worksharing construct if any of the
  9327. // worksharing regions arising from the worksharing construct ever bind
  9328. // to any of the parallel regions arising from the parallel construct.
  9329. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9330. // A list item that is private within a teams region must not appear in a
  9331. // firstprivate clause on a distribute construct if any of the distribute
  9332. // regions arising from the distribute construct ever bind to any of the
  9333. // teams regions arising from the teams construct.
  9334. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9335. // A list item that appears in a reduction clause of a teams construct
  9336. // must not appear in a firstprivate clause on a distribute construct if
  9337. // any of the distribute regions arising from the distribute construct
  9338. // ever bind to any of the teams regions arising from the teams construct.
  9339. if ((isOpenMPWorksharingDirective(CurrDir) ||
  9340. isOpenMPDistributeDirective(CurrDir)) &&
  9341. !isOpenMPParallelDirective(CurrDir) &&
  9342. !isOpenMPTeamsDirective(CurrDir)) {
  9343. DVar = DSAStack->getImplicitDSA(D, true);
  9344. if (DVar.CKind != OMPC_shared &&
  9345. (isOpenMPParallelDirective(DVar.DKind) ||
  9346. isOpenMPTeamsDirective(DVar.DKind) ||
  9347. DVar.DKind == OMPD_unknown)) {
  9348. Diag(ELoc, diag::err_omp_required_access)
  9349. << getOpenMPClauseName(OMPC_firstprivate)
  9350. << getOpenMPClauseName(OMPC_shared);
  9351. reportOriginalDsa(*this, DSAStack, D, DVar);
  9352. continue;
  9353. }
  9354. }
  9355. // OpenMP [2.9.3.4, Restrictions, p.3]
  9356. // A list item that appears in a reduction clause of a parallel construct
  9357. // must not appear in a firstprivate clause on a worksharing or task
  9358. // construct if any of the worksharing or task regions arising from the
  9359. // worksharing or task construct ever bind to any of the parallel regions
  9360. // arising from the parallel construct.
  9361. // OpenMP [2.9.3.4, Restrictions, p.4]
  9362. // A list item that appears in a reduction clause in worksharing
  9363. // construct must not appear in a firstprivate clause in a task construct
  9364. // encountered during execution of any of the worksharing regions arising
  9365. // from the worksharing construct.
  9366. if (isOpenMPTaskingDirective(CurrDir)) {
  9367. DVar = DSAStack->hasInnermostDSA(
  9368. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  9369. [](OpenMPDirectiveKind K) {
  9370. return isOpenMPParallelDirective(K) ||
  9371. isOpenMPWorksharingDirective(K) ||
  9372. isOpenMPTeamsDirective(K);
  9373. },
  9374. /*FromParent=*/true);
  9375. if (DVar.CKind == OMPC_reduction &&
  9376. (isOpenMPParallelDirective(DVar.DKind) ||
  9377. isOpenMPWorksharingDirective(DVar.DKind) ||
  9378. isOpenMPTeamsDirective(DVar.DKind))) {
  9379. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  9380. << getOpenMPDirectiveName(DVar.DKind);
  9381. reportOriginalDsa(*this, DSAStack, D, DVar);
  9382. continue;
  9383. }
  9384. }
  9385. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9386. // A list item cannot appear in both a map clause and a data-sharing
  9387. // attribute clause on the same construct
  9388. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9389. OpenMPClauseKind ConflictKind;
  9390. if (DSAStack->checkMappableExprComponentListsForDecl(
  9391. VD, /*CurrentRegionOnly=*/true,
  9392. [&ConflictKind](
  9393. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9394. OpenMPClauseKind WhereFoundClauseKind) {
  9395. ConflictKind = WhereFoundClauseKind;
  9396. return true;
  9397. })) {
  9398. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9399. << getOpenMPClauseName(OMPC_firstprivate)
  9400. << getOpenMPClauseName(ConflictKind)
  9401. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9402. reportOriginalDsa(*this, DSAStack, D, DVar);
  9403. continue;
  9404. }
  9405. }
  9406. }
  9407. // Variably modified types are not supported for tasks.
  9408. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9409. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  9410. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9411. << getOpenMPClauseName(OMPC_firstprivate) << Type
  9412. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9413. bool IsDecl =
  9414. !VD ||
  9415. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9416. Diag(D->getLocation(),
  9417. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9418. << D;
  9419. continue;
  9420. }
  9421. Type = Type.getUnqualifiedType();
  9422. VarDecl *VDPrivate =
  9423. buildVarDecl(*this, ELoc, Type, D->getName(),
  9424. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9425. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9426. // Generate helper private variable and initialize it with the value of the
  9427. // original variable. The address of the original variable is replaced by
  9428. // the address of the new private variable in the CodeGen. This new variable
  9429. // is not added to IdResolver, so the code in the OpenMP region uses
  9430. // original variable for proper diagnostics and variable capturing.
  9431. Expr *VDInitRefExpr = nullptr;
  9432. // For arrays generate initializer for single element and replace it by the
  9433. // original array element in CodeGen.
  9434. if (Type->isArrayType()) {
  9435. VarDecl *VDInit =
  9436. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  9437. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  9438. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  9439. ElemType = ElemType.getUnqualifiedType();
  9440. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  9441. ".firstprivate.temp");
  9442. InitializedEntity Entity =
  9443. InitializedEntity::InitializeVariable(VDInitTemp);
  9444. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  9445. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  9446. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  9447. if (Result.isInvalid())
  9448. VDPrivate->setInvalidDecl();
  9449. else
  9450. VDPrivate->setInit(Result.getAs<Expr>());
  9451. // Remove temp variable declaration.
  9452. Context.Deallocate(VDInitTemp);
  9453. } else {
  9454. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  9455. ".firstprivate.temp");
  9456. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  9457. RefExpr->getExprLoc());
  9458. AddInitializerToDecl(VDPrivate,
  9459. DefaultLvalueConversion(VDInitRefExpr).get(),
  9460. /*DirectInit=*/false);
  9461. }
  9462. if (VDPrivate->isInvalidDecl()) {
  9463. if (IsImplicitClause) {
  9464. Diag(RefExpr->getExprLoc(),
  9465. diag::note_omp_task_predetermined_firstprivate_here);
  9466. }
  9467. continue;
  9468. }
  9469. CurContext->addDecl(VDPrivate);
  9470. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9471. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  9472. RefExpr->getExprLoc());
  9473. DeclRefExpr *Ref = nullptr;
  9474. if (!VD && !CurContext->isDependentContext()) {
  9475. if (TopDVar.CKind == OMPC_lastprivate) {
  9476. Ref = TopDVar.PrivateCopy;
  9477. } else {
  9478. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9479. if (!isOpenMPCapturedDecl(D))
  9480. ExprCaptures.push_back(Ref->getDecl());
  9481. }
  9482. }
  9483. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  9484. Vars.push_back((VD || CurContext->isDependentContext())
  9485. ? RefExpr->IgnoreParens()
  9486. : Ref);
  9487. PrivateCopies.push_back(VDPrivateRefExpr);
  9488. Inits.push_back(VDInitRefExpr);
  9489. }
  9490. if (Vars.empty())
  9491. return nullptr;
  9492. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9493. Vars, PrivateCopies, Inits,
  9494. buildPreInits(Context, ExprCaptures));
  9495. }
  9496. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  9497. SourceLocation StartLoc,
  9498. SourceLocation LParenLoc,
  9499. SourceLocation EndLoc) {
  9500. SmallVector<Expr *, 8> Vars;
  9501. SmallVector<Expr *, 8> SrcExprs;
  9502. SmallVector<Expr *, 8> DstExprs;
  9503. SmallVector<Expr *, 8> AssignmentOps;
  9504. SmallVector<Decl *, 4> ExprCaptures;
  9505. SmallVector<Expr *, 4> ExprPostUpdates;
  9506. for (Expr *RefExpr : VarList) {
  9507. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9508. SourceLocation ELoc;
  9509. SourceRange ERange;
  9510. Expr *SimpleRefExpr = RefExpr;
  9511. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9512. if (Res.second) {
  9513. // It will be analyzed later.
  9514. Vars.push_back(RefExpr);
  9515. SrcExprs.push_back(nullptr);
  9516. DstExprs.push_back(nullptr);
  9517. AssignmentOps.push_back(nullptr);
  9518. }
  9519. ValueDecl *D = Res.first;
  9520. if (!D)
  9521. continue;
  9522. QualType Type = D->getType();
  9523. auto *VD = dyn_cast<VarDecl>(D);
  9524. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  9525. // A variable that appears in a lastprivate clause must not have an
  9526. // incomplete type or a reference type.
  9527. if (RequireCompleteType(ELoc, Type,
  9528. diag::err_omp_lastprivate_incomplete_type))
  9529. continue;
  9530. Type = Type.getNonReferenceType();
  9531. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9532. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9533. // in a Construct]
  9534. // Variables with the predetermined data-sharing attributes may not be
  9535. // listed in data-sharing attributes clauses, except for the cases
  9536. // listed below.
  9537. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9538. // A list item may appear in a firstprivate or lastprivate clause but not
  9539. // both.
  9540. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9541. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  9542. (isOpenMPDistributeDirective(CurrDir) ||
  9543. DVar.CKind != OMPC_firstprivate) &&
  9544. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  9545. Diag(ELoc, diag::err_omp_wrong_dsa)
  9546. << getOpenMPClauseName(DVar.CKind)
  9547. << getOpenMPClauseName(OMPC_lastprivate);
  9548. reportOriginalDsa(*this, DSAStack, D, DVar);
  9549. continue;
  9550. }
  9551. // OpenMP [2.14.3.5, Restrictions, p.2]
  9552. // A list item that is private within a parallel region, or that appears in
  9553. // the reduction clause of a parallel construct, must not appear in a
  9554. // lastprivate clause on a worksharing construct if any of the corresponding
  9555. // worksharing regions ever binds to any of the corresponding parallel
  9556. // regions.
  9557. DSAStackTy::DSAVarData TopDVar = DVar;
  9558. if (isOpenMPWorksharingDirective(CurrDir) &&
  9559. !isOpenMPParallelDirective(CurrDir) &&
  9560. !isOpenMPTeamsDirective(CurrDir)) {
  9561. DVar = DSAStack->getImplicitDSA(D, true);
  9562. if (DVar.CKind != OMPC_shared) {
  9563. Diag(ELoc, diag::err_omp_required_access)
  9564. << getOpenMPClauseName(OMPC_lastprivate)
  9565. << getOpenMPClauseName(OMPC_shared);
  9566. reportOriginalDsa(*this, DSAStack, D, DVar);
  9567. continue;
  9568. }
  9569. }
  9570. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  9571. // A variable of class type (or array thereof) that appears in a
  9572. // lastprivate clause requires an accessible, unambiguous default
  9573. // constructor for the class type, unless the list item is also specified
  9574. // in a firstprivate clause.
  9575. // A variable of class type (or array thereof) that appears in a
  9576. // lastprivate clause requires an accessible, unambiguous copy assignment
  9577. // operator for the class type.
  9578. Type = Context.getBaseElementType(Type).getNonReferenceType();
  9579. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  9580. Type.getUnqualifiedType(), ".lastprivate.src",
  9581. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9582. DeclRefExpr *PseudoSrcExpr =
  9583. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  9584. VarDecl *DstVD =
  9585. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  9586. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9587. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  9588. // For arrays generate assignment operation for single element and replace
  9589. // it by the original array element in CodeGen.
  9590. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  9591. PseudoDstExpr, PseudoSrcExpr);
  9592. if (AssignmentOp.isInvalid())
  9593. continue;
  9594. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  9595. /*DiscardedValue=*/true);
  9596. if (AssignmentOp.isInvalid())
  9597. continue;
  9598. DeclRefExpr *Ref = nullptr;
  9599. if (!VD && !CurContext->isDependentContext()) {
  9600. if (TopDVar.CKind == OMPC_firstprivate) {
  9601. Ref = TopDVar.PrivateCopy;
  9602. } else {
  9603. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9604. if (!isOpenMPCapturedDecl(D))
  9605. ExprCaptures.push_back(Ref->getDecl());
  9606. }
  9607. if (TopDVar.CKind == OMPC_firstprivate ||
  9608. (!isOpenMPCapturedDecl(D) &&
  9609. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  9610. ExprResult RefRes = DefaultLvalueConversion(Ref);
  9611. if (!RefRes.isUsable())
  9612. continue;
  9613. ExprResult PostUpdateRes =
  9614. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9615. RefRes.get());
  9616. if (!PostUpdateRes.isUsable())
  9617. continue;
  9618. ExprPostUpdates.push_back(
  9619. IgnoredValueConversions(PostUpdateRes.get()).get());
  9620. }
  9621. }
  9622. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  9623. Vars.push_back((VD || CurContext->isDependentContext())
  9624. ? RefExpr->IgnoreParens()
  9625. : Ref);
  9626. SrcExprs.push_back(PseudoSrcExpr);
  9627. DstExprs.push_back(PseudoDstExpr);
  9628. AssignmentOps.push_back(AssignmentOp.get());
  9629. }
  9630. if (Vars.empty())
  9631. return nullptr;
  9632. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9633. Vars, SrcExprs, DstExprs, AssignmentOps,
  9634. buildPreInits(Context, ExprCaptures),
  9635. buildPostUpdate(*this, ExprPostUpdates));
  9636. }
  9637. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  9638. SourceLocation StartLoc,
  9639. SourceLocation LParenLoc,
  9640. SourceLocation EndLoc) {
  9641. SmallVector<Expr *, 8> Vars;
  9642. for (Expr *RefExpr : VarList) {
  9643. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9644. SourceLocation ELoc;
  9645. SourceRange ERange;
  9646. Expr *SimpleRefExpr = RefExpr;
  9647. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9648. if (Res.second) {
  9649. // It will be analyzed later.
  9650. Vars.push_back(RefExpr);
  9651. }
  9652. ValueDecl *D = Res.first;
  9653. if (!D)
  9654. continue;
  9655. auto *VD = dyn_cast<VarDecl>(D);
  9656. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9657. // in a Construct]
  9658. // Variables with the predetermined data-sharing attributes may not be
  9659. // listed in data-sharing attributes clauses, except for the cases
  9660. // listed below. For these exceptions only, listing a predetermined
  9661. // variable in a data-sharing attribute clause is allowed and overrides
  9662. // the variable's predetermined data-sharing attributes.
  9663. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9664. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  9665. DVar.RefExpr) {
  9666. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9667. << getOpenMPClauseName(OMPC_shared);
  9668. reportOriginalDsa(*this, DSAStack, D, DVar);
  9669. continue;
  9670. }
  9671. DeclRefExpr *Ref = nullptr;
  9672. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  9673. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9674. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  9675. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  9676. ? RefExpr->IgnoreParens()
  9677. : Ref);
  9678. }
  9679. if (Vars.empty())
  9680. return nullptr;
  9681. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  9682. }
  9683. namespace {
  9684. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  9685. DSAStackTy *Stack;
  9686. public:
  9687. bool VisitDeclRefExpr(DeclRefExpr *E) {
  9688. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  9689. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  9690. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  9691. return false;
  9692. if (DVar.CKind != OMPC_unknown)
  9693. return true;
  9694. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  9695. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  9696. /*FromParent=*/true);
  9697. return DVarPrivate.CKind != OMPC_unknown;
  9698. }
  9699. return false;
  9700. }
  9701. bool VisitStmt(Stmt *S) {
  9702. for (Stmt *Child : S->children()) {
  9703. if (Child && Visit(Child))
  9704. return true;
  9705. }
  9706. return false;
  9707. }
  9708. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  9709. };
  9710. } // namespace
  9711. namespace {
  9712. // Transform MemberExpression for specified FieldDecl of current class to
  9713. // DeclRefExpr to specified OMPCapturedExprDecl.
  9714. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  9715. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  9716. ValueDecl *Field = nullptr;
  9717. DeclRefExpr *CapturedExpr = nullptr;
  9718. public:
  9719. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  9720. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  9721. ExprResult TransformMemberExpr(MemberExpr *E) {
  9722. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  9723. E->getMemberDecl() == Field) {
  9724. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  9725. return CapturedExpr;
  9726. }
  9727. return BaseTransform::TransformMemberExpr(E);
  9728. }
  9729. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  9730. };
  9731. } // namespace
  9732. template <typename T, typename U>
  9733. static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
  9734. const llvm::function_ref<T(ValueDecl *)> Gen) {
  9735. for (U &Set : Lookups) {
  9736. for (auto *D : Set) {
  9737. if (T Res = Gen(cast<ValueDecl>(D)))
  9738. return Res;
  9739. }
  9740. }
  9741. return T();
  9742. }
  9743. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  9744. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  9745. for (auto RD : D->redecls()) {
  9746. // Don't bother with extra checks if we already know this one isn't visible.
  9747. if (RD == D)
  9748. continue;
  9749. auto ND = cast<NamedDecl>(RD);
  9750. if (LookupResult::isVisible(SemaRef, ND))
  9751. return ND;
  9752. }
  9753. return nullptr;
  9754. }
  9755. static void
  9756. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId,
  9757. SourceLocation Loc, QualType Ty,
  9758. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  9759. // Find all of the associated namespaces and classes based on the
  9760. // arguments we have.
  9761. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  9762. Sema::AssociatedClassSet AssociatedClasses;
  9763. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  9764. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  9765. AssociatedClasses);
  9766. // C++ [basic.lookup.argdep]p3:
  9767. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  9768. // and let Y be the lookup set produced by argument dependent
  9769. // lookup (defined as follows). If X contains [...] then Y is
  9770. // empty. Otherwise Y is the set of declarations found in the
  9771. // namespaces associated with the argument types as described
  9772. // below. The set of declarations found by the lookup of the name
  9773. // is the union of X and Y.
  9774. //
  9775. // Here, we compute Y and add its members to the overloaded
  9776. // candidate set.
  9777. for (auto *NS : AssociatedNamespaces) {
  9778. // When considering an associated namespace, the lookup is the
  9779. // same as the lookup performed when the associated namespace is
  9780. // used as a qualifier (3.4.3.2) except that:
  9781. //
  9782. // -- Any using-directives in the associated namespace are
  9783. // ignored.
  9784. //
  9785. // -- Any namespace-scope friend functions declared in
  9786. // associated classes are visible within their respective
  9787. // namespaces even if they are not visible during an ordinary
  9788. // lookup (11.4).
  9789. DeclContext::lookup_result R = NS->lookup(ReductionId.getName());
  9790. for (auto *D : R) {
  9791. auto *Underlying = D;
  9792. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  9793. Underlying = USD->getTargetDecl();
  9794. if (!isa<OMPDeclareReductionDecl>(Underlying))
  9795. continue;
  9796. if (!SemaRef.isVisible(D)) {
  9797. D = findAcceptableDecl(SemaRef, D);
  9798. if (!D)
  9799. continue;
  9800. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  9801. Underlying = USD->getTargetDecl();
  9802. }
  9803. Lookups.emplace_back();
  9804. Lookups.back().addDecl(Underlying);
  9805. }
  9806. }
  9807. }
  9808. static ExprResult
  9809. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  9810. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  9811. const DeclarationNameInfo &ReductionId, QualType Ty,
  9812. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  9813. if (ReductionIdScopeSpec.isInvalid())
  9814. return ExprError();
  9815. SmallVector<UnresolvedSet<8>, 4> Lookups;
  9816. if (S) {
  9817. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9818. Lookup.suppressDiagnostics();
  9819. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  9820. NamedDecl *D = Lookup.getRepresentativeDecl();
  9821. do {
  9822. S = S->getParent();
  9823. } while (S && !S->isDeclScope(D));
  9824. if (S)
  9825. S = S->getParent();
  9826. Lookups.emplace_back();
  9827. Lookups.back().append(Lookup.begin(), Lookup.end());
  9828. Lookup.clear();
  9829. }
  9830. } else if (auto *ULE =
  9831. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  9832. Lookups.push_back(UnresolvedSet<8>());
  9833. Decl *PrevD = nullptr;
  9834. for (NamedDecl *D : ULE->decls()) {
  9835. if (D == PrevD)
  9836. Lookups.push_back(UnresolvedSet<8>());
  9837. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  9838. Lookups.back().addDecl(DRD);
  9839. PrevD = D;
  9840. }
  9841. }
  9842. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  9843. Ty->isInstantiationDependentType() ||
  9844. Ty->containsUnexpandedParameterPack() ||
  9845. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
  9846. return !D->isInvalidDecl() &&
  9847. (D->getType()->isDependentType() ||
  9848. D->getType()->isInstantiationDependentType() ||
  9849. D->getType()->containsUnexpandedParameterPack());
  9850. })) {
  9851. UnresolvedSet<8> ResSet;
  9852. for (const UnresolvedSet<8> &Set : Lookups) {
  9853. if (Set.empty())
  9854. continue;
  9855. ResSet.append(Set.begin(), Set.end());
  9856. // The last item marks the end of all declarations at the specified scope.
  9857. ResSet.addDecl(Set[Set.size() - 1]);
  9858. }
  9859. return UnresolvedLookupExpr::Create(
  9860. SemaRef.Context, /*NamingClass=*/nullptr,
  9861. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  9862. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  9863. }
  9864. // Lookup inside the classes.
  9865. // C++ [over.match.oper]p3:
  9866. // For a unary operator @ with an operand of a type whose
  9867. // cv-unqualified version is T1, and for a binary operator @ with
  9868. // a left operand of a type whose cv-unqualified version is T1 and
  9869. // a right operand of a type whose cv-unqualified version is T2,
  9870. // three sets of candidate functions, designated member
  9871. // candidates, non-member candidates and built-in candidates, are
  9872. // constructed as follows:
  9873. // -- If T1 is a complete class type or a class currently being
  9874. // defined, the set of member candidates is the result of the
  9875. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  9876. // the set of member candidates is empty.
  9877. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9878. Lookup.suppressDiagnostics();
  9879. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  9880. // Complete the type if it can be completed.
  9881. // If the type is neither complete nor being defined, bail out now.
  9882. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  9883. TyRec->getDecl()->getDefinition()) {
  9884. Lookup.clear();
  9885. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  9886. if (Lookup.empty()) {
  9887. Lookups.emplace_back();
  9888. Lookups.back().append(Lookup.begin(), Lookup.end());
  9889. }
  9890. }
  9891. }
  9892. // Perform ADL.
  9893. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  9894. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9895. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  9896. if (!D->isInvalidDecl() &&
  9897. SemaRef.Context.hasSameType(D->getType(), Ty))
  9898. return D;
  9899. return nullptr;
  9900. }))
  9901. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9902. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9903. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  9904. if (!D->isInvalidDecl() &&
  9905. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  9906. !Ty.isMoreQualifiedThan(D->getType()))
  9907. return D;
  9908. return nullptr;
  9909. })) {
  9910. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  9911. /*DetectVirtual=*/false);
  9912. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  9913. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  9914. VD->getType().getUnqualifiedType()))) {
  9915. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  9916. /*DiagID=*/0) !=
  9917. Sema::AR_inaccessible) {
  9918. SemaRef.BuildBasePathArray(Paths, BasePath);
  9919. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9920. }
  9921. }
  9922. }
  9923. }
  9924. if (ReductionIdScopeSpec.isSet()) {
  9925. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  9926. return ExprError();
  9927. }
  9928. return ExprEmpty();
  9929. }
  9930. namespace {
  9931. /// Data for the reduction-based clauses.
  9932. struct ReductionData {
  9933. /// List of original reduction items.
  9934. SmallVector<Expr *, 8> Vars;
  9935. /// List of private copies of the reduction items.
  9936. SmallVector<Expr *, 8> Privates;
  9937. /// LHS expressions for the reduction_op expressions.
  9938. SmallVector<Expr *, 8> LHSs;
  9939. /// RHS expressions for the reduction_op expressions.
  9940. SmallVector<Expr *, 8> RHSs;
  9941. /// Reduction operation expression.
  9942. SmallVector<Expr *, 8> ReductionOps;
  9943. /// Taskgroup descriptors for the corresponding reduction items in
  9944. /// in_reduction clauses.
  9945. SmallVector<Expr *, 8> TaskgroupDescriptors;
  9946. /// List of captures for clause.
  9947. SmallVector<Decl *, 4> ExprCaptures;
  9948. /// List of postupdate expressions.
  9949. SmallVector<Expr *, 4> ExprPostUpdates;
  9950. ReductionData() = delete;
  9951. /// Reserves required memory for the reduction data.
  9952. ReductionData(unsigned Size) {
  9953. Vars.reserve(Size);
  9954. Privates.reserve(Size);
  9955. LHSs.reserve(Size);
  9956. RHSs.reserve(Size);
  9957. ReductionOps.reserve(Size);
  9958. TaskgroupDescriptors.reserve(Size);
  9959. ExprCaptures.reserve(Size);
  9960. ExprPostUpdates.reserve(Size);
  9961. }
  9962. /// Stores reduction item and reduction operation only (required for dependent
  9963. /// reduction item).
  9964. void push(Expr *Item, Expr *ReductionOp) {
  9965. Vars.emplace_back(Item);
  9966. Privates.emplace_back(nullptr);
  9967. LHSs.emplace_back(nullptr);
  9968. RHSs.emplace_back(nullptr);
  9969. ReductionOps.emplace_back(ReductionOp);
  9970. TaskgroupDescriptors.emplace_back(nullptr);
  9971. }
  9972. /// Stores reduction data.
  9973. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  9974. Expr *TaskgroupDescriptor) {
  9975. Vars.emplace_back(Item);
  9976. Privates.emplace_back(Private);
  9977. LHSs.emplace_back(LHS);
  9978. RHSs.emplace_back(RHS);
  9979. ReductionOps.emplace_back(ReductionOp);
  9980. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  9981. }
  9982. };
  9983. } // namespace
  9984. static bool checkOMPArraySectionConstantForReduction(
  9985. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  9986. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  9987. const Expr *Length = OASE->getLength();
  9988. if (Length == nullptr) {
  9989. // For array sections of the form [1:] or [:], we would need to analyze
  9990. // the lower bound...
  9991. if (OASE->getColonLoc().isValid())
  9992. return false;
  9993. // This is an array subscript which has implicit length 1!
  9994. SingleElement = true;
  9995. ArraySizes.push_back(llvm::APSInt::get(1));
  9996. } else {
  9997. Expr::EvalResult Result;
  9998. if (!Length->EvaluateAsInt(Result, Context))
  9999. return false;
  10000. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  10001. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  10002. ArraySizes.push_back(ConstantLengthValue);
  10003. }
  10004. // Get the base of this array section and walk up from there.
  10005. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  10006. // We require length = 1 for all array sections except the right-most to
  10007. // guarantee that the memory region is contiguous and has no holes in it.
  10008. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  10009. Length = TempOASE->getLength();
  10010. if (Length == nullptr) {
  10011. // For array sections of the form [1:] or [:], we would need to analyze
  10012. // the lower bound...
  10013. if (OASE->getColonLoc().isValid())
  10014. return false;
  10015. // This is an array subscript which has implicit length 1!
  10016. ArraySizes.push_back(llvm::APSInt::get(1));
  10017. } else {
  10018. Expr::EvalResult Result;
  10019. if (!Length->EvaluateAsInt(Result, Context))
  10020. return false;
  10021. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  10022. if (ConstantLengthValue.getSExtValue() != 1)
  10023. return false;
  10024. ArraySizes.push_back(ConstantLengthValue);
  10025. }
  10026. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  10027. }
  10028. // If we have a single element, we don't need to add the implicit lengths.
  10029. if (!SingleElement) {
  10030. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  10031. // Has implicit length 1!
  10032. ArraySizes.push_back(llvm::APSInt::get(1));
  10033. Base = TempASE->getBase()->IgnoreParenImpCasts();
  10034. }
  10035. }
  10036. // This array section can be privatized as a single value or as a constant
  10037. // sized array.
  10038. return true;
  10039. }
  10040. static bool actOnOMPReductionKindClause(
  10041. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  10042. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10043. SourceLocation ColonLoc, SourceLocation EndLoc,
  10044. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10045. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  10046. DeclarationName DN = ReductionId.getName();
  10047. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  10048. BinaryOperatorKind BOK = BO_Comma;
  10049. ASTContext &Context = S.Context;
  10050. // OpenMP [2.14.3.6, reduction clause]
  10051. // C
  10052. // reduction-identifier is either an identifier or one of the following
  10053. // operators: +, -, *, &, |, ^, && and ||
  10054. // C++
  10055. // reduction-identifier is either an id-expression or one of the following
  10056. // operators: +, -, *, &, |, ^, && and ||
  10057. switch (OOK) {
  10058. case OO_Plus:
  10059. case OO_Minus:
  10060. BOK = BO_Add;
  10061. break;
  10062. case OO_Star:
  10063. BOK = BO_Mul;
  10064. break;
  10065. case OO_Amp:
  10066. BOK = BO_And;
  10067. break;
  10068. case OO_Pipe:
  10069. BOK = BO_Or;
  10070. break;
  10071. case OO_Caret:
  10072. BOK = BO_Xor;
  10073. break;
  10074. case OO_AmpAmp:
  10075. BOK = BO_LAnd;
  10076. break;
  10077. case OO_PipePipe:
  10078. BOK = BO_LOr;
  10079. break;
  10080. case OO_New:
  10081. case OO_Delete:
  10082. case OO_Array_New:
  10083. case OO_Array_Delete:
  10084. case OO_Slash:
  10085. case OO_Percent:
  10086. case OO_Tilde:
  10087. case OO_Exclaim:
  10088. case OO_Equal:
  10089. case OO_Less:
  10090. case OO_Greater:
  10091. case OO_LessEqual:
  10092. case OO_GreaterEqual:
  10093. case OO_PlusEqual:
  10094. case OO_MinusEqual:
  10095. case OO_StarEqual:
  10096. case OO_SlashEqual:
  10097. case OO_PercentEqual:
  10098. case OO_CaretEqual:
  10099. case OO_AmpEqual:
  10100. case OO_PipeEqual:
  10101. case OO_LessLess:
  10102. case OO_GreaterGreater:
  10103. case OO_LessLessEqual:
  10104. case OO_GreaterGreaterEqual:
  10105. case OO_EqualEqual:
  10106. case OO_ExclaimEqual:
  10107. case OO_Spaceship:
  10108. case OO_PlusPlus:
  10109. case OO_MinusMinus:
  10110. case OO_Comma:
  10111. case OO_ArrowStar:
  10112. case OO_Arrow:
  10113. case OO_Call:
  10114. case OO_Subscript:
  10115. case OO_Conditional:
  10116. case OO_Coawait:
  10117. case NUM_OVERLOADED_OPERATORS:
  10118. llvm_unreachable("Unexpected reduction identifier");
  10119. case OO_None:
  10120. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  10121. if (II->isStr("max"))
  10122. BOK = BO_GT;
  10123. else if (II->isStr("min"))
  10124. BOK = BO_LT;
  10125. }
  10126. break;
  10127. }
  10128. SourceRange ReductionIdRange;
  10129. if (ReductionIdScopeSpec.isValid())
  10130. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  10131. else
  10132. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  10133. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  10134. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  10135. bool FirstIter = true;
  10136. for (Expr *RefExpr : VarList) {
  10137. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  10138. // OpenMP [2.1, C/C++]
  10139. // A list item is a variable or array section, subject to the restrictions
  10140. // specified in Section 2.4 on page 42 and in each of the sections
  10141. // describing clauses and directives for which a list appears.
  10142. // OpenMP [2.14.3.3, Restrictions, p.1]
  10143. // A variable that is part of another variable (as an array or
  10144. // structure element) cannot appear in a private clause.
  10145. if (!FirstIter && IR != ER)
  10146. ++IR;
  10147. FirstIter = false;
  10148. SourceLocation ELoc;
  10149. SourceRange ERange;
  10150. Expr *SimpleRefExpr = RefExpr;
  10151. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  10152. /*AllowArraySection=*/true);
  10153. if (Res.second) {
  10154. // Try to find 'declare reduction' corresponding construct before using
  10155. // builtin/overloaded operators.
  10156. QualType Type = Context.DependentTy;
  10157. CXXCastPath BasePath;
  10158. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10159. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10160. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10161. Expr *ReductionOp = nullptr;
  10162. if (S.CurContext->isDependentContext() &&
  10163. (DeclareReductionRef.isUnset() ||
  10164. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  10165. ReductionOp = DeclareReductionRef.get();
  10166. // It will be analyzed later.
  10167. RD.push(RefExpr, ReductionOp);
  10168. }
  10169. ValueDecl *D = Res.first;
  10170. if (!D)
  10171. continue;
  10172. Expr *TaskgroupDescriptor = nullptr;
  10173. QualType Type;
  10174. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  10175. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  10176. if (ASE) {
  10177. Type = ASE->getType().getNonReferenceType();
  10178. } else if (OASE) {
  10179. QualType BaseType =
  10180. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  10181. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  10182. Type = ATy->getElementType();
  10183. else
  10184. Type = BaseType->getPointeeType();
  10185. Type = Type.getNonReferenceType();
  10186. } else {
  10187. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  10188. }
  10189. auto *VD = dyn_cast<VarDecl>(D);
  10190. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10191. // A variable that appears in a private clause must not have an incomplete
  10192. // type or a reference type.
  10193. if (S.RequireCompleteType(ELoc, D->getType(),
  10194. diag::err_omp_reduction_incomplete_type))
  10195. continue;
  10196. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10197. // A list item that appears in a reduction clause must not be
  10198. // const-qualified.
  10199. if (Type.getNonReferenceType().isConstant(Context)) {
  10200. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  10201. if (!ASE && !OASE) {
  10202. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10203. VarDecl::DeclarationOnly;
  10204. S.Diag(D->getLocation(),
  10205. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10206. << D;
  10207. }
  10208. continue;
  10209. }
  10210. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  10211. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  10212. // If a list-item is a reference type then it must bind to the same object
  10213. // for all threads of the team.
  10214. if (!ASE && !OASE) {
  10215. if (VD) {
  10216. VarDecl *VDDef = VD->getDefinition();
  10217. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  10218. DSARefChecker Check(Stack);
  10219. if (Check.Visit(VDDef->getInit())) {
  10220. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  10221. << getOpenMPClauseName(ClauseKind) << ERange;
  10222. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  10223. continue;
  10224. }
  10225. }
  10226. }
  10227. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  10228. // in a Construct]
  10229. // Variables with the predetermined data-sharing attributes may not be
  10230. // listed in data-sharing attributes clauses, except for the cases
  10231. // listed below. For these exceptions only, listing a predetermined
  10232. // variable in a data-sharing attribute clause is allowed and overrides
  10233. // the variable's predetermined data-sharing attributes.
  10234. // OpenMP [2.14.3.6, Restrictions, p.3]
  10235. // Any number of reduction clauses can be specified on the directive,
  10236. // but a list item can appear only once in the reduction clauses for that
  10237. // directive.
  10238. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  10239. if (DVar.CKind == OMPC_reduction) {
  10240. S.Diag(ELoc, diag::err_omp_once_referenced)
  10241. << getOpenMPClauseName(ClauseKind);
  10242. if (DVar.RefExpr)
  10243. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  10244. continue;
  10245. }
  10246. if (DVar.CKind != OMPC_unknown) {
  10247. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  10248. << getOpenMPClauseName(DVar.CKind)
  10249. << getOpenMPClauseName(OMPC_reduction);
  10250. reportOriginalDsa(S, Stack, D, DVar);
  10251. continue;
  10252. }
  10253. // OpenMP [2.14.3.6, Restrictions, p.1]
  10254. // A list item that appears in a reduction clause of a worksharing
  10255. // construct must be shared in the parallel regions to which any of the
  10256. // worksharing regions arising from the worksharing construct bind.
  10257. if (isOpenMPWorksharingDirective(CurrDir) &&
  10258. !isOpenMPParallelDirective(CurrDir) &&
  10259. !isOpenMPTeamsDirective(CurrDir)) {
  10260. DVar = Stack->getImplicitDSA(D, true);
  10261. if (DVar.CKind != OMPC_shared) {
  10262. S.Diag(ELoc, diag::err_omp_required_access)
  10263. << getOpenMPClauseName(OMPC_reduction)
  10264. << getOpenMPClauseName(OMPC_shared);
  10265. reportOriginalDsa(S, Stack, D, DVar);
  10266. continue;
  10267. }
  10268. }
  10269. }
  10270. // Try to find 'declare reduction' corresponding construct before using
  10271. // builtin/overloaded operators.
  10272. CXXCastPath BasePath;
  10273. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10274. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10275. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10276. if (DeclareReductionRef.isInvalid())
  10277. continue;
  10278. if (S.CurContext->isDependentContext() &&
  10279. (DeclareReductionRef.isUnset() ||
  10280. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  10281. RD.push(RefExpr, DeclareReductionRef.get());
  10282. continue;
  10283. }
  10284. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  10285. // Not allowed reduction identifier is found.
  10286. S.Diag(ReductionId.getBeginLoc(),
  10287. diag::err_omp_unknown_reduction_identifier)
  10288. << Type << ReductionIdRange;
  10289. continue;
  10290. }
  10291. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10292. // The type of a list item that appears in a reduction clause must be valid
  10293. // for the reduction-identifier. For a max or min reduction in C, the type
  10294. // of the list item must be an allowed arithmetic data type: char, int,
  10295. // float, double, or _Bool, possibly modified with long, short, signed, or
  10296. // unsigned. For a max or min reduction in C++, the type of the list item
  10297. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  10298. // double, or bool, possibly modified with long, short, signed, or unsigned.
  10299. if (DeclareReductionRef.isUnset()) {
  10300. if ((BOK == BO_GT || BOK == BO_LT) &&
  10301. !(Type->isScalarType() ||
  10302. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  10303. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  10304. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  10305. if (!ASE && !OASE) {
  10306. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10307. VarDecl::DeclarationOnly;
  10308. S.Diag(D->getLocation(),
  10309. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10310. << D;
  10311. }
  10312. continue;
  10313. }
  10314. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  10315. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  10316. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  10317. << getOpenMPClauseName(ClauseKind);
  10318. if (!ASE && !OASE) {
  10319. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10320. VarDecl::DeclarationOnly;
  10321. S.Diag(D->getLocation(),
  10322. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10323. << D;
  10324. }
  10325. continue;
  10326. }
  10327. }
  10328. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  10329. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  10330. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10331. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  10332. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10333. QualType PrivateTy = Type;
  10334. // Try if we can determine constant lengths for all array sections and avoid
  10335. // the VLA.
  10336. bool ConstantLengthOASE = false;
  10337. if (OASE) {
  10338. bool SingleElement;
  10339. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  10340. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  10341. Context, OASE, SingleElement, ArraySizes);
  10342. // If we don't have a single element, we must emit a constant array type.
  10343. if (ConstantLengthOASE && !SingleElement) {
  10344. for (llvm::APSInt &Size : ArraySizes)
  10345. PrivateTy = Context.getConstantArrayType(
  10346. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  10347. }
  10348. }
  10349. if ((OASE && !ConstantLengthOASE) ||
  10350. (!OASE && !ASE &&
  10351. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  10352. if (!Context.getTargetInfo().isVLASupported() &&
  10353. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  10354. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  10355. S.Diag(ELoc, diag::note_vla_unsupported);
  10356. continue;
  10357. }
  10358. // For arrays/array sections only:
  10359. // Create pseudo array type for private copy. The size for this array will
  10360. // be generated during codegen.
  10361. // For array subscripts or single variables Private Ty is the same as Type
  10362. // (type of the variable or single array element).
  10363. PrivateTy = Context.getVariableArrayType(
  10364. Type,
  10365. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  10366. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  10367. } else if (!ASE && !OASE &&
  10368. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  10369. PrivateTy = D->getType().getNonReferenceType();
  10370. }
  10371. // Private copy.
  10372. VarDecl *PrivateVD =
  10373. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  10374. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10375. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10376. // Add initializer for private variable.
  10377. Expr *Init = nullptr;
  10378. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  10379. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  10380. if (DeclareReductionRef.isUsable()) {
  10381. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  10382. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  10383. if (DRD->getInitializer()) {
  10384. Init = DRDRef;
  10385. RHSVD->setInit(DRDRef);
  10386. RHSVD->setInitStyle(VarDecl::CallInit);
  10387. }
  10388. } else {
  10389. switch (BOK) {
  10390. case BO_Add:
  10391. case BO_Xor:
  10392. case BO_Or:
  10393. case BO_LOr:
  10394. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  10395. if (Type->isScalarType() || Type->isAnyComplexType())
  10396. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  10397. break;
  10398. case BO_Mul:
  10399. case BO_LAnd:
  10400. if (Type->isScalarType() || Type->isAnyComplexType()) {
  10401. // '*' and '&&' reduction ops - initializer is '1'.
  10402. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  10403. }
  10404. break;
  10405. case BO_And: {
  10406. // '&' reduction op - initializer is '~0'.
  10407. QualType OrigType = Type;
  10408. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  10409. Type = ComplexTy->getElementType();
  10410. if (Type->isRealFloatingType()) {
  10411. llvm::APFloat InitValue =
  10412. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  10413. /*isIEEE=*/true);
  10414. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10415. Type, ELoc);
  10416. } else if (Type->isScalarType()) {
  10417. uint64_t Size = Context.getTypeSize(Type);
  10418. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  10419. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  10420. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10421. }
  10422. if (Init && OrigType->isAnyComplexType()) {
  10423. // Init = 0xFFFF + 0xFFFFi;
  10424. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  10425. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  10426. }
  10427. Type = OrigType;
  10428. break;
  10429. }
  10430. case BO_LT:
  10431. case BO_GT: {
  10432. // 'min' reduction op - initializer is 'Largest representable number in
  10433. // the reduction list item type'.
  10434. // 'max' reduction op - initializer is 'Least representable number in
  10435. // the reduction list item type'.
  10436. if (Type->isIntegerType() || Type->isPointerType()) {
  10437. bool IsSigned = Type->hasSignedIntegerRepresentation();
  10438. uint64_t Size = Context.getTypeSize(Type);
  10439. QualType IntTy =
  10440. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  10441. llvm::APInt InitValue =
  10442. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  10443. : llvm::APInt::getMinValue(Size)
  10444. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  10445. : llvm::APInt::getMaxValue(Size);
  10446. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10447. if (Type->isPointerType()) {
  10448. // Cast to pointer type.
  10449. ExprResult CastExpr = S.BuildCStyleCastExpr(
  10450. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  10451. if (CastExpr.isInvalid())
  10452. continue;
  10453. Init = CastExpr.get();
  10454. }
  10455. } else if (Type->isRealFloatingType()) {
  10456. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  10457. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  10458. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10459. Type, ELoc);
  10460. }
  10461. break;
  10462. }
  10463. case BO_PtrMemD:
  10464. case BO_PtrMemI:
  10465. case BO_MulAssign:
  10466. case BO_Div:
  10467. case BO_Rem:
  10468. case BO_Sub:
  10469. case BO_Shl:
  10470. case BO_Shr:
  10471. case BO_LE:
  10472. case BO_GE:
  10473. case BO_EQ:
  10474. case BO_NE:
  10475. case BO_Cmp:
  10476. case BO_AndAssign:
  10477. case BO_XorAssign:
  10478. case BO_OrAssign:
  10479. case BO_Assign:
  10480. case BO_AddAssign:
  10481. case BO_SubAssign:
  10482. case BO_DivAssign:
  10483. case BO_RemAssign:
  10484. case BO_ShlAssign:
  10485. case BO_ShrAssign:
  10486. case BO_Comma:
  10487. llvm_unreachable("Unexpected reduction operation");
  10488. }
  10489. }
  10490. if (Init && DeclareReductionRef.isUnset())
  10491. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  10492. else if (!Init)
  10493. S.ActOnUninitializedDecl(RHSVD);
  10494. if (RHSVD->isInvalidDecl())
  10495. continue;
  10496. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  10497. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  10498. << Type << ReductionIdRange;
  10499. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10500. VarDecl::DeclarationOnly;
  10501. S.Diag(D->getLocation(),
  10502. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10503. << D;
  10504. continue;
  10505. }
  10506. // Store initializer for single element in private copy. Will be used during
  10507. // codegen.
  10508. PrivateVD->setInit(RHSVD->getInit());
  10509. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  10510. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  10511. ExprResult ReductionOp;
  10512. if (DeclareReductionRef.isUsable()) {
  10513. QualType RedTy = DeclareReductionRef.get()->getType();
  10514. QualType PtrRedTy = Context.getPointerType(RedTy);
  10515. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  10516. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  10517. if (!BasePath.empty()) {
  10518. LHS = S.DefaultLvalueConversion(LHS.get());
  10519. RHS = S.DefaultLvalueConversion(RHS.get());
  10520. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10521. CK_UncheckedDerivedToBase, LHS.get(),
  10522. &BasePath, LHS.get()->getValueKind());
  10523. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10524. CK_UncheckedDerivedToBase, RHS.get(),
  10525. &BasePath, RHS.get()->getValueKind());
  10526. }
  10527. FunctionProtoType::ExtProtoInfo EPI;
  10528. QualType Params[] = {PtrRedTy, PtrRedTy};
  10529. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  10530. auto *OVE = new (Context) OpaqueValueExpr(
  10531. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  10532. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  10533. Expr *Args[] = {LHS.get(), RHS.get()};
  10534. ReductionOp = new (Context)
  10535. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  10536. } else {
  10537. ReductionOp = S.BuildBinOp(
  10538. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  10539. if (ReductionOp.isUsable()) {
  10540. if (BOK != BO_LT && BOK != BO_GT) {
  10541. ReductionOp =
  10542. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10543. BO_Assign, LHSDRE, ReductionOp.get());
  10544. } else {
  10545. auto *ConditionalOp = new (Context)
  10546. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  10547. Type, VK_LValue, OK_Ordinary);
  10548. ReductionOp =
  10549. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10550. BO_Assign, LHSDRE, ConditionalOp);
  10551. }
  10552. if (ReductionOp.isUsable())
  10553. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  10554. }
  10555. if (!ReductionOp.isUsable())
  10556. continue;
  10557. }
  10558. // OpenMP [2.15.4.6, Restrictions, p.2]
  10559. // A list item that appears in an in_reduction clause of a task construct
  10560. // must appear in a task_reduction clause of a construct associated with a
  10561. // taskgroup region that includes the participating task in its taskgroup
  10562. // set. The construct associated with the innermost region that meets this
  10563. // condition must specify the same reduction-identifier as the in_reduction
  10564. // clause.
  10565. if (ClauseKind == OMPC_in_reduction) {
  10566. SourceRange ParentSR;
  10567. BinaryOperatorKind ParentBOK;
  10568. const Expr *ParentReductionOp;
  10569. Expr *ParentBOKTD, *ParentReductionOpTD;
  10570. DSAStackTy::DSAVarData ParentBOKDSA =
  10571. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  10572. ParentBOKTD);
  10573. DSAStackTy::DSAVarData ParentReductionOpDSA =
  10574. Stack->getTopMostTaskgroupReductionData(
  10575. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  10576. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  10577. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  10578. if (!IsParentBOK && !IsParentReductionOp) {
  10579. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  10580. continue;
  10581. }
  10582. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  10583. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  10584. IsParentReductionOp) {
  10585. bool EmitError = true;
  10586. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  10587. llvm::FoldingSetNodeID RedId, ParentRedId;
  10588. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  10589. DeclareReductionRef.get()->Profile(RedId, Context,
  10590. /*Canonical=*/true);
  10591. EmitError = RedId != ParentRedId;
  10592. }
  10593. if (EmitError) {
  10594. S.Diag(ReductionId.getBeginLoc(),
  10595. diag::err_omp_reduction_identifier_mismatch)
  10596. << ReductionIdRange << RefExpr->getSourceRange();
  10597. S.Diag(ParentSR.getBegin(),
  10598. diag::note_omp_previous_reduction_identifier)
  10599. << ParentSR
  10600. << (IsParentBOK ? ParentBOKDSA.RefExpr
  10601. : ParentReductionOpDSA.RefExpr)
  10602. ->getSourceRange();
  10603. continue;
  10604. }
  10605. }
  10606. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  10607. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  10608. }
  10609. DeclRefExpr *Ref = nullptr;
  10610. Expr *VarsExpr = RefExpr->IgnoreParens();
  10611. if (!VD && !S.CurContext->isDependentContext()) {
  10612. if (ASE || OASE) {
  10613. TransformExprToCaptures RebuildToCapture(S, D);
  10614. VarsExpr =
  10615. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  10616. Ref = RebuildToCapture.getCapturedExpr();
  10617. } else {
  10618. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  10619. }
  10620. if (!S.isOpenMPCapturedDecl(D)) {
  10621. RD.ExprCaptures.emplace_back(Ref->getDecl());
  10622. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10623. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  10624. if (!RefRes.isUsable())
  10625. continue;
  10626. ExprResult PostUpdateRes =
  10627. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  10628. RefRes.get());
  10629. if (!PostUpdateRes.isUsable())
  10630. continue;
  10631. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  10632. Stack->getCurrentDirective() == OMPD_taskgroup) {
  10633. S.Diag(RefExpr->getExprLoc(),
  10634. diag::err_omp_reduction_non_addressable_expression)
  10635. << RefExpr->getSourceRange();
  10636. continue;
  10637. }
  10638. RD.ExprPostUpdates.emplace_back(
  10639. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  10640. }
  10641. }
  10642. }
  10643. // All reduction items are still marked as reduction (to do not increase
  10644. // code base size).
  10645. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  10646. if (CurrDir == OMPD_taskgroup) {
  10647. if (DeclareReductionRef.isUsable())
  10648. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  10649. DeclareReductionRef.get());
  10650. else
  10651. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  10652. }
  10653. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  10654. TaskgroupDescriptor);
  10655. }
  10656. return RD.Vars.empty();
  10657. }
  10658. OMPClause *Sema::ActOnOpenMPReductionClause(
  10659. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10660. SourceLocation ColonLoc, SourceLocation EndLoc,
  10661. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10662. ArrayRef<Expr *> UnresolvedReductions) {
  10663. ReductionData RD(VarList.size());
  10664. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  10665. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10666. ReductionIdScopeSpec, ReductionId,
  10667. UnresolvedReductions, RD))
  10668. return nullptr;
  10669. return OMPReductionClause::Create(
  10670. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10671. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10672. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10673. buildPreInits(Context, RD.ExprCaptures),
  10674. buildPostUpdate(*this, RD.ExprPostUpdates));
  10675. }
  10676. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  10677. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10678. SourceLocation ColonLoc, SourceLocation EndLoc,
  10679. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10680. ArrayRef<Expr *> UnresolvedReductions) {
  10681. ReductionData RD(VarList.size());
  10682. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  10683. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10684. ReductionIdScopeSpec, ReductionId,
  10685. UnresolvedReductions, RD))
  10686. return nullptr;
  10687. return OMPTaskReductionClause::Create(
  10688. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10689. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10690. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10691. buildPreInits(Context, RD.ExprCaptures),
  10692. buildPostUpdate(*this, RD.ExprPostUpdates));
  10693. }
  10694. OMPClause *Sema::ActOnOpenMPInReductionClause(
  10695. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10696. SourceLocation ColonLoc, SourceLocation EndLoc,
  10697. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10698. ArrayRef<Expr *> UnresolvedReductions) {
  10699. ReductionData RD(VarList.size());
  10700. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  10701. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10702. ReductionIdScopeSpec, ReductionId,
  10703. UnresolvedReductions, RD))
  10704. return nullptr;
  10705. return OMPInReductionClause::Create(
  10706. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10707. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10708. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  10709. buildPreInits(Context, RD.ExprCaptures),
  10710. buildPostUpdate(*this, RD.ExprPostUpdates));
  10711. }
  10712. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  10713. SourceLocation LinLoc) {
  10714. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  10715. LinKind == OMPC_LINEAR_unknown) {
  10716. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  10717. return true;
  10718. }
  10719. return false;
  10720. }
  10721. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  10722. OpenMPLinearClauseKind LinKind,
  10723. QualType Type) {
  10724. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  10725. // A variable must not have an incomplete type or a reference type.
  10726. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  10727. return true;
  10728. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  10729. !Type->isReferenceType()) {
  10730. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  10731. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  10732. return true;
  10733. }
  10734. Type = Type.getNonReferenceType();
  10735. // A list item must not be const-qualified.
  10736. if (Type.isConstant(Context)) {
  10737. Diag(ELoc, diag::err_omp_const_variable)
  10738. << getOpenMPClauseName(OMPC_linear);
  10739. if (D) {
  10740. bool IsDecl =
  10741. !VD ||
  10742. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10743. Diag(D->getLocation(),
  10744. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10745. << D;
  10746. }
  10747. return true;
  10748. }
  10749. // A list item must be of integral or pointer type.
  10750. Type = Type.getUnqualifiedType().getCanonicalType();
  10751. const auto *Ty = Type.getTypePtrOrNull();
  10752. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  10753. !Ty->isPointerType())) {
  10754. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  10755. if (D) {
  10756. bool IsDecl =
  10757. !VD ||
  10758. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10759. Diag(D->getLocation(),
  10760. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10761. << D;
  10762. }
  10763. return true;
  10764. }
  10765. return false;
  10766. }
  10767. OMPClause *Sema::ActOnOpenMPLinearClause(
  10768. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  10769. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  10770. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10771. SmallVector<Expr *, 8> Vars;
  10772. SmallVector<Expr *, 8> Privates;
  10773. SmallVector<Expr *, 8> Inits;
  10774. SmallVector<Decl *, 4> ExprCaptures;
  10775. SmallVector<Expr *, 4> ExprPostUpdates;
  10776. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  10777. LinKind = OMPC_LINEAR_val;
  10778. for (Expr *RefExpr : VarList) {
  10779. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10780. SourceLocation ELoc;
  10781. SourceRange ERange;
  10782. Expr *SimpleRefExpr = RefExpr;
  10783. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10784. if (Res.second) {
  10785. // It will be analyzed later.
  10786. Vars.push_back(RefExpr);
  10787. Privates.push_back(nullptr);
  10788. Inits.push_back(nullptr);
  10789. }
  10790. ValueDecl *D = Res.first;
  10791. if (!D)
  10792. continue;
  10793. QualType Type = D->getType();
  10794. auto *VD = dyn_cast<VarDecl>(D);
  10795. // OpenMP [2.14.3.7, linear clause]
  10796. // A list-item cannot appear in more than one linear clause.
  10797. // A list-item that appears in a linear clause cannot appear in any
  10798. // other data-sharing attribute clause.
  10799. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10800. if (DVar.RefExpr) {
  10801. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10802. << getOpenMPClauseName(OMPC_linear);
  10803. reportOriginalDsa(*this, DSAStack, D, DVar);
  10804. continue;
  10805. }
  10806. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  10807. continue;
  10808. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10809. // Build private copy of original var.
  10810. VarDecl *Private =
  10811. buildVarDecl(*this, ELoc, Type, D->getName(),
  10812. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10813. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10814. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  10815. // Build var to save initial value.
  10816. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  10817. Expr *InitExpr;
  10818. DeclRefExpr *Ref = nullptr;
  10819. if (!VD && !CurContext->isDependentContext()) {
  10820. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10821. if (!isOpenMPCapturedDecl(D)) {
  10822. ExprCaptures.push_back(Ref->getDecl());
  10823. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10824. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10825. if (!RefRes.isUsable())
  10826. continue;
  10827. ExprResult PostUpdateRes =
  10828. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10829. SimpleRefExpr, RefRes.get());
  10830. if (!PostUpdateRes.isUsable())
  10831. continue;
  10832. ExprPostUpdates.push_back(
  10833. IgnoredValueConversions(PostUpdateRes.get()).get());
  10834. }
  10835. }
  10836. }
  10837. if (LinKind == OMPC_LINEAR_uval)
  10838. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  10839. else
  10840. InitExpr = VD ? SimpleRefExpr : Ref;
  10841. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  10842. /*DirectInit=*/false);
  10843. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  10844. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  10845. Vars.push_back((VD || CurContext->isDependentContext())
  10846. ? RefExpr->IgnoreParens()
  10847. : Ref);
  10848. Privates.push_back(PrivateRef);
  10849. Inits.push_back(InitRef);
  10850. }
  10851. if (Vars.empty())
  10852. return nullptr;
  10853. Expr *StepExpr = Step;
  10854. Expr *CalcStepExpr = nullptr;
  10855. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  10856. !Step->isInstantiationDependent() &&
  10857. !Step->containsUnexpandedParameterPack()) {
  10858. SourceLocation StepLoc = Step->getBeginLoc();
  10859. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  10860. if (Val.isInvalid())
  10861. return nullptr;
  10862. StepExpr = Val.get();
  10863. // Build var to save the step value.
  10864. VarDecl *SaveVar =
  10865. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  10866. ExprResult SaveRef =
  10867. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  10868. ExprResult CalcStep =
  10869. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  10870. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  10871. // Warn about zero linear step (it would be probably better specified as
  10872. // making corresponding variables 'const').
  10873. llvm::APSInt Result;
  10874. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  10875. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  10876. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  10877. << (Vars.size() > 1);
  10878. if (!IsConstant && CalcStep.isUsable()) {
  10879. // Calculate the step beforehand instead of doing this on each iteration.
  10880. // (This is not used if the number of iterations may be kfold-ed).
  10881. CalcStepExpr = CalcStep.get();
  10882. }
  10883. }
  10884. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  10885. ColonLoc, EndLoc, Vars, Privates, Inits,
  10886. StepExpr, CalcStepExpr,
  10887. buildPreInits(Context, ExprCaptures),
  10888. buildPostUpdate(*this, ExprPostUpdates));
  10889. }
  10890. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  10891. Expr *NumIterations, Sema &SemaRef,
  10892. Scope *S, DSAStackTy *Stack) {
  10893. // Walk the vars and build update/final expressions for the CodeGen.
  10894. SmallVector<Expr *, 8> Updates;
  10895. SmallVector<Expr *, 8> Finals;
  10896. Expr *Step = Clause.getStep();
  10897. Expr *CalcStep = Clause.getCalcStep();
  10898. // OpenMP [2.14.3.7, linear clause]
  10899. // If linear-step is not specified it is assumed to be 1.
  10900. if (!Step)
  10901. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  10902. else if (CalcStep)
  10903. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  10904. bool HasErrors = false;
  10905. auto CurInit = Clause.inits().begin();
  10906. auto CurPrivate = Clause.privates().begin();
  10907. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  10908. for (Expr *RefExpr : Clause.varlists()) {
  10909. SourceLocation ELoc;
  10910. SourceRange ERange;
  10911. Expr *SimpleRefExpr = RefExpr;
  10912. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  10913. ValueDecl *D = Res.first;
  10914. if (Res.second || !D) {
  10915. Updates.push_back(nullptr);
  10916. Finals.push_back(nullptr);
  10917. HasErrors = true;
  10918. continue;
  10919. }
  10920. auto &&Info = Stack->isLoopControlVariable(D);
  10921. // OpenMP [2.15.11, distribute simd Construct]
  10922. // A list item may not appear in a linear clause, unless it is the loop
  10923. // iteration variable.
  10924. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  10925. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  10926. SemaRef.Diag(ELoc,
  10927. diag::err_omp_linear_distribute_var_non_loop_iteration);
  10928. Updates.push_back(nullptr);
  10929. Finals.push_back(nullptr);
  10930. HasErrors = true;
  10931. continue;
  10932. }
  10933. Expr *InitExpr = *CurInit;
  10934. // Build privatized reference to the current linear var.
  10935. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  10936. Expr *CapturedRef;
  10937. if (LinKind == OMPC_LINEAR_uval)
  10938. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  10939. else
  10940. CapturedRef =
  10941. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  10942. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  10943. /*RefersToCapture=*/true);
  10944. // Build update: Var = InitExpr + IV * Step
  10945. ExprResult Update;
  10946. if (!Info.first)
  10947. Update =
  10948. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  10949. InitExpr, IV, Step, /* Subtract */ false);
  10950. else
  10951. Update = *CurPrivate;
  10952. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  10953. /*DiscardedValue=*/true);
  10954. // Build final: Var = InitExpr + NumIterations * Step
  10955. ExprResult Final;
  10956. if (!Info.first)
  10957. Final =
  10958. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  10959. InitExpr, NumIterations, Step, /*Subtract=*/false);
  10960. else
  10961. Final = *CurPrivate;
  10962. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  10963. /*DiscardedValue=*/true);
  10964. if (!Update.isUsable() || !Final.isUsable()) {
  10965. Updates.push_back(nullptr);
  10966. Finals.push_back(nullptr);
  10967. HasErrors = true;
  10968. } else {
  10969. Updates.push_back(Update.get());
  10970. Finals.push_back(Final.get());
  10971. }
  10972. ++CurInit;
  10973. ++CurPrivate;
  10974. }
  10975. Clause.setUpdates(Updates);
  10976. Clause.setFinals(Finals);
  10977. return HasErrors;
  10978. }
  10979. OMPClause *Sema::ActOnOpenMPAlignedClause(
  10980. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  10981. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10982. SmallVector<Expr *, 8> Vars;
  10983. for (Expr *RefExpr : VarList) {
  10984. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10985. SourceLocation ELoc;
  10986. SourceRange ERange;
  10987. Expr *SimpleRefExpr = RefExpr;
  10988. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10989. if (Res.second) {
  10990. // It will be analyzed later.
  10991. Vars.push_back(RefExpr);
  10992. }
  10993. ValueDecl *D = Res.first;
  10994. if (!D)
  10995. continue;
  10996. QualType QType = D->getType();
  10997. auto *VD = dyn_cast<VarDecl>(D);
  10998. // OpenMP [2.8.1, simd construct, Restrictions]
  10999. // The type of list items appearing in the aligned clause must be
  11000. // array, pointer, reference to array, or reference to pointer.
  11001. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  11002. const Type *Ty = QType.getTypePtrOrNull();
  11003. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  11004. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  11005. << QType << getLangOpts().CPlusPlus << ERange;
  11006. bool IsDecl =
  11007. !VD ||
  11008. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11009. Diag(D->getLocation(),
  11010. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11011. << D;
  11012. continue;
  11013. }
  11014. // OpenMP [2.8.1, simd construct, Restrictions]
  11015. // A list-item cannot appear in more than one aligned clause.
  11016. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  11017. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  11018. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  11019. << getOpenMPClauseName(OMPC_aligned);
  11020. continue;
  11021. }
  11022. DeclRefExpr *Ref = nullptr;
  11023. if (!VD && isOpenMPCapturedDecl(D))
  11024. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11025. Vars.push_back(DefaultFunctionArrayConversion(
  11026. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  11027. .get());
  11028. }
  11029. // OpenMP [2.8.1, simd construct, Description]
  11030. // The parameter of the aligned clause, alignment, must be a constant
  11031. // positive integer expression.
  11032. // If no optional parameter is specified, implementation-defined default
  11033. // alignments for SIMD instructions on the target platforms are assumed.
  11034. if (Alignment != nullptr) {
  11035. ExprResult AlignResult =
  11036. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  11037. if (AlignResult.isInvalid())
  11038. return nullptr;
  11039. Alignment = AlignResult.get();
  11040. }
  11041. if (Vars.empty())
  11042. return nullptr;
  11043. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  11044. EndLoc, Vars, Alignment);
  11045. }
  11046. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  11047. SourceLocation StartLoc,
  11048. SourceLocation LParenLoc,
  11049. SourceLocation EndLoc) {
  11050. SmallVector<Expr *, 8> Vars;
  11051. SmallVector<Expr *, 8> SrcExprs;
  11052. SmallVector<Expr *, 8> DstExprs;
  11053. SmallVector<Expr *, 8> AssignmentOps;
  11054. for (Expr *RefExpr : VarList) {
  11055. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  11056. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11057. // It will be analyzed later.
  11058. Vars.push_back(RefExpr);
  11059. SrcExprs.push_back(nullptr);
  11060. DstExprs.push_back(nullptr);
  11061. AssignmentOps.push_back(nullptr);
  11062. continue;
  11063. }
  11064. SourceLocation ELoc = RefExpr->getExprLoc();
  11065. // OpenMP [2.1, C/C++]
  11066. // A list item is a variable name.
  11067. // OpenMP [2.14.4.1, Restrictions, p.1]
  11068. // A list item that appears in a copyin clause must be threadprivate.
  11069. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  11070. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  11071. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  11072. << 0 << RefExpr->getSourceRange();
  11073. continue;
  11074. }
  11075. Decl *D = DE->getDecl();
  11076. auto *VD = cast<VarDecl>(D);
  11077. QualType Type = VD->getType();
  11078. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  11079. // It will be analyzed later.
  11080. Vars.push_back(DE);
  11081. SrcExprs.push_back(nullptr);
  11082. DstExprs.push_back(nullptr);
  11083. AssignmentOps.push_back(nullptr);
  11084. continue;
  11085. }
  11086. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  11087. // A list item that appears in a copyin clause must be threadprivate.
  11088. if (!DSAStack->isThreadPrivate(VD)) {
  11089. Diag(ELoc, diag::err_omp_required_access)
  11090. << getOpenMPClauseName(OMPC_copyin)
  11091. << getOpenMPDirectiveName(OMPD_threadprivate);
  11092. continue;
  11093. }
  11094. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11095. // A variable of class type (or array thereof) that appears in a
  11096. // copyin clause requires an accessible, unambiguous copy assignment
  11097. // operator for the class type.
  11098. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11099. VarDecl *SrcVD =
  11100. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  11101. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11102. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  11103. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  11104. VarDecl *DstVD =
  11105. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  11106. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11107. DeclRefExpr *PseudoDstExpr =
  11108. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  11109. // For arrays generate assignment operation for single element and replace
  11110. // it by the original array element in CodeGen.
  11111. ExprResult AssignmentOp =
  11112. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  11113. PseudoSrcExpr);
  11114. if (AssignmentOp.isInvalid())
  11115. continue;
  11116. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  11117. /*DiscardedValue=*/true);
  11118. if (AssignmentOp.isInvalid())
  11119. continue;
  11120. DSAStack->addDSA(VD, DE, OMPC_copyin);
  11121. Vars.push_back(DE);
  11122. SrcExprs.push_back(PseudoSrcExpr);
  11123. DstExprs.push_back(PseudoDstExpr);
  11124. AssignmentOps.push_back(AssignmentOp.get());
  11125. }
  11126. if (Vars.empty())
  11127. return nullptr;
  11128. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11129. SrcExprs, DstExprs, AssignmentOps);
  11130. }
  11131. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  11132. SourceLocation StartLoc,
  11133. SourceLocation LParenLoc,
  11134. SourceLocation EndLoc) {
  11135. SmallVector<Expr *, 8> Vars;
  11136. SmallVector<Expr *, 8> SrcExprs;
  11137. SmallVector<Expr *, 8> DstExprs;
  11138. SmallVector<Expr *, 8> AssignmentOps;
  11139. for (Expr *RefExpr : VarList) {
  11140. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11141. SourceLocation ELoc;
  11142. SourceRange ERange;
  11143. Expr *SimpleRefExpr = RefExpr;
  11144. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11145. if (Res.second) {
  11146. // It will be analyzed later.
  11147. Vars.push_back(RefExpr);
  11148. SrcExprs.push_back(nullptr);
  11149. DstExprs.push_back(nullptr);
  11150. AssignmentOps.push_back(nullptr);
  11151. }
  11152. ValueDecl *D = Res.first;
  11153. if (!D)
  11154. continue;
  11155. QualType Type = D->getType();
  11156. auto *VD = dyn_cast<VarDecl>(D);
  11157. // OpenMP [2.14.4.2, Restrictions, p.2]
  11158. // A list item that appears in a copyprivate clause may not appear in a
  11159. // private or firstprivate clause on the single construct.
  11160. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  11161. DSAStackTy::DSAVarData DVar =
  11162. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11163. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  11164. DVar.RefExpr) {
  11165. Diag(ELoc, diag::err_omp_wrong_dsa)
  11166. << getOpenMPClauseName(DVar.CKind)
  11167. << getOpenMPClauseName(OMPC_copyprivate);
  11168. reportOriginalDsa(*this, DSAStack, D, DVar);
  11169. continue;
  11170. }
  11171. // OpenMP [2.11.4.2, Restrictions, p.1]
  11172. // All list items that appear in a copyprivate clause must be either
  11173. // threadprivate or private in the enclosing context.
  11174. if (DVar.CKind == OMPC_unknown) {
  11175. DVar = DSAStack->getImplicitDSA(D, false);
  11176. if (DVar.CKind == OMPC_shared) {
  11177. Diag(ELoc, diag::err_omp_required_access)
  11178. << getOpenMPClauseName(OMPC_copyprivate)
  11179. << "threadprivate or private in the enclosing context";
  11180. reportOriginalDsa(*this, DSAStack, D, DVar);
  11181. continue;
  11182. }
  11183. }
  11184. }
  11185. // Variably modified types are not supported.
  11186. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  11187. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11188. << getOpenMPClauseName(OMPC_copyprivate) << Type
  11189. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11190. bool IsDecl =
  11191. !VD ||
  11192. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11193. Diag(D->getLocation(),
  11194. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11195. << D;
  11196. continue;
  11197. }
  11198. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11199. // A variable of class type (or array thereof) that appears in a
  11200. // copyin clause requires an accessible, unambiguous copy assignment
  11201. // operator for the class type.
  11202. Type = Context.getBaseElementType(Type.getNonReferenceType())
  11203. .getUnqualifiedType();
  11204. VarDecl *SrcVD =
  11205. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  11206. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11207. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  11208. VarDecl *DstVD =
  11209. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  11210. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11211. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11212. ExprResult AssignmentOp = BuildBinOp(
  11213. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  11214. if (AssignmentOp.isInvalid())
  11215. continue;
  11216. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  11217. /*DiscardedValue=*/true);
  11218. if (AssignmentOp.isInvalid())
  11219. continue;
  11220. // No need to mark vars as copyprivate, they are already threadprivate or
  11221. // implicitly private.
  11222. assert(VD || isOpenMPCapturedDecl(D));
  11223. Vars.push_back(
  11224. VD ? RefExpr->IgnoreParens()
  11225. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  11226. SrcExprs.push_back(PseudoSrcExpr);
  11227. DstExprs.push_back(PseudoDstExpr);
  11228. AssignmentOps.push_back(AssignmentOp.get());
  11229. }
  11230. if (Vars.empty())
  11231. return nullptr;
  11232. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11233. Vars, SrcExprs, DstExprs, AssignmentOps);
  11234. }
  11235. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  11236. SourceLocation StartLoc,
  11237. SourceLocation LParenLoc,
  11238. SourceLocation EndLoc) {
  11239. if (VarList.empty())
  11240. return nullptr;
  11241. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  11242. }
  11243. OMPClause *
  11244. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  11245. SourceLocation DepLoc, SourceLocation ColonLoc,
  11246. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11247. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11248. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  11249. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  11250. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11251. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  11252. return nullptr;
  11253. }
  11254. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  11255. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  11256. DepKind == OMPC_DEPEND_sink)) {
  11257. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  11258. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11259. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  11260. /*Last=*/OMPC_DEPEND_unknown, Except)
  11261. << getOpenMPClauseName(OMPC_depend);
  11262. return nullptr;
  11263. }
  11264. SmallVector<Expr *, 8> Vars;
  11265. DSAStackTy::OperatorOffsetTy OpsOffs;
  11266. llvm::APSInt DepCounter(/*BitWidth=*/32);
  11267. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  11268. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  11269. if (const Expr *OrderedCountExpr =
  11270. DSAStack->getParentOrderedRegionParam().first) {
  11271. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  11272. TotalDepCount.setIsUnsigned(/*Val=*/true);
  11273. }
  11274. }
  11275. for (Expr *RefExpr : VarList) {
  11276. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  11277. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11278. // It will be analyzed later.
  11279. Vars.push_back(RefExpr);
  11280. continue;
  11281. }
  11282. SourceLocation ELoc = RefExpr->getExprLoc();
  11283. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  11284. if (DepKind == OMPC_DEPEND_sink) {
  11285. if (DSAStack->getParentOrderedRegionParam().first &&
  11286. DepCounter >= TotalDepCount) {
  11287. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  11288. continue;
  11289. }
  11290. ++DepCounter;
  11291. // OpenMP [2.13.9, Summary]
  11292. // depend(dependence-type : vec), where dependence-type is:
  11293. // 'sink' and where vec is the iteration vector, which has the form:
  11294. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  11295. // where n is the value specified by the ordered clause in the loop
  11296. // directive, xi denotes the loop iteration variable of the i-th nested
  11297. // loop associated with the loop directive, and di is a constant
  11298. // non-negative integer.
  11299. if (CurContext->isDependentContext()) {
  11300. // It will be analyzed later.
  11301. Vars.push_back(RefExpr);
  11302. continue;
  11303. }
  11304. SimpleExpr = SimpleExpr->IgnoreImplicit();
  11305. OverloadedOperatorKind OOK = OO_None;
  11306. SourceLocation OOLoc;
  11307. Expr *LHS = SimpleExpr;
  11308. Expr *RHS = nullptr;
  11309. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  11310. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  11311. OOLoc = BO->getOperatorLoc();
  11312. LHS = BO->getLHS()->IgnoreParenImpCasts();
  11313. RHS = BO->getRHS()->IgnoreParenImpCasts();
  11314. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  11315. OOK = OCE->getOperator();
  11316. OOLoc = OCE->getOperatorLoc();
  11317. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11318. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  11319. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  11320. OOK = MCE->getMethodDecl()
  11321. ->getNameInfo()
  11322. .getName()
  11323. .getCXXOverloadedOperator();
  11324. OOLoc = MCE->getCallee()->getExprLoc();
  11325. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  11326. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11327. }
  11328. SourceLocation ELoc;
  11329. SourceRange ERange;
  11330. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  11331. if (Res.second) {
  11332. // It will be analyzed later.
  11333. Vars.push_back(RefExpr);
  11334. }
  11335. ValueDecl *D = Res.first;
  11336. if (!D)
  11337. continue;
  11338. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  11339. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  11340. continue;
  11341. }
  11342. if (RHS) {
  11343. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  11344. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  11345. if (RHSRes.isInvalid())
  11346. continue;
  11347. }
  11348. if (!CurContext->isDependentContext() &&
  11349. DSAStack->getParentOrderedRegionParam().first &&
  11350. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  11351. const ValueDecl *VD =
  11352. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  11353. if (VD)
  11354. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11355. << 1 << VD;
  11356. else
  11357. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  11358. continue;
  11359. }
  11360. OpsOffs.emplace_back(RHS, OOK);
  11361. } else {
  11362. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  11363. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  11364. (ASE &&
  11365. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  11366. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  11367. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11368. << RefExpr->getSourceRange();
  11369. continue;
  11370. }
  11371. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  11372. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  11373. ExprResult Res =
  11374. CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
  11375. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  11376. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  11377. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11378. << RefExpr->getSourceRange();
  11379. continue;
  11380. }
  11381. }
  11382. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  11383. }
  11384. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  11385. TotalDepCount > VarList.size() &&
  11386. DSAStack->getParentOrderedRegionParam().first &&
  11387. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  11388. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11389. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  11390. }
  11391. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  11392. Vars.empty())
  11393. return nullptr;
  11394. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11395. DepKind, DepLoc, ColonLoc, Vars,
  11396. TotalDepCount.getZExtValue());
  11397. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  11398. DSAStack->isParentOrderedRegion())
  11399. DSAStack->addDoacrossDependClause(C, OpsOffs);
  11400. return C;
  11401. }
  11402. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  11403. SourceLocation LParenLoc,
  11404. SourceLocation EndLoc) {
  11405. Expr *ValExpr = Device;
  11406. Stmt *HelperValStmt = nullptr;
  11407. // OpenMP [2.9.1, Restrictions]
  11408. // The device expression must evaluate to a non-negative integer value.
  11409. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  11410. /*StrictlyPositive=*/false))
  11411. return nullptr;
  11412. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11413. OpenMPDirectiveKind CaptureRegion =
  11414. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  11415. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11416. ValExpr = MakeFullExpr(ValExpr).get();
  11417. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  11418. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11419. HelperValStmt = buildPreInits(Context, Captures);
  11420. }
  11421. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  11422. StartLoc, LParenLoc, EndLoc);
  11423. }
  11424. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  11425. DSAStackTy *Stack, QualType QTy,
  11426. bool FullCheck = true) {
  11427. NamedDecl *ND;
  11428. if (QTy->isIncompleteType(&ND)) {
  11429. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  11430. return false;
  11431. }
  11432. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  11433. !QTy.isTrivialType(SemaRef.Context))
  11434. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  11435. return true;
  11436. }
  11437. /// Return true if it can be proven that the provided array expression
  11438. /// (array section or array subscript) does NOT specify the whole size of the
  11439. /// array whose base type is \a BaseQTy.
  11440. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  11441. const Expr *E,
  11442. QualType BaseQTy) {
  11443. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11444. // If this is an array subscript, it refers to the whole size if the size of
  11445. // the dimension is constant and equals 1. Also, an array section assumes the
  11446. // format of an array subscript if no colon is used.
  11447. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  11448. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11449. return ATy->getSize().getSExtValue() != 1;
  11450. // Size can't be evaluated statically.
  11451. return false;
  11452. }
  11453. assert(OASE && "Expecting array section if not an array subscript.");
  11454. const Expr *LowerBound = OASE->getLowerBound();
  11455. const Expr *Length = OASE->getLength();
  11456. // If there is a lower bound that does not evaluates to zero, we are not
  11457. // covering the whole dimension.
  11458. if (LowerBound) {
  11459. Expr::EvalResult Result;
  11460. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11461. return false; // Can't get the integer value as a constant.
  11462. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  11463. if (ConstLowerBound.getSExtValue())
  11464. return true;
  11465. }
  11466. // If we don't have a length we covering the whole dimension.
  11467. if (!Length)
  11468. return false;
  11469. // If the base is a pointer, we don't have a way to get the size of the
  11470. // pointee.
  11471. if (BaseQTy->isPointerType())
  11472. return false;
  11473. // We can only check if the length is the same as the size of the dimension
  11474. // if we have a constant array.
  11475. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  11476. if (!CATy)
  11477. return false;
  11478. Expr::EvalResult Result;
  11479. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11480. return false; // Can't get the integer value as a constant.
  11481. llvm::APSInt ConstLength = Result.Val.getInt();
  11482. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  11483. }
  11484. // Return true if it can be proven that the provided array expression (array
  11485. // section or array subscript) does NOT specify a single element of the array
  11486. // whose base type is \a BaseQTy.
  11487. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  11488. const Expr *E,
  11489. QualType BaseQTy) {
  11490. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11491. // An array subscript always refer to a single element. Also, an array section
  11492. // assumes the format of an array subscript if no colon is used.
  11493. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  11494. return false;
  11495. assert(OASE && "Expecting array section if not an array subscript.");
  11496. const Expr *Length = OASE->getLength();
  11497. // If we don't have a length we have to check if the array has unitary size
  11498. // for this dimension. Also, we should always expect a length if the base type
  11499. // is pointer.
  11500. if (!Length) {
  11501. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11502. return ATy->getSize().getSExtValue() != 1;
  11503. // We cannot assume anything.
  11504. return false;
  11505. }
  11506. // Check if the length evaluates to 1.
  11507. Expr::EvalResult Result;
  11508. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11509. return false; // Can't get the integer value as a constant.
  11510. llvm::APSInt ConstLength = Result.Val.getInt();
  11511. return ConstLength.getSExtValue() != 1;
  11512. }
  11513. // Return the expression of the base of the mappable expression or null if it
  11514. // cannot be determined and do all the necessary checks to see if the expression
  11515. // is valid as a standalone mappable expression. In the process, record all the
  11516. // components of the expression.
  11517. static const Expr *checkMapClauseExpressionBase(
  11518. Sema &SemaRef, Expr *E,
  11519. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  11520. OpenMPClauseKind CKind, bool NoDiagnose) {
  11521. SourceLocation ELoc = E->getExprLoc();
  11522. SourceRange ERange = E->getSourceRange();
  11523. // The base of elements of list in a map clause have to be either:
  11524. // - a reference to variable or field.
  11525. // - a member expression.
  11526. // - an array expression.
  11527. //
  11528. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  11529. // reference to 'r'.
  11530. //
  11531. // If we have:
  11532. //
  11533. // struct SS {
  11534. // Bla S;
  11535. // foo() {
  11536. // #pragma omp target map (S.Arr[:12]);
  11537. // }
  11538. // }
  11539. //
  11540. // We want to retrieve the member expression 'this->S';
  11541. const Expr *RelevantExpr = nullptr;
  11542. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  11543. // If a list item is an array section, it must specify contiguous storage.
  11544. //
  11545. // For this restriction it is sufficient that we make sure only references
  11546. // to variables or fields and array expressions, and that no array sections
  11547. // exist except in the rightmost expression (unless they cover the whole
  11548. // dimension of the array). E.g. these would be invalid:
  11549. //
  11550. // r.ArrS[3:5].Arr[6:7]
  11551. //
  11552. // r.ArrS[3:5].x
  11553. //
  11554. // but these would be valid:
  11555. // r.ArrS[3].Arr[6:7]
  11556. //
  11557. // r.ArrS[3].x
  11558. bool AllowUnitySizeArraySection = true;
  11559. bool AllowWholeSizeArraySection = true;
  11560. while (!RelevantExpr) {
  11561. E = E->IgnoreParenImpCasts();
  11562. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  11563. if (!isa<VarDecl>(CurE->getDecl()))
  11564. return nullptr;
  11565. RelevantExpr = CurE;
  11566. // If we got a reference to a declaration, we should not expect any array
  11567. // section before that.
  11568. AllowUnitySizeArraySection = false;
  11569. AllowWholeSizeArraySection = false;
  11570. // Record the component.
  11571. CurComponents.emplace_back(CurE, CurE->getDecl());
  11572. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  11573. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  11574. if (isa<CXXThisExpr>(BaseE))
  11575. // We found a base expression: this->Val.
  11576. RelevantExpr = CurE;
  11577. else
  11578. E = BaseE;
  11579. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  11580. if (!NoDiagnose) {
  11581. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  11582. << CurE->getSourceRange();
  11583. return nullptr;
  11584. }
  11585. if (RelevantExpr)
  11586. return nullptr;
  11587. continue;
  11588. }
  11589. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  11590. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  11591. // A bit-field cannot appear in a map clause.
  11592. //
  11593. if (FD->isBitField()) {
  11594. if (!NoDiagnose) {
  11595. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  11596. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  11597. return nullptr;
  11598. }
  11599. if (RelevantExpr)
  11600. return nullptr;
  11601. continue;
  11602. }
  11603. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11604. // If the type of a list item is a reference to a type T then the type
  11605. // will be considered to be T for all purposes of this clause.
  11606. QualType CurType = BaseE->getType().getNonReferenceType();
  11607. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  11608. // A list item cannot be a variable that is a member of a structure with
  11609. // a union type.
  11610. //
  11611. if (CurType->isUnionType()) {
  11612. if (!NoDiagnose) {
  11613. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  11614. << CurE->getSourceRange();
  11615. return nullptr;
  11616. }
  11617. continue;
  11618. }
  11619. // If we got a member expression, we should not expect any array section
  11620. // before that:
  11621. //
  11622. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  11623. // If a list item is an element of a structure, only the rightmost symbol
  11624. // of the variable reference can be an array section.
  11625. //
  11626. AllowUnitySizeArraySection = false;
  11627. AllowWholeSizeArraySection = false;
  11628. // Record the component.
  11629. CurComponents.emplace_back(CurE, FD);
  11630. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  11631. E = CurE->getBase()->IgnoreParenImpCasts();
  11632. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  11633. if (!NoDiagnose) {
  11634. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11635. << 0 << CurE->getSourceRange();
  11636. return nullptr;
  11637. }
  11638. continue;
  11639. }
  11640. // If we got an array subscript that express the whole dimension we
  11641. // can have any array expressions before. If it only expressing part of
  11642. // the dimension, we can only have unitary-size array expressions.
  11643. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  11644. E->getType()))
  11645. AllowWholeSizeArraySection = false;
  11646. // Record the component - we don't have any declaration associated.
  11647. CurComponents.emplace_back(CurE, nullptr);
  11648. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  11649. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  11650. E = CurE->getBase()->IgnoreParenImpCasts();
  11651. QualType CurType =
  11652. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11653. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11654. // If the type of a list item is a reference to a type T then the type
  11655. // will be considered to be T for all purposes of this clause.
  11656. if (CurType->isReferenceType())
  11657. CurType = CurType->getPointeeType();
  11658. bool IsPointer = CurType->isAnyPointerType();
  11659. if (!IsPointer && !CurType->isArrayType()) {
  11660. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11661. << 0 << CurE->getSourceRange();
  11662. return nullptr;
  11663. }
  11664. bool NotWhole =
  11665. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  11666. bool NotUnity =
  11667. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  11668. if (AllowWholeSizeArraySection) {
  11669. // Any array section is currently allowed. Allowing a whole size array
  11670. // section implies allowing a unity array section as well.
  11671. //
  11672. // If this array section refers to the whole dimension we can still
  11673. // accept other array sections before this one, except if the base is a
  11674. // pointer. Otherwise, only unitary sections are accepted.
  11675. if (NotWhole || IsPointer)
  11676. AllowWholeSizeArraySection = false;
  11677. } else if (AllowUnitySizeArraySection && NotUnity) {
  11678. // A unity or whole array section is not allowed and that is not
  11679. // compatible with the properties of the current array section.
  11680. SemaRef.Diag(
  11681. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  11682. << CurE->getSourceRange();
  11683. return nullptr;
  11684. }
  11685. // Record the component - we don't have any declaration associated.
  11686. CurComponents.emplace_back(CurE, nullptr);
  11687. } else {
  11688. if (!NoDiagnose) {
  11689. // If nothing else worked, this is not a valid map clause expression.
  11690. SemaRef.Diag(
  11691. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  11692. << ERange;
  11693. }
  11694. return nullptr;
  11695. }
  11696. }
  11697. return RelevantExpr;
  11698. }
  11699. // Return true if expression E associated with value VD has conflicts with other
  11700. // map information.
  11701. static bool checkMapConflicts(
  11702. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  11703. bool CurrentRegionOnly,
  11704. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  11705. OpenMPClauseKind CKind) {
  11706. assert(VD && E);
  11707. SourceLocation ELoc = E->getExprLoc();
  11708. SourceRange ERange = E->getSourceRange();
  11709. // In order to easily check the conflicts we need to match each component of
  11710. // the expression under test with the components of the expressions that are
  11711. // already in the stack.
  11712. assert(!CurComponents.empty() && "Map clause expression with no components!");
  11713. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  11714. "Map clause expression with unexpected base!");
  11715. // Variables to help detecting enclosing problems in data environment nests.
  11716. bool IsEnclosedByDataEnvironmentExpr = false;
  11717. const Expr *EnclosingExpr = nullptr;
  11718. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  11719. VD, CurrentRegionOnly,
  11720. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  11721. ERange, CKind, &EnclosingExpr,
  11722. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  11723. StackComponents,
  11724. OpenMPClauseKind) {
  11725. assert(!StackComponents.empty() &&
  11726. "Map clause expression with no components!");
  11727. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  11728. "Map clause expression with unexpected base!");
  11729. (void)VD;
  11730. // The whole expression in the stack.
  11731. const Expr *RE = StackComponents.front().getAssociatedExpression();
  11732. // Expressions must start from the same base. Here we detect at which
  11733. // point both expressions diverge from each other and see if we can
  11734. // detect if the memory referred to both expressions is contiguous and
  11735. // do not overlap.
  11736. auto CI = CurComponents.rbegin();
  11737. auto CE = CurComponents.rend();
  11738. auto SI = StackComponents.rbegin();
  11739. auto SE = StackComponents.rend();
  11740. for (; CI != CE && SI != SE; ++CI, ++SI) {
  11741. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  11742. // At most one list item can be an array item derived from a given
  11743. // variable in map clauses of the same construct.
  11744. if (CurrentRegionOnly &&
  11745. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  11746. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  11747. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  11748. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  11749. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  11750. diag::err_omp_multiple_array_items_in_map_clause)
  11751. << CI->getAssociatedExpression()->getSourceRange();
  11752. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  11753. diag::note_used_here)
  11754. << SI->getAssociatedExpression()->getSourceRange();
  11755. return true;
  11756. }
  11757. // Do both expressions have the same kind?
  11758. if (CI->getAssociatedExpression()->getStmtClass() !=
  11759. SI->getAssociatedExpression()->getStmtClass())
  11760. break;
  11761. // Are we dealing with different variables/fields?
  11762. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  11763. break;
  11764. }
  11765. // Check if the extra components of the expressions in the enclosing
  11766. // data environment are redundant for the current base declaration.
  11767. // If they are, the maps completely overlap, which is legal.
  11768. for (; SI != SE; ++SI) {
  11769. QualType Type;
  11770. if (const auto *ASE =
  11771. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  11772. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  11773. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  11774. SI->getAssociatedExpression())) {
  11775. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  11776. Type =
  11777. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11778. }
  11779. if (Type.isNull() || Type->isAnyPointerType() ||
  11780. checkArrayExpressionDoesNotReferToWholeSize(
  11781. SemaRef, SI->getAssociatedExpression(), Type))
  11782. break;
  11783. }
  11784. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11785. // List items of map clauses in the same construct must not share
  11786. // original storage.
  11787. //
  11788. // If the expressions are exactly the same or one is a subset of the
  11789. // other, it means they are sharing storage.
  11790. if (CI == CE && SI == SE) {
  11791. if (CurrentRegionOnly) {
  11792. if (CKind == OMPC_map) {
  11793. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11794. } else {
  11795. assert(CKind == OMPC_to || CKind == OMPC_from);
  11796. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11797. << ERange;
  11798. }
  11799. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11800. << RE->getSourceRange();
  11801. return true;
  11802. }
  11803. // If we find the same expression in the enclosing data environment,
  11804. // that is legal.
  11805. IsEnclosedByDataEnvironmentExpr = true;
  11806. return false;
  11807. }
  11808. QualType DerivedType =
  11809. std::prev(CI)->getAssociatedDeclaration()->getType();
  11810. SourceLocation DerivedLoc =
  11811. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  11812. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11813. // If the type of a list item is a reference to a type T then the type
  11814. // will be considered to be T for all purposes of this clause.
  11815. DerivedType = DerivedType.getNonReferenceType();
  11816. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  11817. // A variable for which the type is pointer and an array section
  11818. // derived from that variable must not appear as list items of map
  11819. // clauses of the same construct.
  11820. //
  11821. // Also, cover one of the cases in:
  11822. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11823. // If any part of the original storage of a list item has corresponding
  11824. // storage in the device data environment, all of the original storage
  11825. // must have corresponding storage in the device data environment.
  11826. //
  11827. if (DerivedType->isAnyPointerType()) {
  11828. if (CI == CE || SI == SE) {
  11829. SemaRef.Diag(
  11830. DerivedLoc,
  11831. diag::err_omp_pointer_mapped_along_with_derived_section)
  11832. << DerivedLoc;
  11833. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11834. << RE->getSourceRange();
  11835. return true;
  11836. }
  11837. if (CI->getAssociatedExpression()->getStmtClass() !=
  11838. SI->getAssociatedExpression()->getStmtClass() ||
  11839. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  11840. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  11841. assert(CI != CE && SI != SE);
  11842. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  11843. << DerivedLoc;
  11844. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11845. << RE->getSourceRange();
  11846. return true;
  11847. }
  11848. }
  11849. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11850. // List items of map clauses in the same construct must not share
  11851. // original storage.
  11852. //
  11853. // An expression is a subset of the other.
  11854. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  11855. if (CKind == OMPC_map) {
  11856. if (CI != CE || SI != SE) {
  11857. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  11858. // a pointer.
  11859. auto Begin =
  11860. CI != CE ? CurComponents.begin() : StackComponents.begin();
  11861. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  11862. auto It = Begin;
  11863. while (It != End && !It->getAssociatedDeclaration())
  11864. std::advance(It, 1);
  11865. assert(It != End &&
  11866. "Expected at least one component with the declaration.");
  11867. if (It != Begin && It->getAssociatedDeclaration()
  11868. ->getType()
  11869. .getCanonicalType()
  11870. ->isAnyPointerType()) {
  11871. IsEnclosedByDataEnvironmentExpr = false;
  11872. EnclosingExpr = nullptr;
  11873. return false;
  11874. }
  11875. }
  11876. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11877. } else {
  11878. assert(CKind == OMPC_to || CKind == OMPC_from);
  11879. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11880. << ERange;
  11881. }
  11882. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11883. << RE->getSourceRange();
  11884. return true;
  11885. }
  11886. // The current expression uses the same base as other expression in the
  11887. // data environment but does not contain it completely.
  11888. if (!CurrentRegionOnly && SI != SE)
  11889. EnclosingExpr = RE;
  11890. // The current expression is a subset of the expression in the data
  11891. // environment.
  11892. IsEnclosedByDataEnvironmentExpr |=
  11893. (!CurrentRegionOnly && CI != CE && SI == SE);
  11894. return false;
  11895. });
  11896. if (CurrentRegionOnly)
  11897. return FoundError;
  11898. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11899. // If any part of the original storage of a list item has corresponding
  11900. // storage in the device data environment, all of the original storage must
  11901. // have corresponding storage in the device data environment.
  11902. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  11903. // If a list item is an element of a structure, and a different element of
  11904. // the structure has a corresponding list item in the device data environment
  11905. // prior to a task encountering the construct associated with the map clause,
  11906. // then the list item must also have a corresponding list item in the device
  11907. // data environment prior to the task encountering the construct.
  11908. //
  11909. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  11910. SemaRef.Diag(ELoc,
  11911. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  11912. << ERange;
  11913. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  11914. << EnclosingExpr->getSourceRange();
  11915. return true;
  11916. }
  11917. return FoundError;
  11918. }
  11919. namespace {
  11920. // Utility struct that gathers all the related lists associated with a mappable
  11921. // expression.
  11922. struct MappableVarListInfo {
  11923. // The list of expressions.
  11924. ArrayRef<Expr *> VarList;
  11925. // The list of processed expressions.
  11926. SmallVector<Expr *, 16> ProcessedVarList;
  11927. // The mappble components for each expression.
  11928. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  11929. // The base declaration of the variable.
  11930. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  11931. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  11932. // We have a list of components and base declarations for each entry in the
  11933. // variable list.
  11934. VarComponents.reserve(VarList.size());
  11935. VarBaseDeclarations.reserve(VarList.size());
  11936. }
  11937. };
  11938. }
  11939. // Check the validity of the provided variable list for the provided clause kind
  11940. // \a CKind. In the check process the valid expressions, and mappable expression
  11941. // components and variables are extracted and used to fill \a Vars,
  11942. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  11943. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  11944. static void
  11945. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  11946. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  11947. SourceLocation StartLoc,
  11948. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  11949. bool IsMapTypeImplicit = false) {
  11950. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  11951. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  11952. "Unexpected clause kind with mappable expressions!");
  11953. // Keep track of the mappable components and base declarations in this clause.
  11954. // Each entry in the list is going to have a list of components associated. We
  11955. // record each set of the components so that we can build the clause later on.
  11956. // In the end we should have the same amount of declarations and component
  11957. // lists.
  11958. for (Expr *RE : MVLI.VarList) {
  11959. assert(RE && "Null expr in omp to/from/map clause");
  11960. SourceLocation ELoc = RE->getExprLoc();
  11961. const Expr *VE = RE->IgnoreParenLValueCasts();
  11962. if (VE->isValueDependent() || VE->isTypeDependent() ||
  11963. VE->isInstantiationDependent() ||
  11964. VE->containsUnexpandedParameterPack()) {
  11965. // We can only analyze this information once the missing information is
  11966. // resolved.
  11967. MVLI.ProcessedVarList.push_back(RE);
  11968. continue;
  11969. }
  11970. Expr *SimpleExpr = RE->IgnoreParenCasts();
  11971. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  11972. SemaRef.Diag(ELoc,
  11973. diag::err_omp_expected_named_var_member_or_array_expression)
  11974. << RE->getSourceRange();
  11975. continue;
  11976. }
  11977. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  11978. ValueDecl *CurDeclaration = nullptr;
  11979. // Obtain the array or member expression bases if required. Also, fill the
  11980. // components array with all the components identified in the process.
  11981. const Expr *BE = checkMapClauseExpressionBase(
  11982. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  11983. if (!BE)
  11984. continue;
  11985. assert(!CurComponents.empty() &&
  11986. "Invalid mappable expression information.");
  11987. // For the following checks, we rely on the base declaration which is
  11988. // expected to be associated with the last component. The declaration is
  11989. // expected to be a variable or a field (if 'this' is being mapped).
  11990. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  11991. assert(CurDeclaration && "Null decl on map clause.");
  11992. assert(
  11993. CurDeclaration->isCanonicalDecl() &&
  11994. "Expecting components to have associated only canonical declarations.");
  11995. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  11996. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  11997. assert((VD || FD) && "Only variables or fields are expected here!");
  11998. (void)FD;
  11999. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  12000. // threadprivate variables cannot appear in a map clause.
  12001. // OpenMP 4.5 [2.10.5, target update Construct]
  12002. // threadprivate variables cannot appear in a from clause.
  12003. if (VD && DSAS->isThreadPrivate(VD)) {
  12004. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12005. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  12006. << getOpenMPClauseName(CKind);
  12007. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  12008. continue;
  12009. }
  12010. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12011. // A list item cannot appear in both a map clause and a data-sharing
  12012. // attribute clause on the same construct.
  12013. // Check conflicts with other map clause expressions. We check the conflicts
  12014. // with the current construct separately from the enclosing data
  12015. // environment, because the restrictions are different. We only have to
  12016. // check conflicts across regions for the map clauses.
  12017. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12018. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  12019. break;
  12020. if (CKind == OMPC_map &&
  12021. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12022. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  12023. break;
  12024. // OpenMP 4.5 [2.10.5, target update Construct]
  12025. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12026. // If the type of a list item is a reference to a type T then the type will
  12027. // be considered to be T for all purposes of this clause.
  12028. auto I = llvm::find_if(
  12029. CurComponents,
  12030. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  12031. return MC.getAssociatedDeclaration();
  12032. });
  12033. assert(I != CurComponents.end() && "Null decl on map clause.");
  12034. QualType Type =
  12035. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  12036. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  12037. // A list item in a to or from clause must have a mappable type.
  12038. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12039. // A list item must have a mappable type.
  12040. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  12041. DSAS, Type))
  12042. continue;
  12043. if (CKind == OMPC_map) {
  12044. // target enter data
  12045. // OpenMP [2.10.2, Restrictions, p. 99]
  12046. // A map-type must be specified in all map clauses and must be either
  12047. // to or alloc.
  12048. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  12049. if (DKind == OMPD_target_enter_data &&
  12050. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  12051. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12052. << (IsMapTypeImplicit ? 1 : 0)
  12053. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12054. << getOpenMPDirectiveName(DKind);
  12055. continue;
  12056. }
  12057. // target exit_data
  12058. // OpenMP [2.10.3, Restrictions, p. 102]
  12059. // A map-type must be specified in all map clauses and must be either
  12060. // from, release, or delete.
  12061. if (DKind == OMPD_target_exit_data &&
  12062. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  12063. MapType == OMPC_MAP_delete)) {
  12064. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12065. << (IsMapTypeImplicit ? 1 : 0)
  12066. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12067. << getOpenMPDirectiveName(DKind);
  12068. continue;
  12069. }
  12070. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  12071. // A list item cannot appear in both a map clause and a data-sharing
  12072. // attribute clause on the same construct
  12073. if (VD && isOpenMPTargetExecutionDirective(DKind)) {
  12074. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12075. if (isOpenMPPrivate(DVar.CKind)) {
  12076. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12077. << getOpenMPClauseName(DVar.CKind)
  12078. << getOpenMPClauseName(OMPC_map)
  12079. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  12080. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  12081. continue;
  12082. }
  12083. }
  12084. }
  12085. // Save the current expression.
  12086. MVLI.ProcessedVarList.push_back(RE);
  12087. // Store the components in the stack so that they can be used to check
  12088. // against other clauses later on.
  12089. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  12090. /*WhereFoundClauseKind=*/OMPC_map);
  12091. // Save the components and declaration to create the clause. For purposes of
  12092. // the clause creation, any component list that has has base 'this' uses
  12093. // null as base declaration.
  12094. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12095. MVLI.VarComponents.back().append(CurComponents.begin(),
  12096. CurComponents.end());
  12097. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  12098. : CurDeclaration);
  12099. }
  12100. }
  12101. OMPClause *
  12102. Sema::ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  12103. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  12104. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  12105. SourceLocation MapLoc, SourceLocation ColonLoc,
  12106. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  12107. SourceLocation LParenLoc, SourceLocation EndLoc) {
  12108. MappableVarListInfo MVLI(VarList);
  12109. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  12110. MapType, IsMapTypeImplicit);
  12111. OpenMPMapModifierKind Modifiers[] = { OMPC_MAP_MODIFIER_unknown,
  12112. OMPC_MAP_MODIFIER_unknown };
  12113. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  12114. // Process map-type-modifiers, flag errors for duplicate modifiers.
  12115. unsigned Count = 0;
  12116. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  12117. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  12118. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  12119. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  12120. continue;
  12121. }
  12122. assert(Count < OMPMapClause::NumberOfModifiers &&
  12123. "Modifiers exceed the allowed number of map type modifiers");
  12124. Modifiers[Count] = MapTypeModifiers[I];
  12125. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  12126. ++Count;
  12127. }
  12128. // We need to produce a map clause even if we don't have variables so that
  12129. // other diagnostics related with non-existing map clauses are accurate.
  12130. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12131. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12132. MVLI.VarComponents, Modifiers, ModifiersLoc,
  12133. MapType, IsMapTypeImplicit, MapLoc);
  12134. }
  12135. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  12136. TypeResult ParsedType) {
  12137. assert(ParsedType.isUsable());
  12138. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  12139. if (ReductionType.isNull())
  12140. return QualType();
  12141. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  12142. // A type name in a declare reduction directive cannot be a function type, an
  12143. // array type, a reference type, or a type qualified with const, volatile or
  12144. // restrict.
  12145. if (ReductionType.hasQualifiers()) {
  12146. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  12147. return QualType();
  12148. }
  12149. if (ReductionType->isFunctionType()) {
  12150. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  12151. return QualType();
  12152. }
  12153. if (ReductionType->isReferenceType()) {
  12154. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  12155. return QualType();
  12156. }
  12157. if (ReductionType->isArrayType()) {
  12158. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  12159. return QualType();
  12160. }
  12161. return ReductionType;
  12162. }
  12163. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  12164. Scope *S, DeclContext *DC, DeclarationName Name,
  12165. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  12166. AccessSpecifier AS, Decl *PrevDeclInScope) {
  12167. SmallVector<Decl *, 8> Decls;
  12168. Decls.reserve(ReductionTypes.size());
  12169. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  12170. forRedeclarationInCurContext());
  12171. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  12172. // A reduction-identifier may not be re-declared in the current scope for the
  12173. // same type or for a type that is compatible according to the base language
  12174. // rules.
  12175. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  12176. OMPDeclareReductionDecl *PrevDRD = nullptr;
  12177. bool InCompoundScope = true;
  12178. if (S != nullptr) {
  12179. // Find previous declaration with the same name not referenced in other
  12180. // declarations.
  12181. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  12182. InCompoundScope =
  12183. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  12184. LookupName(Lookup, S);
  12185. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  12186. /*AllowInlineNamespace=*/false);
  12187. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  12188. LookupResult::Filter Filter = Lookup.makeFilter();
  12189. while (Filter.hasNext()) {
  12190. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  12191. if (InCompoundScope) {
  12192. auto I = UsedAsPrevious.find(PrevDecl);
  12193. if (I == UsedAsPrevious.end())
  12194. UsedAsPrevious[PrevDecl] = false;
  12195. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  12196. UsedAsPrevious[D] = true;
  12197. }
  12198. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  12199. PrevDecl->getLocation();
  12200. }
  12201. Filter.done();
  12202. if (InCompoundScope) {
  12203. for (const auto &PrevData : UsedAsPrevious) {
  12204. if (!PrevData.second) {
  12205. PrevDRD = PrevData.first;
  12206. break;
  12207. }
  12208. }
  12209. }
  12210. } else if (PrevDeclInScope != nullptr) {
  12211. auto *PrevDRDInScope = PrevDRD =
  12212. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  12213. do {
  12214. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  12215. PrevDRDInScope->getLocation();
  12216. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  12217. } while (PrevDRDInScope != nullptr);
  12218. }
  12219. for (const auto &TyData : ReductionTypes) {
  12220. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  12221. bool Invalid = false;
  12222. if (I != PreviousRedeclTypes.end()) {
  12223. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  12224. << TyData.first;
  12225. Diag(I->second, diag::note_previous_definition);
  12226. Invalid = true;
  12227. }
  12228. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  12229. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  12230. Name, TyData.first, PrevDRD);
  12231. DC->addDecl(DRD);
  12232. DRD->setAccess(AS);
  12233. Decls.push_back(DRD);
  12234. if (Invalid)
  12235. DRD->setInvalidDecl();
  12236. else
  12237. PrevDRD = DRD;
  12238. }
  12239. return DeclGroupPtrTy::make(
  12240. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  12241. }
  12242. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  12243. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12244. // Enter new function scope.
  12245. PushFunctionScope();
  12246. setFunctionHasBranchProtectedScope();
  12247. getCurFunction()->setHasOMPDeclareReductionCombiner();
  12248. if (S != nullptr)
  12249. PushDeclContext(S, DRD);
  12250. else
  12251. CurContext = DRD;
  12252. PushExpressionEvaluationContext(
  12253. ExpressionEvaluationContext::PotentiallyEvaluated);
  12254. QualType ReductionType = DRD->getType();
  12255. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  12256. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  12257. // uses semantics of argument handles by value, but it should be passed by
  12258. // reference. C lang does not support references, so pass all parameters as
  12259. // pointers.
  12260. // Create 'T omp_in;' variable.
  12261. VarDecl *OmpInParm =
  12262. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  12263. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  12264. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  12265. // uses semantics of argument handles by value, but it should be passed by
  12266. // reference. C lang does not support references, so pass all parameters as
  12267. // pointers.
  12268. // Create 'T omp_out;' variable.
  12269. VarDecl *OmpOutParm =
  12270. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  12271. if (S != nullptr) {
  12272. PushOnScopeChains(OmpInParm, S);
  12273. PushOnScopeChains(OmpOutParm, S);
  12274. } else {
  12275. DRD->addDecl(OmpInParm);
  12276. DRD->addDecl(OmpOutParm);
  12277. }
  12278. Expr *InE =
  12279. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  12280. Expr *OutE =
  12281. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  12282. DRD->setCombinerData(InE, OutE);
  12283. }
  12284. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  12285. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12286. DiscardCleanupsInEvaluationContext();
  12287. PopExpressionEvaluationContext();
  12288. PopDeclContext();
  12289. PopFunctionScopeInfo();
  12290. if (Combiner != nullptr)
  12291. DRD->setCombiner(Combiner);
  12292. else
  12293. DRD->setInvalidDecl();
  12294. }
  12295. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  12296. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12297. // Enter new function scope.
  12298. PushFunctionScope();
  12299. setFunctionHasBranchProtectedScope();
  12300. if (S != nullptr)
  12301. PushDeclContext(S, DRD);
  12302. else
  12303. CurContext = DRD;
  12304. PushExpressionEvaluationContext(
  12305. ExpressionEvaluationContext::PotentiallyEvaluated);
  12306. QualType ReductionType = DRD->getType();
  12307. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  12308. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  12309. // uses semantics of argument handles by value, but it should be passed by
  12310. // reference. C lang does not support references, so pass all parameters as
  12311. // pointers.
  12312. // Create 'T omp_priv;' variable.
  12313. VarDecl *OmpPrivParm =
  12314. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  12315. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  12316. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  12317. // uses semantics of argument handles by value, but it should be passed by
  12318. // reference. C lang does not support references, so pass all parameters as
  12319. // pointers.
  12320. // Create 'T omp_orig;' variable.
  12321. VarDecl *OmpOrigParm =
  12322. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  12323. if (S != nullptr) {
  12324. PushOnScopeChains(OmpPrivParm, S);
  12325. PushOnScopeChains(OmpOrigParm, S);
  12326. } else {
  12327. DRD->addDecl(OmpPrivParm);
  12328. DRD->addDecl(OmpOrigParm);
  12329. }
  12330. Expr *OrigE =
  12331. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  12332. Expr *PrivE =
  12333. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  12334. DRD->setInitializerData(OrigE, PrivE);
  12335. return OmpPrivParm;
  12336. }
  12337. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  12338. VarDecl *OmpPrivParm) {
  12339. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12340. DiscardCleanupsInEvaluationContext();
  12341. PopExpressionEvaluationContext();
  12342. PopDeclContext();
  12343. PopFunctionScopeInfo();
  12344. if (Initializer != nullptr) {
  12345. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  12346. } else if (OmpPrivParm->hasInit()) {
  12347. DRD->setInitializer(OmpPrivParm->getInit(),
  12348. OmpPrivParm->isDirectInit()
  12349. ? OMPDeclareReductionDecl::DirectInit
  12350. : OMPDeclareReductionDecl::CopyInit);
  12351. } else {
  12352. DRD->setInvalidDecl();
  12353. }
  12354. }
  12355. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  12356. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  12357. for (Decl *D : DeclReductions.get()) {
  12358. if (IsValid) {
  12359. if (S)
  12360. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  12361. /*AddToContext=*/false);
  12362. } else {
  12363. D->setInvalidDecl();
  12364. }
  12365. }
  12366. return DeclReductions;
  12367. }
  12368. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  12369. SourceLocation StartLoc,
  12370. SourceLocation LParenLoc,
  12371. SourceLocation EndLoc) {
  12372. Expr *ValExpr = NumTeams;
  12373. Stmt *HelperValStmt = nullptr;
  12374. // OpenMP [teams Constrcut, Restrictions]
  12375. // The num_teams expression must evaluate to a positive integer value.
  12376. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  12377. /*StrictlyPositive=*/true))
  12378. return nullptr;
  12379. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12380. OpenMPDirectiveKind CaptureRegion =
  12381. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  12382. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12383. ValExpr = MakeFullExpr(ValExpr).get();
  12384. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12385. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12386. HelperValStmt = buildPreInits(Context, Captures);
  12387. }
  12388. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  12389. StartLoc, LParenLoc, EndLoc);
  12390. }
  12391. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  12392. SourceLocation StartLoc,
  12393. SourceLocation LParenLoc,
  12394. SourceLocation EndLoc) {
  12395. Expr *ValExpr = ThreadLimit;
  12396. Stmt *HelperValStmt = nullptr;
  12397. // OpenMP [teams Constrcut, Restrictions]
  12398. // The thread_limit expression must evaluate to a positive integer value.
  12399. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  12400. /*StrictlyPositive=*/true))
  12401. return nullptr;
  12402. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12403. OpenMPDirectiveKind CaptureRegion =
  12404. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  12405. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12406. ValExpr = MakeFullExpr(ValExpr).get();
  12407. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12408. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12409. HelperValStmt = buildPreInits(Context, Captures);
  12410. }
  12411. return new (Context) OMPThreadLimitClause(
  12412. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  12413. }
  12414. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  12415. SourceLocation StartLoc,
  12416. SourceLocation LParenLoc,
  12417. SourceLocation EndLoc) {
  12418. Expr *ValExpr = Priority;
  12419. // OpenMP [2.9.1, task Constrcut]
  12420. // The priority-value is a non-negative numerical scalar expression.
  12421. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  12422. /*StrictlyPositive=*/false))
  12423. return nullptr;
  12424. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12425. }
  12426. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  12427. SourceLocation StartLoc,
  12428. SourceLocation LParenLoc,
  12429. SourceLocation EndLoc) {
  12430. Expr *ValExpr = Grainsize;
  12431. // OpenMP [2.9.2, taskloop Constrcut]
  12432. // The parameter of the grainsize clause must be a positive integer
  12433. // expression.
  12434. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  12435. /*StrictlyPositive=*/true))
  12436. return nullptr;
  12437. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12438. }
  12439. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  12440. SourceLocation StartLoc,
  12441. SourceLocation LParenLoc,
  12442. SourceLocation EndLoc) {
  12443. Expr *ValExpr = NumTasks;
  12444. // OpenMP [2.9.2, taskloop Constrcut]
  12445. // The parameter of the num_tasks clause must be a positive integer
  12446. // expression.
  12447. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  12448. /*StrictlyPositive=*/true))
  12449. return nullptr;
  12450. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12451. }
  12452. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  12453. SourceLocation LParenLoc,
  12454. SourceLocation EndLoc) {
  12455. // OpenMP [2.13.2, critical construct, Description]
  12456. // ... where hint-expression is an integer constant expression that evaluates
  12457. // to a valid lock hint.
  12458. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  12459. if (HintExpr.isInvalid())
  12460. return nullptr;
  12461. return new (Context)
  12462. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  12463. }
  12464. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  12465. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  12466. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  12467. SourceLocation EndLoc) {
  12468. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  12469. std::string Values;
  12470. Values += "'";
  12471. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  12472. Values += "'";
  12473. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  12474. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  12475. return nullptr;
  12476. }
  12477. Expr *ValExpr = ChunkSize;
  12478. Stmt *HelperValStmt = nullptr;
  12479. if (ChunkSize) {
  12480. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  12481. !ChunkSize->isInstantiationDependent() &&
  12482. !ChunkSize->containsUnexpandedParameterPack()) {
  12483. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  12484. ExprResult Val =
  12485. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  12486. if (Val.isInvalid())
  12487. return nullptr;
  12488. ValExpr = Val.get();
  12489. // OpenMP [2.7.1, Restrictions]
  12490. // chunk_size must be a loop invariant integer expression with a positive
  12491. // value.
  12492. llvm::APSInt Result;
  12493. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  12494. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  12495. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  12496. << "dist_schedule" << ChunkSize->getSourceRange();
  12497. return nullptr;
  12498. }
  12499. } else if (getOpenMPCaptureRegionForClause(
  12500. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  12501. OMPD_unknown &&
  12502. !CurContext->isDependentContext()) {
  12503. ValExpr = MakeFullExpr(ValExpr).get();
  12504. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12505. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12506. HelperValStmt = buildPreInits(Context, Captures);
  12507. }
  12508. }
  12509. }
  12510. return new (Context)
  12511. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  12512. Kind, ValExpr, HelperValStmt);
  12513. }
  12514. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  12515. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  12516. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  12517. SourceLocation KindLoc, SourceLocation EndLoc) {
  12518. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  12519. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  12520. std::string Value;
  12521. SourceLocation Loc;
  12522. Value += "'";
  12523. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  12524. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  12525. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  12526. Loc = MLoc;
  12527. } else {
  12528. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  12529. OMPC_DEFAULTMAP_scalar);
  12530. Loc = KindLoc;
  12531. }
  12532. Value += "'";
  12533. Diag(Loc, diag::err_omp_unexpected_clause_value)
  12534. << Value << getOpenMPClauseName(OMPC_defaultmap);
  12535. return nullptr;
  12536. }
  12537. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  12538. return new (Context)
  12539. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  12540. }
  12541. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  12542. DeclContext *CurLexicalContext = getCurLexicalContext();
  12543. if (!CurLexicalContext->isFileContext() &&
  12544. !CurLexicalContext->isExternCContext() &&
  12545. !CurLexicalContext->isExternCXXContext() &&
  12546. !isa<CXXRecordDecl>(CurLexicalContext) &&
  12547. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  12548. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  12549. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  12550. Diag(Loc, diag::err_omp_region_not_file_context);
  12551. return false;
  12552. }
  12553. ++DeclareTargetNestingLevel;
  12554. return true;
  12555. }
  12556. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  12557. assert(DeclareTargetNestingLevel > 0 &&
  12558. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  12559. --DeclareTargetNestingLevel;
  12560. }
  12561. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  12562. CXXScopeSpec &ScopeSpec,
  12563. const DeclarationNameInfo &Id,
  12564. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  12565. NamedDeclSetType &SameDirectiveDecls) {
  12566. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  12567. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  12568. if (Lookup.isAmbiguous())
  12569. return;
  12570. Lookup.suppressDiagnostics();
  12571. if (!Lookup.isSingleResult()) {
  12572. if (TypoCorrection Corrected =
  12573. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  12574. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  12575. CTK_ErrorRecovery)) {
  12576. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  12577. << Id.getName());
  12578. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  12579. return;
  12580. }
  12581. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  12582. return;
  12583. }
  12584. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  12585. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  12586. isa<FunctionTemplateDecl>(ND)) {
  12587. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  12588. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  12589. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  12590. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  12591. cast<ValueDecl>(ND));
  12592. if (!Res) {
  12593. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  12594. ND->addAttr(A);
  12595. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12596. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  12597. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  12598. } else if (*Res != MT) {
  12599. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  12600. << Id.getName();
  12601. }
  12602. } else {
  12603. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  12604. }
  12605. }
  12606. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  12607. Sema &SemaRef, Decl *D) {
  12608. if (!D || !isa<VarDecl>(D))
  12609. return;
  12610. auto *VD = cast<VarDecl>(D);
  12611. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  12612. return;
  12613. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  12614. SemaRef.Diag(SL, diag::note_used_here) << SR;
  12615. }
  12616. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  12617. Sema &SemaRef, DSAStackTy *Stack,
  12618. ValueDecl *VD) {
  12619. return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  12620. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  12621. /*FullCheck=*/false);
  12622. }
  12623. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  12624. SourceLocation IdLoc) {
  12625. if (!D || D->isInvalidDecl())
  12626. return;
  12627. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  12628. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  12629. if (auto *VD = dyn_cast<VarDecl>(D)) {
  12630. // Only global variables can be marked as declare target.
  12631. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  12632. !VD->isStaticDataMember())
  12633. return;
  12634. // 2.10.6: threadprivate variable cannot appear in a declare target
  12635. // directive.
  12636. if (DSAStack->isThreadPrivate(VD)) {
  12637. Diag(SL, diag::err_omp_threadprivate_in_target);
  12638. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  12639. return;
  12640. }
  12641. }
  12642. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  12643. D = FTD->getTemplatedDecl();
  12644. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  12645. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  12646. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  12647. if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  12648. assert(IdLoc.isValid() && "Source location is expected");
  12649. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  12650. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  12651. return;
  12652. }
  12653. }
  12654. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  12655. // Problem if any with var declared with incomplete type will be reported
  12656. // as normal, so no need to check it here.
  12657. if ((E || !VD->getType()->isIncompleteType()) &&
  12658. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  12659. return;
  12660. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  12661. // Checking declaration inside declare target region.
  12662. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  12663. isa<FunctionTemplateDecl>(D)) {
  12664. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  12665. Context, OMPDeclareTargetDeclAttr::MT_To);
  12666. D->addAttr(A);
  12667. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12668. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  12669. }
  12670. return;
  12671. }
  12672. }
  12673. if (!E)
  12674. return;
  12675. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  12676. }
  12677. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  12678. SourceLocation StartLoc,
  12679. SourceLocation LParenLoc,
  12680. SourceLocation EndLoc) {
  12681. MappableVarListInfo MVLI(VarList);
  12682. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  12683. if (MVLI.ProcessedVarList.empty())
  12684. return nullptr;
  12685. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12686. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12687. MVLI.VarComponents);
  12688. }
  12689. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  12690. SourceLocation StartLoc,
  12691. SourceLocation LParenLoc,
  12692. SourceLocation EndLoc) {
  12693. MappableVarListInfo MVLI(VarList);
  12694. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  12695. if (MVLI.ProcessedVarList.empty())
  12696. return nullptr;
  12697. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12698. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12699. MVLI.VarComponents);
  12700. }
  12701. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  12702. SourceLocation StartLoc,
  12703. SourceLocation LParenLoc,
  12704. SourceLocation EndLoc) {
  12705. MappableVarListInfo MVLI(VarList);
  12706. SmallVector<Expr *, 8> PrivateCopies;
  12707. SmallVector<Expr *, 8> Inits;
  12708. for (Expr *RefExpr : VarList) {
  12709. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  12710. SourceLocation ELoc;
  12711. SourceRange ERange;
  12712. Expr *SimpleRefExpr = RefExpr;
  12713. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12714. if (Res.second) {
  12715. // It will be analyzed later.
  12716. MVLI.ProcessedVarList.push_back(RefExpr);
  12717. PrivateCopies.push_back(nullptr);
  12718. Inits.push_back(nullptr);
  12719. }
  12720. ValueDecl *D = Res.first;
  12721. if (!D)
  12722. continue;
  12723. QualType Type = D->getType();
  12724. Type = Type.getNonReferenceType().getUnqualifiedType();
  12725. auto *VD = dyn_cast<VarDecl>(D);
  12726. // Item should be a pointer or reference to pointer.
  12727. if (!Type->isPointerType()) {
  12728. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  12729. << 0 << RefExpr->getSourceRange();
  12730. continue;
  12731. }
  12732. // Build the private variable and the expression that refers to it.
  12733. auto VDPrivate =
  12734. buildVarDecl(*this, ELoc, Type, D->getName(),
  12735. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12736. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12737. if (VDPrivate->isInvalidDecl())
  12738. continue;
  12739. CurContext->addDecl(VDPrivate);
  12740. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  12741. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  12742. // Add temporary variable to initialize the private copy of the pointer.
  12743. VarDecl *VDInit =
  12744. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  12745. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  12746. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  12747. AddInitializerToDecl(VDPrivate,
  12748. DefaultLvalueConversion(VDInitRefExpr).get(),
  12749. /*DirectInit=*/false);
  12750. // If required, build a capture to implement the privatization initialized
  12751. // with the current list item value.
  12752. DeclRefExpr *Ref = nullptr;
  12753. if (!VD)
  12754. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12755. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  12756. PrivateCopies.push_back(VDPrivateRefExpr);
  12757. Inits.push_back(VDInitRefExpr);
  12758. // We need to add a data sharing attribute for this variable to make sure it
  12759. // is correctly captured. A variable that shows up in a use_device_ptr has
  12760. // similar properties of a first private variable.
  12761. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  12762. // Create a mappable component for the list item. List items in this clause
  12763. // only need a component.
  12764. MVLI.VarBaseDeclarations.push_back(D);
  12765. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12766. MVLI.VarComponents.back().push_back(
  12767. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  12768. }
  12769. if (MVLI.ProcessedVarList.empty())
  12770. return nullptr;
  12771. return OMPUseDevicePtrClause::Create(
  12772. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12773. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12774. }
  12775. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  12776. SourceLocation StartLoc,
  12777. SourceLocation LParenLoc,
  12778. SourceLocation EndLoc) {
  12779. MappableVarListInfo MVLI(VarList);
  12780. for (Expr *RefExpr : VarList) {
  12781. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  12782. SourceLocation ELoc;
  12783. SourceRange ERange;
  12784. Expr *SimpleRefExpr = RefExpr;
  12785. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12786. if (Res.second) {
  12787. // It will be analyzed later.
  12788. MVLI.ProcessedVarList.push_back(RefExpr);
  12789. }
  12790. ValueDecl *D = Res.first;
  12791. if (!D)
  12792. continue;
  12793. QualType Type = D->getType();
  12794. // item should be a pointer or array or reference to pointer or array
  12795. if (!Type.getNonReferenceType()->isPointerType() &&
  12796. !Type.getNonReferenceType()->isArrayType()) {
  12797. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  12798. << 0 << RefExpr->getSourceRange();
  12799. continue;
  12800. }
  12801. // Check if the declaration in the clause does not show up in any data
  12802. // sharing attribute.
  12803. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12804. if (isOpenMPPrivate(DVar.CKind)) {
  12805. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12806. << getOpenMPClauseName(DVar.CKind)
  12807. << getOpenMPClauseName(OMPC_is_device_ptr)
  12808. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  12809. reportOriginalDsa(*this, DSAStack, D, DVar);
  12810. continue;
  12811. }
  12812. const Expr *ConflictExpr;
  12813. if (DSAStack->checkMappableExprComponentListsForDecl(
  12814. D, /*CurrentRegionOnly=*/true,
  12815. [&ConflictExpr](
  12816. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  12817. OpenMPClauseKind) -> bool {
  12818. ConflictExpr = R.front().getAssociatedExpression();
  12819. return true;
  12820. })) {
  12821. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  12822. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  12823. << ConflictExpr->getSourceRange();
  12824. continue;
  12825. }
  12826. // Store the components in the stack so that they can be used to check
  12827. // against other clauses later on.
  12828. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  12829. DSAStack->addMappableExpressionComponents(
  12830. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  12831. // Record the expression we've just processed.
  12832. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  12833. // Create a mappable component for the list item. List items in this clause
  12834. // only need a component. We use a null declaration to signal fields in
  12835. // 'this'.
  12836. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  12837. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  12838. "Unexpected device pointer expression!");
  12839. MVLI.VarBaseDeclarations.push_back(
  12840. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  12841. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12842. MVLI.VarComponents.back().push_back(MC);
  12843. }
  12844. if (MVLI.ProcessedVarList.empty())
  12845. return nullptr;
  12846. return OMPIsDevicePtrClause::Create(
  12847. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12848. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12849. }