SemaOpenMP.cpp 658 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This file implements semantic analysis for OpenMP directives and
  10. /// clauses.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "TreeTransform.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/StmtCXX.h"
  21. #include "clang/AST/StmtOpenMP.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/AST/TypeOrdering.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. bool HasMutipleLoops = false;
  135. const Decl *PossiblyLoopCounter = nullptr;
  136. bool NowaitRegion = false;
  137. bool CancelRegion = false;
  138. bool LoopStart = false;
  139. bool BodyComplete = false;
  140. SourceLocation InnerTeamsRegionLoc;
  141. /// Reference to the taskgroup task_reduction reference expression.
  142. Expr *TaskgroupReductionRef = nullptr;
  143. llvm::DenseSet<QualType> MappedClassesQualTypes;
  144. /// List of globals marked as declare target link in this target region
  145. /// (isOpenMPTargetExecutionDirective(Directive) == true).
  146. llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
  147. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  148. Scope *CurScope, SourceLocation Loc)
  149. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  150. ConstructLoc(Loc) {}
  151. SharingMapTy() = default;
  152. };
  153. using StackTy = SmallVector<SharingMapTy, 4>;
  154. /// Stack of used declaration and their data-sharing attributes.
  155. DeclSAMapTy Threadprivates;
  156. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  157. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  158. /// true, if check for DSA must be from parent directive, false, if
  159. /// from current directive.
  160. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  161. Sema &SemaRef;
  162. bool ForceCapturing = false;
  163. /// true if all the variables in the target executable directives must be
  164. /// captured by reference.
  165. bool ForceCaptureByReferenceInTargetExecutable = false;
  166. CriticalsWithHintsTy Criticals;
  167. unsigned IgnoredStackElements = 0;
  168. /// Iterators over the stack iterate in order from innermost to outermost
  169. /// directive.
  170. using const_iterator = StackTy::const_reverse_iterator;
  171. const_iterator begin() const {
  172. return Stack.empty() ? const_iterator()
  173. : Stack.back().first.rbegin() + IgnoredStackElements;
  174. }
  175. const_iterator end() const {
  176. return Stack.empty() ? const_iterator() : Stack.back().first.rend();
  177. }
  178. using iterator = StackTy::reverse_iterator;
  179. iterator begin() {
  180. return Stack.empty() ? iterator()
  181. : Stack.back().first.rbegin() + IgnoredStackElements;
  182. }
  183. iterator end() {
  184. return Stack.empty() ? iterator() : Stack.back().first.rend();
  185. }
  186. // Convenience operations to get at the elements of the stack.
  187. bool isStackEmpty() const {
  188. return Stack.empty() ||
  189. Stack.back().second != CurrentNonCapturingFunctionScope ||
  190. Stack.back().first.size() <= IgnoredStackElements;
  191. }
  192. size_t getStackSize() const {
  193. return isStackEmpty() ? 0
  194. : Stack.back().first.size() - IgnoredStackElements;
  195. }
  196. SharingMapTy *getTopOfStackOrNull() {
  197. size_t Size = getStackSize();
  198. if (Size == 0)
  199. return nullptr;
  200. return &Stack.back().first[Size - 1];
  201. }
  202. const SharingMapTy *getTopOfStackOrNull() const {
  203. return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
  204. }
  205. SharingMapTy &getTopOfStack() {
  206. assert(!isStackEmpty() && "no current directive");
  207. return *getTopOfStackOrNull();
  208. }
  209. const SharingMapTy &getTopOfStack() const {
  210. return const_cast<DSAStackTy&>(*this).getTopOfStack();
  211. }
  212. SharingMapTy *getSecondOnStackOrNull() {
  213. size_t Size = getStackSize();
  214. if (Size <= 1)
  215. return nullptr;
  216. return &Stack.back().first[Size - 2];
  217. }
  218. const SharingMapTy *getSecondOnStackOrNull() const {
  219. return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
  220. }
  221. /// Get the stack element at a certain level (previously returned by
  222. /// \c getNestingLevel).
  223. ///
  224. /// Note that nesting levels count from outermost to innermost, and this is
  225. /// the reverse of our iteration order where new inner levels are pushed at
  226. /// the front of the stack.
  227. SharingMapTy &getStackElemAtLevel(unsigned Level) {
  228. assert(Level < getStackSize() && "no such stack element");
  229. return Stack.back().first[Level];
  230. }
  231. const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
  232. return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
  233. }
  234. DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
  235. /// Checks if the variable is a local for OpenMP region.
  236. bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
  237. /// Vector of previously declared requires directives
  238. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  239. /// omp_allocator_handle_t type.
  240. QualType OMPAllocatorHandleT;
  241. /// Expression for the predefined allocators.
  242. Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
  243. nullptr};
  244. /// Vector of previously encountered target directives
  245. SmallVector<SourceLocation, 2> TargetLocations;
  246. public:
  247. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  248. /// Sets omp_allocator_handle_t type.
  249. void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
  250. /// Gets omp_allocator_handle_t type.
  251. QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
  252. /// Sets the given default allocator.
  253. void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  254. Expr *Allocator) {
  255. OMPPredefinedAllocators[AllocatorKind] = Allocator;
  256. }
  257. /// Returns the specified default allocator.
  258. Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
  259. return OMPPredefinedAllocators[AllocatorKind];
  260. }
  261. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  262. OpenMPClauseKind getClauseParsingMode() const {
  263. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  264. return ClauseKindMode;
  265. }
  266. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  267. bool isBodyComplete() const {
  268. const SharingMapTy *Top = getTopOfStackOrNull();
  269. return Top && Top->BodyComplete;
  270. }
  271. void setBodyComplete() {
  272. getTopOfStack().BodyComplete = true;
  273. }
  274. bool isForceVarCapturing() const { return ForceCapturing; }
  275. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  276. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  277. ForceCaptureByReferenceInTargetExecutable = V;
  278. }
  279. bool isForceCaptureByReferenceInTargetExecutable() const {
  280. return ForceCaptureByReferenceInTargetExecutable;
  281. }
  282. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  283. Scope *CurScope, SourceLocation Loc) {
  284. assert(!IgnoredStackElements &&
  285. "cannot change stack while ignoring elements");
  286. if (Stack.empty() ||
  287. Stack.back().second != CurrentNonCapturingFunctionScope)
  288. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  289. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  290. Stack.back().first.back().DefaultAttrLoc = Loc;
  291. }
  292. void pop() {
  293. assert(!IgnoredStackElements &&
  294. "cannot change stack while ignoring elements");
  295. assert(!Stack.back().first.empty() &&
  296. "Data-sharing attributes stack is empty!");
  297. Stack.back().first.pop_back();
  298. }
  299. /// RAII object to temporarily leave the scope of a directive when we want to
  300. /// logically operate in its parent.
  301. class ParentDirectiveScope {
  302. DSAStackTy &Self;
  303. bool Active;
  304. public:
  305. ParentDirectiveScope(DSAStackTy &Self, bool Activate)
  306. : Self(Self), Active(false) {
  307. if (Activate)
  308. enable();
  309. }
  310. ~ParentDirectiveScope() { disable(); }
  311. void disable() {
  312. if (Active) {
  313. --Self.IgnoredStackElements;
  314. Active = false;
  315. }
  316. }
  317. void enable() {
  318. if (!Active) {
  319. ++Self.IgnoredStackElements;
  320. Active = true;
  321. }
  322. }
  323. };
  324. /// Marks that we're started loop parsing.
  325. void loopInit() {
  326. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  327. "Expected loop-based directive.");
  328. getTopOfStack().LoopStart = true;
  329. }
  330. /// Start capturing of the variables in the loop context.
  331. void loopStart() {
  332. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  333. "Expected loop-based directive.");
  334. getTopOfStack().LoopStart = false;
  335. }
  336. /// true, if variables are captured, false otherwise.
  337. bool isLoopStarted() const {
  338. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  339. "Expected loop-based directive.");
  340. return !getTopOfStack().LoopStart;
  341. }
  342. /// Marks (or clears) declaration as possibly loop counter.
  343. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  344. getTopOfStack().PossiblyLoopCounter =
  345. D ? D->getCanonicalDecl() : D;
  346. }
  347. /// Gets the possible loop counter decl.
  348. const Decl *getPossiblyLoopCunter() const {
  349. return getTopOfStack().PossiblyLoopCounter;
  350. }
  351. /// Start new OpenMP region stack in new non-capturing function.
  352. void pushFunction() {
  353. assert(!IgnoredStackElements &&
  354. "cannot change stack while ignoring elements");
  355. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  356. assert(!isa<CapturingScopeInfo>(CurFnScope));
  357. CurrentNonCapturingFunctionScope = CurFnScope;
  358. }
  359. /// Pop region stack for non-capturing function.
  360. void popFunction(const FunctionScopeInfo *OldFSI) {
  361. assert(!IgnoredStackElements &&
  362. "cannot change stack while ignoring elements");
  363. if (!Stack.empty() && Stack.back().second == OldFSI) {
  364. assert(Stack.back().first.empty());
  365. Stack.pop_back();
  366. }
  367. CurrentNonCapturingFunctionScope = nullptr;
  368. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  369. if (!isa<CapturingScopeInfo>(FSI)) {
  370. CurrentNonCapturingFunctionScope = FSI;
  371. break;
  372. }
  373. }
  374. }
  375. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  376. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  377. }
  378. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  379. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  380. auto I = Criticals.find(Name.getAsString());
  381. if (I != Criticals.end())
  382. return I->second;
  383. return std::make_pair(nullptr, llvm::APSInt());
  384. }
  385. /// If 'aligned' declaration for given variable \a D was not seen yet,
  386. /// add it and return NULL; otherwise return previous occurrence's expression
  387. /// for diagnostics.
  388. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  389. /// Register specified variable as loop control variable.
  390. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  391. /// Check if the specified variable is a loop control variable for
  392. /// current region.
  393. /// \return The index of the loop control variable in the list of associated
  394. /// for-loops (from outer to inner).
  395. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  396. /// Check if the specified variable is a loop control variable for
  397. /// parent region.
  398. /// \return The index of the loop control variable in the list of associated
  399. /// for-loops (from outer to inner).
  400. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  401. /// Get the loop control variable for the I-th loop (or nullptr) in
  402. /// parent directive.
  403. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  404. /// Adds explicit data sharing attribute to the specified declaration.
  405. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  406. DeclRefExpr *PrivateCopy = nullptr);
  407. /// Adds additional information for the reduction items with the reduction id
  408. /// represented as an operator.
  409. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  410. BinaryOperatorKind BOK);
  411. /// Adds additional information for the reduction items with the reduction id
  412. /// represented as reduction identifier.
  413. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  414. const Expr *ReductionRef);
  415. /// Returns the location and reduction operation from the innermost parent
  416. /// region for the given \p D.
  417. const DSAVarData
  418. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  419. BinaryOperatorKind &BOK,
  420. Expr *&TaskgroupDescriptor) const;
  421. /// Returns the location and reduction operation from the innermost parent
  422. /// region for the given \p D.
  423. const DSAVarData
  424. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  425. const Expr *&ReductionRef,
  426. Expr *&TaskgroupDescriptor) const;
  427. /// Return reduction reference expression for the current taskgroup.
  428. Expr *getTaskgroupReductionRef() const {
  429. assert(getTopOfStack().Directive == OMPD_taskgroup &&
  430. "taskgroup reference expression requested for non taskgroup "
  431. "directive.");
  432. return getTopOfStack().TaskgroupReductionRef;
  433. }
  434. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  435. /// descriptor variable at the \p Level of OpenMP regions.
  436. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  437. return getStackElemAtLevel(Level).TaskgroupReductionRef &&
  438. cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
  439. ->getDecl() == VD;
  440. }
  441. /// Returns data sharing attributes from top of the stack for the
  442. /// specified declaration.
  443. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  444. /// Returns data-sharing attributes for the specified declaration.
  445. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  446. /// Checks if the specified variables has data-sharing attributes which
  447. /// match specified \a CPred predicate in any directive which matches \a DPred
  448. /// predicate.
  449. const DSAVarData
  450. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  451. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  452. bool FromParent) const;
  453. /// Checks if the specified variables has data-sharing attributes which
  454. /// match specified \a CPred predicate in any innermost directive which
  455. /// matches \a DPred predicate.
  456. const DSAVarData
  457. hasInnermostDSA(ValueDecl *D,
  458. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  459. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  460. bool FromParent) const;
  461. /// Checks if the specified variables has explicit data-sharing
  462. /// attributes which match specified \a CPred predicate at the specified
  463. /// OpenMP region.
  464. bool hasExplicitDSA(const ValueDecl *D,
  465. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  466. unsigned Level, bool NotLastprivate = false) const;
  467. /// Returns true if the directive at level \Level matches in the
  468. /// specified \a DPred predicate.
  469. bool hasExplicitDirective(
  470. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  471. unsigned Level) const;
  472. /// Finds a directive which matches specified \a DPred predicate.
  473. bool hasDirective(
  474. const llvm::function_ref<bool(
  475. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  476. DPred,
  477. bool FromParent) const;
  478. /// Returns currently analyzed directive.
  479. OpenMPDirectiveKind getCurrentDirective() const {
  480. const SharingMapTy *Top = getTopOfStackOrNull();
  481. return Top ? Top->Directive : OMPD_unknown;
  482. }
  483. /// Returns directive kind at specified level.
  484. OpenMPDirectiveKind getDirective(unsigned Level) const {
  485. assert(!isStackEmpty() && "No directive at specified level.");
  486. return getStackElemAtLevel(Level).Directive;
  487. }
  488. /// Returns the capture region at the specified level.
  489. OpenMPDirectiveKind getCaptureRegion(unsigned Level,
  490. unsigned OpenMPCaptureLevel) const {
  491. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  492. getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
  493. return CaptureRegions[OpenMPCaptureLevel];
  494. }
  495. /// Returns parent directive.
  496. OpenMPDirectiveKind getParentDirective() const {
  497. const SharingMapTy *Parent = getSecondOnStackOrNull();
  498. return Parent ? Parent->Directive : OMPD_unknown;
  499. }
  500. /// Add requires decl to internal vector
  501. void addRequiresDecl(OMPRequiresDecl *RD) {
  502. RequiresDecls.push_back(RD);
  503. }
  504. /// Checks if the defined 'requires' directive has specified type of clause.
  505. template <typename ClauseType>
  506. bool hasRequiresDeclWithClause() {
  507. return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
  508. return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
  509. return isa<ClauseType>(C);
  510. });
  511. });
  512. }
  513. /// Checks for a duplicate clause amongst previously declared requires
  514. /// directives
  515. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  516. bool IsDuplicate = false;
  517. for (OMPClause *CNew : ClauseList) {
  518. for (const OMPRequiresDecl *D : RequiresDecls) {
  519. for (const OMPClause *CPrev : D->clauselists()) {
  520. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  521. SemaRef.Diag(CNew->getBeginLoc(),
  522. diag::err_omp_requires_clause_redeclaration)
  523. << getOpenMPClauseName(CNew->getClauseKind());
  524. SemaRef.Diag(CPrev->getBeginLoc(),
  525. diag::note_omp_requires_previous_clause)
  526. << getOpenMPClauseName(CPrev->getClauseKind());
  527. IsDuplicate = true;
  528. }
  529. }
  530. }
  531. }
  532. return IsDuplicate;
  533. }
  534. /// Add location of previously encountered target to internal vector
  535. void addTargetDirLocation(SourceLocation LocStart) {
  536. TargetLocations.push_back(LocStart);
  537. }
  538. // Return previously encountered target region locations.
  539. ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
  540. return TargetLocations;
  541. }
  542. /// Set default data sharing attribute to none.
  543. void setDefaultDSANone(SourceLocation Loc) {
  544. getTopOfStack().DefaultAttr = DSA_none;
  545. getTopOfStack().DefaultAttrLoc = Loc;
  546. }
  547. /// Set default data sharing attribute to shared.
  548. void setDefaultDSAShared(SourceLocation Loc) {
  549. getTopOfStack().DefaultAttr = DSA_shared;
  550. getTopOfStack().DefaultAttrLoc = Loc;
  551. }
  552. /// Set default data mapping attribute to 'tofrom:scalar'.
  553. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  554. getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
  555. getTopOfStack().DefaultMapAttrLoc = Loc;
  556. }
  557. DefaultDataSharingAttributes getDefaultDSA() const {
  558. return isStackEmpty() ? DSA_unspecified
  559. : getTopOfStack().DefaultAttr;
  560. }
  561. SourceLocation getDefaultDSALocation() const {
  562. return isStackEmpty() ? SourceLocation()
  563. : getTopOfStack().DefaultAttrLoc;
  564. }
  565. DefaultMapAttributes getDefaultDMA() const {
  566. return isStackEmpty() ? DMA_unspecified
  567. : getTopOfStack().DefaultMapAttr;
  568. }
  569. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  570. return getStackElemAtLevel(Level).DefaultMapAttr;
  571. }
  572. SourceLocation getDefaultDMALocation() const {
  573. return isStackEmpty() ? SourceLocation()
  574. : getTopOfStack().DefaultMapAttrLoc;
  575. }
  576. /// Checks if the specified variable is a threadprivate.
  577. bool isThreadPrivate(VarDecl *D) {
  578. const DSAVarData DVar = getTopDSA(D, false);
  579. return isOpenMPThreadPrivate(DVar.CKind);
  580. }
  581. /// Marks current region as ordered (it has an 'ordered' clause).
  582. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  583. OMPOrderedClause *Clause) {
  584. if (IsOrdered)
  585. getTopOfStack().OrderedRegion.emplace(Param, Clause);
  586. else
  587. getTopOfStack().OrderedRegion.reset();
  588. }
  589. /// Returns true, if region is ordered (has associated 'ordered' clause),
  590. /// false - otherwise.
  591. bool isOrderedRegion() const {
  592. if (const SharingMapTy *Top = getTopOfStackOrNull())
  593. return Top->OrderedRegion.hasValue();
  594. return false;
  595. }
  596. /// Returns optional parameter for the ordered region.
  597. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  598. if (const SharingMapTy *Top = getTopOfStackOrNull())
  599. if (Top->OrderedRegion.hasValue())
  600. return Top->OrderedRegion.getValue();
  601. return std::make_pair(nullptr, nullptr);
  602. }
  603. /// Returns true, if parent region is ordered (has associated
  604. /// 'ordered' clause), false - otherwise.
  605. bool isParentOrderedRegion() const {
  606. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  607. return Parent->OrderedRegion.hasValue();
  608. return false;
  609. }
  610. /// Returns optional parameter for the ordered region.
  611. std::pair<const Expr *, OMPOrderedClause *>
  612. getParentOrderedRegionParam() const {
  613. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  614. if (Parent->OrderedRegion.hasValue())
  615. return Parent->OrderedRegion.getValue();
  616. return std::make_pair(nullptr, nullptr);
  617. }
  618. /// Marks current region as nowait (it has a 'nowait' clause).
  619. void setNowaitRegion(bool IsNowait = true) {
  620. getTopOfStack().NowaitRegion = IsNowait;
  621. }
  622. /// Returns true, if parent region is nowait (has associated
  623. /// 'nowait' clause), false - otherwise.
  624. bool isParentNowaitRegion() const {
  625. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  626. return Parent->NowaitRegion;
  627. return false;
  628. }
  629. /// Marks parent region as cancel region.
  630. void setParentCancelRegion(bool Cancel = true) {
  631. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  632. Parent->CancelRegion |= Cancel;
  633. }
  634. /// Return true if current region has inner cancel construct.
  635. bool isCancelRegion() const {
  636. const SharingMapTy *Top = getTopOfStackOrNull();
  637. return Top ? Top->CancelRegion : false;
  638. }
  639. /// Set collapse value for the region.
  640. void setAssociatedLoops(unsigned Val) {
  641. getTopOfStack().AssociatedLoops = Val;
  642. if (Val > 1)
  643. getTopOfStack().HasMutipleLoops = true;
  644. }
  645. /// Return collapse value for region.
  646. unsigned getAssociatedLoops() const {
  647. const SharingMapTy *Top = getTopOfStackOrNull();
  648. return Top ? Top->AssociatedLoops : 0;
  649. }
  650. /// Returns true if the construct is associated with multiple loops.
  651. bool hasMutipleLoops() const {
  652. const SharingMapTy *Top = getTopOfStackOrNull();
  653. return Top ? Top->HasMutipleLoops : false;
  654. }
  655. /// Marks current target region as one with closely nested teams
  656. /// region.
  657. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  658. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  659. Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
  660. }
  661. /// Returns true, if current region has closely nested teams region.
  662. bool hasInnerTeamsRegion() const {
  663. return getInnerTeamsRegionLoc().isValid();
  664. }
  665. /// Returns location of the nested teams region (if any).
  666. SourceLocation getInnerTeamsRegionLoc() const {
  667. const SharingMapTy *Top = getTopOfStackOrNull();
  668. return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
  669. }
  670. Scope *getCurScope() const {
  671. const SharingMapTy *Top = getTopOfStackOrNull();
  672. return Top ? Top->CurScope : nullptr;
  673. }
  674. SourceLocation getConstructLoc() const {
  675. const SharingMapTy *Top = getTopOfStackOrNull();
  676. return Top ? Top->ConstructLoc : SourceLocation();
  677. }
  678. /// Do the check specified in \a Check to all component lists and return true
  679. /// if any issue is found.
  680. bool checkMappableExprComponentListsForDecl(
  681. const ValueDecl *VD, bool CurrentRegionOnly,
  682. const llvm::function_ref<
  683. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  684. OpenMPClauseKind)>
  685. Check) const {
  686. if (isStackEmpty())
  687. return false;
  688. auto SI = begin();
  689. auto SE = end();
  690. if (SI == SE)
  691. return false;
  692. if (CurrentRegionOnly)
  693. SE = std::next(SI);
  694. else
  695. std::advance(SI, 1);
  696. for (; SI != SE; ++SI) {
  697. auto MI = SI->MappedExprComponents.find(VD);
  698. if (MI != SI->MappedExprComponents.end())
  699. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  700. MI->second.Components)
  701. if (Check(L, MI->second.Kind))
  702. return true;
  703. }
  704. return false;
  705. }
  706. /// Do the check specified in \a Check to all component lists at a given level
  707. /// and return true if any issue is found.
  708. bool checkMappableExprComponentListsForDeclAtLevel(
  709. const ValueDecl *VD, unsigned Level,
  710. const llvm::function_ref<
  711. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  712. OpenMPClauseKind)>
  713. Check) const {
  714. if (getStackSize() <= Level)
  715. return false;
  716. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  717. auto MI = StackElem.MappedExprComponents.find(VD);
  718. if (MI != StackElem.MappedExprComponents.end())
  719. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  720. MI->second.Components)
  721. if (Check(L, MI->second.Kind))
  722. return true;
  723. return false;
  724. }
  725. /// Create a new mappable expression component list associated with a given
  726. /// declaration and initialize it with the provided list of components.
  727. void addMappableExpressionComponents(
  728. const ValueDecl *VD,
  729. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  730. OpenMPClauseKind WhereFoundClauseKind) {
  731. MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
  732. // Create new entry and append the new components there.
  733. MEC.Components.resize(MEC.Components.size() + 1);
  734. MEC.Components.back().append(Components.begin(), Components.end());
  735. MEC.Kind = WhereFoundClauseKind;
  736. }
  737. unsigned getNestingLevel() const {
  738. assert(!isStackEmpty());
  739. return getStackSize() - 1;
  740. }
  741. void addDoacrossDependClause(OMPDependClause *C,
  742. const OperatorOffsetTy &OpsOffs) {
  743. SharingMapTy *Parent = getSecondOnStackOrNull();
  744. assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
  745. Parent->DoacrossDepends.try_emplace(C, OpsOffs);
  746. }
  747. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  748. getDoacrossDependClauses() const {
  749. const SharingMapTy &StackElem = getTopOfStack();
  750. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  751. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  752. return llvm::make_range(Ref.begin(), Ref.end());
  753. }
  754. return llvm::make_range(StackElem.DoacrossDepends.end(),
  755. StackElem.DoacrossDepends.end());
  756. }
  757. // Store types of classes which have been explicitly mapped
  758. void addMappedClassesQualTypes(QualType QT) {
  759. SharingMapTy &StackElem = getTopOfStack();
  760. StackElem.MappedClassesQualTypes.insert(QT);
  761. }
  762. // Return set of mapped classes types
  763. bool isClassPreviouslyMapped(QualType QT) const {
  764. const SharingMapTy &StackElem = getTopOfStack();
  765. return StackElem.MappedClassesQualTypes.count(QT) != 0;
  766. }
  767. /// Adds global declare target to the parent target region.
  768. void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
  769. assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  770. E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
  771. "Expected declare target link global.");
  772. for (auto &Elem : *this) {
  773. if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
  774. Elem.DeclareTargetLinkVarDecls.push_back(E);
  775. return;
  776. }
  777. }
  778. }
  779. /// Returns the list of globals with declare target link if current directive
  780. /// is target.
  781. ArrayRef<DeclRefExpr *> getLinkGlobals() const {
  782. assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
  783. "Expected target executable directive.");
  784. return getTopOfStack().DeclareTargetLinkVarDecls;
  785. }
  786. };
  787. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  788. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  789. }
  790. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  791. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
  792. DKind == OMPD_unknown;
  793. }
  794. } // namespace
  795. static const Expr *getExprAsWritten(const Expr *E) {
  796. if (const auto *FE = dyn_cast<FullExpr>(E))
  797. E = FE->getSubExpr();
  798. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  799. E = MTE->GetTemporaryExpr();
  800. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  801. E = Binder->getSubExpr();
  802. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  803. E = ICE->getSubExprAsWritten();
  804. return E->IgnoreParens();
  805. }
  806. static Expr *getExprAsWritten(Expr *E) {
  807. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  808. }
  809. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  810. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  811. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  812. D = ME->getMemberDecl();
  813. const auto *VD = dyn_cast<VarDecl>(D);
  814. const auto *FD = dyn_cast<FieldDecl>(D);
  815. if (VD != nullptr) {
  816. VD = VD->getCanonicalDecl();
  817. D = VD;
  818. } else {
  819. assert(FD);
  820. FD = FD->getCanonicalDecl();
  821. D = FD;
  822. }
  823. return D;
  824. }
  825. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  826. return const_cast<ValueDecl *>(
  827. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  828. }
  829. DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
  830. ValueDecl *D) const {
  831. D = getCanonicalDecl(D);
  832. auto *VD = dyn_cast<VarDecl>(D);
  833. const auto *FD = dyn_cast<FieldDecl>(D);
  834. DSAVarData DVar;
  835. if (Iter == end()) {
  836. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  837. // in a region but not in construct]
  838. // File-scope or namespace-scope variables referenced in called routines
  839. // in the region are shared unless they appear in a threadprivate
  840. // directive.
  841. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  842. DVar.CKind = OMPC_shared;
  843. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  844. // in a region but not in construct]
  845. // Variables with static storage duration that are declared in called
  846. // routines in the region are shared.
  847. if (VD && VD->hasGlobalStorage())
  848. DVar.CKind = OMPC_shared;
  849. // Non-static data members are shared by default.
  850. if (FD)
  851. DVar.CKind = OMPC_shared;
  852. return DVar;
  853. }
  854. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  855. // in a Construct, C/C++, predetermined, p.1]
  856. // Variables with automatic storage duration that are declared in a scope
  857. // inside the construct are private.
  858. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  859. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  860. DVar.CKind = OMPC_private;
  861. return DVar;
  862. }
  863. DVar.DKind = Iter->Directive;
  864. // Explicitly specified attributes and local variables with predetermined
  865. // attributes.
  866. if (Iter->SharingMap.count(D)) {
  867. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  868. DVar.RefExpr = Data.RefExpr.getPointer();
  869. DVar.PrivateCopy = Data.PrivateCopy;
  870. DVar.CKind = Data.Attributes;
  871. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  872. return DVar;
  873. }
  874. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  875. // in a Construct, C/C++, implicitly determined, p.1]
  876. // In a parallel or task construct, the data-sharing attributes of these
  877. // variables are determined by the default clause, if present.
  878. switch (Iter->DefaultAttr) {
  879. case DSA_shared:
  880. DVar.CKind = OMPC_shared;
  881. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  882. return DVar;
  883. case DSA_none:
  884. return DVar;
  885. case DSA_unspecified:
  886. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  887. // in a Construct, implicitly determined, p.2]
  888. // In a parallel construct, if no default clause is present, these
  889. // variables are shared.
  890. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  891. if ((isOpenMPParallelDirective(DVar.DKind) &&
  892. !isOpenMPTaskLoopDirective(DVar.DKind)) ||
  893. isOpenMPTeamsDirective(DVar.DKind)) {
  894. DVar.CKind = OMPC_shared;
  895. return DVar;
  896. }
  897. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  898. // in a Construct, implicitly determined, p.4]
  899. // In a task construct, if no default clause is present, a variable that in
  900. // the enclosing context is determined to be shared by all implicit tasks
  901. // bound to the current team is shared.
  902. if (isOpenMPTaskingDirective(DVar.DKind)) {
  903. DSAVarData DVarTemp;
  904. const_iterator I = Iter, E = end();
  905. do {
  906. ++I;
  907. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  908. // Referenced in a Construct, implicitly determined, p.6]
  909. // In a task construct, if no default clause is present, a variable
  910. // whose data-sharing attribute is not determined by the rules above is
  911. // firstprivate.
  912. DVarTemp = getDSA(I, D);
  913. if (DVarTemp.CKind != OMPC_shared) {
  914. DVar.RefExpr = nullptr;
  915. DVar.CKind = OMPC_firstprivate;
  916. return DVar;
  917. }
  918. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  919. DVar.CKind =
  920. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  921. return DVar;
  922. }
  923. }
  924. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  925. // in a Construct, implicitly determined, p.3]
  926. // For constructs other than task, if no default clause is present, these
  927. // variables inherit their data-sharing attributes from the enclosing
  928. // context.
  929. return getDSA(++Iter, D);
  930. }
  931. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  932. const Expr *NewDE) {
  933. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  934. D = getCanonicalDecl(D);
  935. SharingMapTy &StackElem = getTopOfStack();
  936. auto It = StackElem.AlignedMap.find(D);
  937. if (It == StackElem.AlignedMap.end()) {
  938. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  939. StackElem.AlignedMap[D] = NewDE;
  940. return nullptr;
  941. }
  942. assert(It->second && "Unexpected nullptr expr in the aligned map");
  943. return It->second;
  944. }
  945. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  946. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  947. D = getCanonicalDecl(D);
  948. SharingMapTy &StackElem = getTopOfStack();
  949. StackElem.LCVMap.try_emplace(
  950. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  951. }
  952. const DSAStackTy::LCDeclInfo
  953. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  954. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  955. D = getCanonicalDecl(D);
  956. const SharingMapTy &StackElem = getTopOfStack();
  957. auto It = StackElem.LCVMap.find(D);
  958. if (It != StackElem.LCVMap.end())
  959. return It->second;
  960. return {0, nullptr};
  961. }
  962. const DSAStackTy::LCDeclInfo
  963. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  964. const SharingMapTy *Parent = getSecondOnStackOrNull();
  965. assert(Parent && "Data-sharing attributes stack is empty");
  966. D = getCanonicalDecl(D);
  967. auto It = Parent->LCVMap.find(D);
  968. if (It != Parent->LCVMap.end())
  969. return It->second;
  970. return {0, nullptr};
  971. }
  972. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  973. const SharingMapTy *Parent = getSecondOnStackOrNull();
  974. assert(Parent && "Data-sharing attributes stack is empty");
  975. if (Parent->LCVMap.size() < I)
  976. return nullptr;
  977. for (const auto &Pair : Parent->LCVMap)
  978. if (Pair.second.first == I)
  979. return Pair.first;
  980. return nullptr;
  981. }
  982. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  983. DeclRefExpr *PrivateCopy) {
  984. D = getCanonicalDecl(D);
  985. if (A == OMPC_threadprivate) {
  986. DSAInfo &Data = Threadprivates[D];
  987. Data.Attributes = A;
  988. Data.RefExpr.setPointer(E);
  989. Data.PrivateCopy = nullptr;
  990. } else {
  991. DSAInfo &Data = getTopOfStack().SharingMap[D];
  992. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  993. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  994. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  995. (isLoopControlVariable(D).first && A == OMPC_private));
  996. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  997. Data.RefExpr.setInt(/*IntVal=*/true);
  998. return;
  999. }
  1000. const bool IsLastprivate =
  1001. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  1002. Data.Attributes = A;
  1003. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  1004. Data.PrivateCopy = PrivateCopy;
  1005. if (PrivateCopy) {
  1006. DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
  1007. Data.Attributes = A;
  1008. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  1009. Data.PrivateCopy = nullptr;
  1010. }
  1011. }
  1012. }
  1013. /// Build a variable declaration for OpenMP loop iteration variable.
  1014. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  1015. StringRef Name, const AttrVec *Attrs = nullptr,
  1016. DeclRefExpr *OrigRef = nullptr) {
  1017. DeclContext *DC = SemaRef.CurContext;
  1018. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1019. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1020. auto *Decl =
  1021. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  1022. if (Attrs) {
  1023. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  1024. I != E; ++I)
  1025. Decl->addAttr(*I);
  1026. }
  1027. Decl->setImplicit();
  1028. if (OrigRef) {
  1029. Decl->addAttr(
  1030. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  1031. }
  1032. return Decl;
  1033. }
  1034. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  1035. SourceLocation Loc,
  1036. bool RefersToCapture = false) {
  1037. D->setReferenced();
  1038. D->markUsed(S.Context);
  1039. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  1040. SourceLocation(), D, RefersToCapture, Loc, Ty,
  1041. VK_LValue);
  1042. }
  1043. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1044. BinaryOperatorKind BOK) {
  1045. D = getCanonicalDecl(D);
  1046. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1047. assert(
  1048. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1049. "Additional reduction info may be specified only for reduction items.");
  1050. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1051. assert(ReductionData.ReductionRange.isInvalid() &&
  1052. getTopOfStack().Directive == OMPD_taskgroup &&
  1053. "Additional reduction info may be specified only once for reduction "
  1054. "items.");
  1055. ReductionData.set(BOK, SR);
  1056. Expr *&TaskgroupReductionRef =
  1057. getTopOfStack().TaskgroupReductionRef;
  1058. if (!TaskgroupReductionRef) {
  1059. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1060. SemaRef.Context.VoidPtrTy, ".task_red.");
  1061. TaskgroupReductionRef =
  1062. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1063. }
  1064. }
  1065. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1066. const Expr *ReductionRef) {
  1067. D = getCanonicalDecl(D);
  1068. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1069. assert(
  1070. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1071. "Additional reduction info may be specified only for reduction items.");
  1072. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1073. assert(ReductionData.ReductionRange.isInvalid() &&
  1074. getTopOfStack().Directive == OMPD_taskgroup &&
  1075. "Additional reduction info may be specified only once for reduction "
  1076. "items.");
  1077. ReductionData.set(ReductionRef, SR);
  1078. Expr *&TaskgroupReductionRef =
  1079. getTopOfStack().TaskgroupReductionRef;
  1080. if (!TaskgroupReductionRef) {
  1081. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1082. SemaRef.Context.VoidPtrTy, ".task_red.");
  1083. TaskgroupReductionRef =
  1084. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1085. }
  1086. }
  1087. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1088. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  1089. Expr *&TaskgroupDescriptor) const {
  1090. D = getCanonicalDecl(D);
  1091. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1092. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1093. const DSAInfo &Data = I->SharingMap.lookup(D);
  1094. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1095. continue;
  1096. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1097. if (!ReductionData.ReductionOp ||
  1098. ReductionData.ReductionOp.is<const Expr *>())
  1099. return DSAVarData();
  1100. SR = ReductionData.ReductionRange;
  1101. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  1102. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1103. "expression for the descriptor is not "
  1104. "set.");
  1105. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1106. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1107. Data.PrivateCopy, I->DefaultAttrLoc);
  1108. }
  1109. return DSAVarData();
  1110. }
  1111. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1112. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  1113. Expr *&TaskgroupDescriptor) const {
  1114. D = getCanonicalDecl(D);
  1115. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1116. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1117. const DSAInfo &Data = I->SharingMap.lookup(D);
  1118. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1119. continue;
  1120. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1121. if (!ReductionData.ReductionOp ||
  1122. !ReductionData.ReductionOp.is<const Expr *>())
  1123. return DSAVarData();
  1124. SR = ReductionData.ReductionRange;
  1125. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1126. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1127. "expression for the descriptor is not "
  1128. "set.");
  1129. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1130. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1131. Data.PrivateCopy, I->DefaultAttrLoc);
  1132. }
  1133. return DSAVarData();
  1134. }
  1135. bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
  1136. D = D->getCanonicalDecl();
  1137. for (const_iterator E = end(); I != E; ++I) {
  1138. if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
  1139. isOpenMPTargetExecutionDirective(I->Directive)) {
  1140. Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  1141. Scope *CurScope = getCurScope();
  1142. while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
  1143. CurScope = CurScope->getParent();
  1144. return CurScope != TopScope;
  1145. }
  1146. }
  1147. return false;
  1148. }
  1149. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1150. bool AcceptIfMutable = true,
  1151. bool *IsClassType = nullptr) {
  1152. ASTContext &Context = SemaRef.getASTContext();
  1153. Type = Type.getNonReferenceType().getCanonicalType();
  1154. bool IsConstant = Type.isConstant(Context);
  1155. Type = Context.getBaseElementType(Type);
  1156. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1157. ? Type->getAsCXXRecordDecl()
  1158. : nullptr;
  1159. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1160. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1161. RD = CTD->getTemplatedDecl();
  1162. if (IsClassType)
  1163. *IsClassType = RD;
  1164. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1165. RD->hasDefinition() && RD->hasMutableFields());
  1166. }
  1167. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1168. QualType Type, OpenMPClauseKind CKind,
  1169. SourceLocation ELoc,
  1170. bool AcceptIfMutable = true,
  1171. bool ListItemNotVar = false) {
  1172. ASTContext &Context = SemaRef.getASTContext();
  1173. bool IsClassType;
  1174. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1175. unsigned Diag = ListItemNotVar
  1176. ? diag::err_omp_const_list_item
  1177. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1178. : diag::err_omp_const_variable;
  1179. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1180. if (!ListItemNotVar && D) {
  1181. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1182. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1183. VarDecl::DeclarationOnly;
  1184. SemaRef.Diag(D->getLocation(),
  1185. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1186. << D;
  1187. }
  1188. return true;
  1189. }
  1190. return false;
  1191. }
  1192. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1193. bool FromParent) {
  1194. D = getCanonicalDecl(D);
  1195. DSAVarData DVar;
  1196. auto *VD = dyn_cast<VarDecl>(D);
  1197. auto TI = Threadprivates.find(D);
  1198. if (TI != Threadprivates.end()) {
  1199. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1200. DVar.CKind = OMPC_threadprivate;
  1201. return DVar;
  1202. }
  1203. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1204. DVar.RefExpr = buildDeclRefExpr(
  1205. SemaRef, VD, D->getType().getNonReferenceType(),
  1206. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1207. DVar.CKind = OMPC_threadprivate;
  1208. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1209. return DVar;
  1210. }
  1211. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1212. // in a Construct, C/C++, predetermined, p.1]
  1213. // Variables appearing in threadprivate directives are threadprivate.
  1214. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1215. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1216. SemaRef.getLangOpts().OpenMPUseTLS &&
  1217. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1218. (VD && VD->getStorageClass() == SC_Register &&
  1219. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1220. DVar.RefExpr = buildDeclRefExpr(
  1221. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1222. DVar.CKind = OMPC_threadprivate;
  1223. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1224. return DVar;
  1225. }
  1226. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1227. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1228. !isLoopControlVariable(D).first) {
  1229. const_iterator IterTarget =
  1230. std::find_if(begin(), end(), [](const SharingMapTy &Data) {
  1231. return isOpenMPTargetExecutionDirective(Data.Directive);
  1232. });
  1233. if (IterTarget != end()) {
  1234. const_iterator ParentIterTarget = IterTarget + 1;
  1235. for (const_iterator Iter = begin();
  1236. Iter != ParentIterTarget; ++Iter) {
  1237. if (isOpenMPLocal(VD, Iter)) {
  1238. DVar.RefExpr =
  1239. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1240. D->getLocation());
  1241. DVar.CKind = OMPC_threadprivate;
  1242. return DVar;
  1243. }
  1244. }
  1245. if (!isClauseParsingMode() || IterTarget != begin()) {
  1246. auto DSAIter = IterTarget->SharingMap.find(D);
  1247. if (DSAIter != IterTarget->SharingMap.end() &&
  1248. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1249. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1250. DVar.CKind = OMPC_threadprivate;
  1251. return DVar;
  1252. }
  1253. const_iterator End = end();
  1254. if (!SemaRef.isOpenMPCapturedByRef(
  1255. D, std::distance(ParentIterTarget, End),
  1256. /*OpenMPCaptureLevel=*/0)) {
  1257. DVar.RefExpr =
  1258. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1259. IterTarget->ConstructLoc);
  1260. DVar.CKind = OMPC_threadprivate;
  1261. return DVar;
  1262. }
  1263. }
  1264. }
  1265. }
  1266. if (isStackEmpty())
  1267. // Not in OpenMP execution region and top scope was already checked.
  1268. return DVar;
  1269. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1270. // in a Construct, C/C++, predetermined, p.4]
  1271. // Static data members are shared.
  1272. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1273. // in a Construct, C/C++, predetermined, p.7]
  1274. // Variables with static storage duration that are declared in a scope
  1275. // inside the construct are shared.
  1276. if (VD && VD->isStaticDataMember()) {
  1277. // Check for explicitly specified attributes.
  1278. const_iterator I = begin();
  1279. const_iterator EndI = end();
  1280. if (FromParent && I != EndI)
  1281. ++I;
  1282. auto It = I->SharingMap.find(D);
  1283. if (It != I->SharingMap.end()) {
  1284. const DSAInfo &Data = It->getSecond();
  1285. DVar.RefExpr = Data.RefExpr.getPointer();
  1286. DVar.PrivateCopy = Data.PrivateCopy;
  1287. DVar.CKind = Data.Attributes;
  1288. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1289. DVar.DKind = I->Directive;
  1290. return DVar;
  1291. }
  1292. DVar.CKind = OMPC_shared;
  1293. return DVar;
  1294. }
  1295. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1296. // The predetermined shared attribute for const-qualified types having no
  1297. // mutable members was removed after OpenMP 3.1.
  1298. if (SemaRef.LangOpts.OpenMP <= 31) {
  1299. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1300. // in a Construct, C/C++, predetermined, p.6]
  1301. // Variables with const qualified type having no mutable member are
  1302. // shared.
  1303. if (isConstNotMutableType(SemaRef, D->getType())) {
  1304. // Variables with const-qualified type having no mutable member may be
  1305. // listed in a firstprivate clause, even if they are static data members.
  1306. DSAVarData DVarTemp = hasInnermostDSA(
  1307. D,
  1308. [](OpenMPClauseKind C) {
  1309. return C == OMPC_firstprivate || C == OMPC_shared;
  1310. },
  1311. MatchesAlways, FromParent);
  1312. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1313. return DVarTemp;
  1314. DVar.CKind = OMPC_shared;
  1315. return DVar;
  1316. }
  1317. }
  1318. // Explicitly specified attributes and local variables with predetermined
  1319. // attributes.
  1320. const_iterator I = begin();
  1321. const_iterator EndI = end();
  1322. if (FromParent && I != EndI)
  1323. ++I;
  1324. auto It = I->SharingMap.find(D);
  1325. if (It != I->SharingMap.end()) {
  1326. const DSAInfo &Data = It->getSecond();
  1327. DVar.RefExpr = Data.RefExpr.getPointer();
  1328. DVar.PrivateCopy = Data.PrivateCopy;
  1329. DVar.CKind = Data.Attributes;
  1330. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1331. DVar.DKind = I->Directive;
  1332. }
  1333. return DVar;
  1334. }
  1335. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1336. bool FromParent) const {
  1337. if (isStackEmpty()) {
  1338. const_iterator I;
  1339. return getDSA(I, D);
  1340. }
  1341. D = getCanonicalDecl(D);
  1342. const_iterator StartI = begin();
  1343. const_iterator EndI = end();
  1344. if (FromParent && StartI != EndI)
  1345. ++StartI;
  1346. return getDSA(StartI, D);
  1347. }
  1348. const DSAStackTy::DSAVarData
  1349. DSAStackTy::hasDSA(ValueDecl *D,
  1350. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1351. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1352. bool FromParent) const {
  1353. if (isStackEmpty())
  1354. return {};
  1355. D = getCanonicalDecl(D);
  1356. const_iterator I = begin();
  1357. const_iterator EndI = end();
  1358. if (FromParent && I != EndI)
  1359. ++I;
  1360. for (; I != EndI; ++I) {
  1361. if (!DPred(I->Directive) &&
  1362. !isImplicitOrExplicitTaskingRegion(I->Directive))
  1363. continue;
  1364. const_iterator NewI = I;
  1365. DSAVarData DVar = getDSA(NewI, D);
  1366. if (I == NewI && CPred(DVar.CKind))
  1367. return DVar;
  1368. }
  1369. return {};
  1370. }
  1371. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1372. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1373. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1374. bool FromParent) const {
  1375. if (isStackEmpty())
  1376. return {};
  1377. D = getCanonicalDecl(D);
  1378. const_iterator StartI = begin();
  1379. const_iterator EndI = end();
  1380. if (FromParent && StartI != EndI)
  1381. ++StartI;
  1382. if (StartI == EndI || !DPred(StartI->Directive))
  1383. return {};
  1384. const_iterator NewI = StartI;
  1385. DSAVarData DVar = getDSA(NewI, D);
  1386. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1387. }
  1388. bool DSAStackTy::hasExplicitDSA(
  1389. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1390. unsigned Level, bool NotLastprivate) const {
  1391. if (getStackSize() <= Level)
  1392. return false;
  1393. D = getCanonicalDecl(D);
  1394. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1395. auto I = StackElem.SharingMap.find(D);
  1396. if (I != StackElem.SharingMap.end() &&
  1397. I->getSecond().RefExpr.getPointer() &&
  1398. CPred(I->getSecond().Attributes) &&
  1399. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1400. return true;
  1401. // Check predetermined rules for the loop control variables.
  1402. auto LI = StackElem.LCVMap.find(D);
  1403. if (LI != StackElem.LCVMap.end())
  1404. return CPred(OMPC_private);
  1405. return false;
  1406. }
  1407. bool DSAStackTy::hasExplicitDirective(
  1408. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1409. unsigned Level) const {
  1410. if (getStackSize() <= Level)
  1411. return false;
  1412. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1413. return DPred(StackElem.Directive);
  1414. }
  1415. bool DSAStackTy::hasDirective(
  1416. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1417. const DeclarationNameInfo &, SourceLocation)>
  1418. DPred,
  1419. bool FromParent) const {
  1420. // We look only in the enclosing region.
  1421. size_t Skip = FromParent ? 2 : 1;
  1422. for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
  1423. I != E; ++I) {
  1424. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1425. return true;
  1426. }
  1427. return false;
  1428. }
  1429. void Sema::InitDataSharingAttributesStack() {
  1430. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1431. }
  1432. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1433. void Sema::pushOpenMPFunctionRegion() {
  1434. DSAStack->pushFunction();
  1435. }
  1436. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1437. DSAStack->popFunction(OldFSI);
  1438. }
  1439. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1440. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1441. "Expected OpenMP device compilation.");
  1442. return !S.isInOpenMPTargetExecutionDirective() &&
  1443. !S.isInOpenMPDeclareTargetContext();
  1444. }
  1445. namespace {
  1446. /// Status of the function emission on the host/device.
  1447. enum class FunctionEmissionStatus {
  1448. Emitted,
  1449. Discarded,
  1450. Unknown,
  1451. };
  1452. } // anonymous namespace
  1453. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1454. unsigned DiagID) {
  1455. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1456. "Expected OpenMP device compilation.");
  1457. FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
  1458. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1459. switch (FES) {
  1460. case FunctionEmissionStatus::Emitted:
  1461. Kind = DeviceDiagBuilder::K_Immediate;
  1462. break;
  1463. case FunctionEmissionStatus::Unknown:
  1464. Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
  1465. : DeviceDiagBuilder::K_Immediate;
  1466. break;
  1467. case FunctionEmissionStatus::TemplateDiscarded:
  1468. case FunctionEmissionStatus::OMPDiscarded:
  1469. Kind = DeviceDiagBuilder::K_Nop;
  1470. break;
  1471. case FunctionEmissionStatus::CUDADiscarded:
  1472. llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
  1473. break;
  1474. }
  1475. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1476. }
  1477. Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
  1478. unsigned DiagID) {
  1479. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1480. "Expected OpenMP host compilation.");
  1481. FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
  1482. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1483. switch (FES) {
  1484. case FunctionEmissionStatus::Emitted:
  1485. Kind = DeviceDiagBuilder::K_Immediate;
  1486. break;
  1487. case FunctionEmissionStatus::Unknown:
  1488. Kind = DeviceDiagBuilder::K_Deferred;
  1489. break;
  1490. case FunctionEmissionStatus::TemplateDiscarded:
  1491. case FunctionEmissionStatus::OMPDiscarded:
  1492. case FunctionEmissionStatus::CUDADiscarded:
  1493. Kind = DeviceDiagBuilder::K_Nop;
  1494. break;
  1495. }
  1496. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1497. }
  1498. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
  1499. bool CheckForDelayedContext) {
  1500. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1501. "Expected OpenMP device compilation.");
  1502. assert(Callee && "Callee may not be null.");
  1503. Callee = Callee->getMostRecentDecl();
  1504. FunctionDecl *Caller = getCurFunctionDecl();
  1505. // host only function are not available on the device.
  1506. if (Caller) {
  1507. FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
  1508. FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
  1509. assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
  1510. CalleeS != FunctionEmissionStatus::CUDADiscarded &&
  1511. "CUDADiscarded unexpected in OpenMP device function check");
  1512. if ((CallerS == FunctionEmissionStatus::Emitted ||
  1513. (!isOpenMPDeviceDelayedContext(*this) &&
  1514. CallerS == FunctionEmissionStatus::Unknown)) &&
  1515. CalleeS == FunctionEmissionStatus::OMPDiscarded) {
  1516. StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
  1517. OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1518. Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
  1519. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1520. diag::note_omp_marked_device_type_here)
  1521. << HostDevTy;
  1522. return;
  1523. }
  1524. }
  1525. // If the caller is known-emitted, mark the callee as known-emitted.
  1526. // Otherwise, mark the call in our call graph so we can traverse it later.
  1527. if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
  1528. (!Caller && !CheckForDelayedContext) ||
  1529. (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
  1530. markKnownEmitted(*this, Caller, Callee, Loc,
  1531. [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
  1532. return CheckForDelayedContext &&
  1533. S.getEmissionStatus(FD) ==
  1534. FunctionEmissionStatus::Emitted;
  1535. });
  1536. else if (Caller)
  1537. DeviceCallGraph[Caller].insert({Callee, Loc});
  1538. }
  1539. void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
  1540. bool CheckCaller) {
  1541. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1542. "Expected OpenMP host compilation.");
  1543. assert(Callee && "Callee may not be null.");
  1544. Callee = Callee->getMostRecentDecl();
  1545. FunctionDecl *Caller = getCurFunctionDecl();
  1546. // device only function are not available on the host.
  1547. if (Caller) {
  1548. FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
  1549. FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
  1550. assert(
  1551. (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
  1552. CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
  1553. "CUDADiscarded unexpected in OpenMP host function check");
  1554. if (CallerS == FunctionEmissionStatus::Emitted &&
  1555. CalleeS == FunctionEmissionStatus::OMPDiscarded) {
  1556. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1557. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1558. Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
  1559. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1560. diag::note_omp_marked_device_type_here)
  1561. << NoHostDevTy;
  1562. return;
  1563. }
  1564. }
  1565. // If the caller is known-emitted, mark the callee as known-emitted.
  1566. // Otherwise, mark the call in our call graph so we can traverse it later.
  1567. if (!shouldIgnoreInHostDeviceCheck(Callee)) {
  1568. if ((!CheckCaller && !Caller) ||
  1569. (Caller &&
  1570. getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
  1571. markKnownEmitted(
  1572. *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
  1573. return CheckCaller &&
  1574. S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
  1575. });
  1576. else if (Caller)
  1577. DeviceCallGraph[Caller].insert({Callee, Loc});
  1578. }
  1579. }
  1580. void Sema::checkOpenMPDeviceExpr(const Expr *E) {
  1581. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1582. "OpenMP device compilation mode is expected.");
  1583. QualType Ty = E->getType();
  1584. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1585. ((Ty->isFloat128Type() ||
  1586. (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
  1587. !Context.getTargetInfo().hasFloat128Type()) ||
  1588. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1589. !Context.getTargetInfo().hasInt128Type()))
  1590. targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
  1591. << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
  1592. << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
  1593. }
  1594. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
  1595. unsigned OpenMPCaptureLevel) const {
  1596. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1597. ASTContext &Ctx = getASTContext();
  1598. bool IsByRef = true;
  1599. // Find the directive that is associated with the provided scope.
  1600. D = cast<ValueDecl>(D->getCanonicalDecl());
  1601. QualType Ty = D->getType();
  1602. bool IsVariableUsedInMapClause = false;
  1603. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1604. // This table summarizes how a given variable should be passed to the device
  1605. // given its type and the clauses where it appears. This table is based on
  1606. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1607. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1608. //
  1609. // =========================================================================
  1610. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1611. // | |(tofrom:scalar)| | pvt | | | |
  1612. // =========================================================================
  1613. // | scl | | | | - | | bycopy|
  1614. // | scl | | - | x | - | - | bycopy|
  1615. // | scl | | x | - | - | - | null |
  1616. // | scl | x | | | - | | byref |
  1617. // | scl | x | - | x | - | - | bycopy|
  1618. // | scl | x | x | - | - | - | null |
  1619. // | scl | | - | - | - | x | byref |
  1620. // | scl | x | - | - | - | x | byref |
  1621. //
  1622. // | agg | n.a. | | | - | | byref |
  1623. // | agg | n.a. | - | x | - | - | byref |
  1624. // | agg | n.a. | x | - | - | - | null |
  1625. // | agg | n.a. | - | - | - | x | byref |
  1626. // | agg | n.a. | - | - | - | x[] | byref |
  1627. //
  1628. // | ptr | n.a. | | | - | | bycopy|
  1629. // | ptr | n.a. | - | x | - | - | bycopy|
  1630. // | ptr | n.a. | x | - | - | - | null |
  1631. // | ptr | n.a. | - | - | - | x | byref |
  1632. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1633. // | ptr | n.a. | - | - | x | | bycopy|
  1634. // | ptr | n.a. | - | - | x | x | bycopy|
  1635. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1636. // =========================================================================
  1637. // Legend:
  1638. // scl - scalar
  1639. // ptr - pointer
  1640. // agg - aggregate
  1641. // x - applies
  1642. // - - invalid in this combination
  1643. // [] - mapped with an array section
  1644. // byref - should be mapped by reference
  1645. // byval - should be mapped by value
  1646. // null - initialize a local variable to null on the device
  1647. //
  1648. // Observations:
  1649. // - All scalar declarations that show up in a map clause have to be passed
  1650. // by reference, because they may have been mapped in the enclosing data
  1651. // environment.
  1652. // - If the scalar value does not fit the size of uintptr, it has to be
  1653. // passed by reference, regardless the result in the table above.
  1654. // - For pointers mapped by value that have either an implicit map or an
  1655. // array section, the runtime library may pass the NULL value to the
  1656. // device instead of the value passed to it by the compiler.
  1657. if (Ty->isReferenceType())
  1658. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1659. // Locate map clauses and see if the variable being captured is referred to
  1660. // in any of those clauses. Here we only care about variables, not fields,
  1661. // because fields are part of aggregates.
  1662. bool IsVariableAssociatedWithSection = false;
  1663. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1664. D, Level,
  1665. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1666. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1667. MapExprComponents,
  1668. OpenMPClauseKind WhereFoundClauseKind) {
  1669. // Only the map clause information influences how a variable is
  1670. // captured. E.g. is_device_ptr does not require changing the default
  1671. // behavior.
  1672. if (WhereFoundClauseKind != OMPC_map)
  1673. return false;
  1674. auto EI = MapExprComponents.rbegin();
  1675. auto EE = MapExprComponents.rend();
  1676. assert(EI != EE && "Invalid map expression!");
  1677. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1678. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1679. ++EI;
  1680. if (EI == EE)
  1681. return false;
  1682. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1683. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1684. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1685. IsVariableAssociatedWithSection = true;
  1686. // There is nothing more we need to know about this variable.
  1687. return true;
  1688. }
  1689. // Keep looking for more map info.
  1690. return false;
  1691. });
  1692. if (IsVariableUsedInMapClause) {
  1693. // If variable is identified in a map clause it is always captured by
  1694. // reference except if it is a pointer that is dereferenced somehow.
  1695. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1696. } else {
  1697. // By default, all the data that has a scalar type is mapped by copy
  1698. // (except for reduction variables).
  1699. IsByRef =
  1700. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1701. !Ty->isAnyPointerType()) ||
  1702. !Ty->isScalarType() ||
  1703. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1704. DSAStack->hasExplicitDSA(
  1705. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1706. }
  1707. }
  1708. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1709. IsByRef =
  1710. ((IsVariableUsedInMapClause &&
  1711. DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
  1712. OMPD_target) ||
  1713. !DSAStack->hasExplicitDSA(
  1714. D,
  1715. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1716. Level, /*NotLastprivate=*/true)) &&
  1717. // If the variable is artificial and must be captured by value - try to
  1718. // capture by value.
  1719. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1720. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1721. }
  1722. // When passing data by copy, we need to make sure it fits the uintptr size
  1723. // and alignment, because the runtime library only deals with uintptr types.
  1724. // If it does not fit the uintptr size, we need to pass the data by reference
  1725. // instead.
  1726. if (!IsByRef &&
  1727. (Ctx.getTypeSizeInChars(Ty) >
  1728. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1729. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1730. IsByRef = true;
  1731. }
  1732. return IsByRef;
  1733. }
  1734. unsigned Sema::getOpenMPNestingLevel() const {
  1735. assert(getLangOpts().OpenMP);
  1736. return DSAStack->getNestingLevel();
  1737. }
  1738. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1739. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1740. !DSAStack->isClauseParsingMode()) ||
  1741. DSAStack->hasDirective(
  1742. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1743. SourceLocation) -> bool {
  1744. return isOpenMPTargetExecutionDirective(K);
  1745. },
  1746. false);
  1747. }
  1748. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
  1749. unsigned StopAt) {
  1750. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1751. D = getCanonicalDecl(D);
  1752. // If we want to determine whether the variable should be captured from the
  1753. // perspective of the current capturing scope, and we've already left all the
  1754. // capturing scopes of the top directive on the stack, check from the
  1755. // perspective of its parent directive (if any) instead.
  1756. DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
  1757. *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
  1758. // If we are attempting to capture a global variable in a directive with
  1759. // 'target' we return true so that this global is also mapped to the device.
  1760. //
  1761. auto *VD = dyn_cast<VarDecl>(D);
  1762. if (VD && !VD->hasLocalStorage() &&
  1763. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1764. if (isInOpenMPDeclareTargetContext()) {
  1765. // Try to mark variable as declare target if it is used in capturing
  1766. // regions.
  1767. if (LangOpts.OpenMP <= 45 &&
  1768. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1769. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1770. return nullptr;
  1771. } else if (isInOpenMPTargetExecutionDirective()) {
  1772. // If the declaration is enclosed in a 'declare target' directive,
  1773. // then it should not be captured.
  1774. //
  1775. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1776. return nullptr;
  1777. return VD;
  1778. }
  1779. }
  1780. if (CheckScopeInfo) {
  1781. bool OpenMPFound = false;
  1782. for (unsigned I = StopAt + 1; I > 0; --I) {
  1783. FunctionScopeInfo *FSI = FunctionScopes[I - 1];
  1784. if(!isa<CapturingScopeInfo>(FSI))
  1785. return nullptr;
  1786. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  1787. if (RSI->CapRegionKind == CR_OpenMP) {
  1788. OpenMPFound = true;
  1789. break;
  1790. }
  1791. }
  1792. if (!OpenMPFound)
  1793. return nullptr;
  1794. }
  1795. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1796. (!DSAStack->isClauseParsingMode() ||
  1797. DSAStack->getParentDirective() != OMPD_unknown)) {
  1798. auto &&Info = DSAStack->isLoopControlVariable(D);
  1799. if (Info.first ||
  1800. (VD && VD->hasLocalStorage() &&
  1801. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1802. (VD && DSAStack->isForceVarCapturing()))
  1803. return VD ? VD : Info.second;
  1804. DSAStackTy::DSAVarData DVarPrivate =
  1805. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1806. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1807. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1808. // Threadprivate variables must not be captured.
  1809. if (isOpenMPThreadPrivate(DVarPrivate.CKind))
  1810. return nullptr;
  1811. // The variable is not private or it is the variable in the directive with
  1812. // default(none) clause and not used in any clause.
  1813. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1814. [](OpenMPDirectiveKind) { return true; },
  1815. DSAStack->isClauseParsingMode());
  1816. if (DVarPrivate.CKind != OMPC_unknown ||
  1817. (VD && DSAStack->getDefaultDSA() == DSA_none))
  1818. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1819. }
  1820. return nullptr;
  1821. }
  1822. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1823. unsigned Level) const {
  1824. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1825. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1826. FunctionScopesIndex -= Regions.size();
  1827. }
  1828. void Sema::startOpenMPLoop() {
  1829. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1830. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1831. DSAStack->loopInit();
  1832. }
  1833. void Sema::startOpenMPCXXRangeFor() {
  1834. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1835. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1836. DSAStack->resetPossibleLoopCounter();
  1837. DSAStack->loopStart();
  1838. }
  1839. }
  1840. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1841. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1842. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1843. if (DSAStack->getAssociatedLoops() > 0 &&
  1844. !DSAStack->isLoopStarted()) {
  1845. DSAStack->resetPossibleLoopCounter(D);
  1846. DSAStack->loopStart();
  1847. return true;
  1848. }
  1849. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1850. DSAStack->isLoopControlVariable(D).first) &&
  1851. !DSAStack->hasExplicitDSA(
  1852. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1853. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1854. return true;
  1855. }
  1856. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1857. if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
  1858. DSAStack->isForceVarCapturing() &&
  1859. !DSAStack->hasExplicitDSA(
  1860. D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
  1861. return true;
  1862. }
  1863. return DSAStack->hasExplicitDSA(
  1864. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1865. (DSAStack->isClauseParsingMode() &&
  1866. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1867. // Consider taskgroup reduction descriptor variable a private to avoid
  1868. // possible capture in the region.
  1869. (DSAStack->hasExplicitDirective(
  1870. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1871. Level) &&
  1872. DSAStack->isTaskgroupReductionRef(D, Level));
  1873. }
  1874. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1875. unsigned Level) {
  1876. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1877. D = getCanonicalDecl(D);
  1878. OpenMPClauseKind OMPC = OMPC_unknown;
  1879. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1880. const unsigned NewLevel = I - 1;
  1881. if (DSAStack->hasExplicitDSA(D,
  1882. [&OMPC](const OpenMPClauseKind K) {
  1883. if (isOpenMPPrivate(K)) {
  1884. OMPC = K;
  1885. return true;
  1886. }
  1887. return false;
  1888. },
  1889. NewLevel))
  1890. break;
  1891. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1892. D, NewLevel,
  1893. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1894. OpenMPClauseKind) { return true; })) {
  1895. OMPC = OMPC_map;
  1896. break;
  1897. }
  1898. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1899. NewLevel)) {
  1900. OMPC = OMPC_map;
  1901. if (D->getType()->isScalarType() &&
  1902. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1903. DefaultMapAttributes::DMA_tofrom_scalar)
  1904. OMPC = OMPC_firstprivate;
  1905. break;
  1906. }
  1907. }
  1908. if (OMPC != OMPC_unknown)
  1909. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1910. }
  1911. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1912. unsigned Level) const {
  1913. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1914. // Return true if the current level is no longer enclosed in a target region.
  1915. const auto *VD = dyn_cast<VarDecl>(D);
  1916. return VD && !VD->hasLocalStorage() &&
  1917. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1918. Level);
  1919. }
  1920. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1921. void Sema::finalizeOpenMPDelayedAnalysis() {
  1922. assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
  1923. // Diagnose implicit declare target functions and their callees.
  1924. for (const auto &CallerCallees : DeviceCallGraph) {
  1925. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1926. OMPDeclareTargetDeclAttr::getDeviceType(
  1927. CallerCallees.getFirst()->getMostRecentDecl());
  1928. // Ignore host functions during device analyzis.
  1929. if (LangOpts.OpenMPIsDevice && DevTy &&
  1930. *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  1931. continue;
  1932. // Ignore nohost functions during host analyzis.
  1933. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1934. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  1935. continue;
  1936. for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
  1937. &Callee : CallerCallees.getSecond()) {
  1938. const FunctionDecl *FD = Callee.first->getMostRecentDecl();
  1939. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1940. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  1941. if (LangOpts.OpenMPIsDevice && DevTy &&
  1942. *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
  1943. // Diagnose host function called during device codegen.
  1944. StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
  1945. OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1946. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1947. << HostDevTy << 0;
  1948. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1949. diag::note_omp_marked_device_type_here)
  1950. << HostDevTy;
  1951. continue;
  1952. }
  1953. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1954. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  1955. // Diagnose nohost function called during host codegen.
  1956. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1957. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1958. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1959. << NoHostDevTy << 1;
  1960. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1961. diag::note_omp_marked_device_type_here)
  1962. << NoHostDevTy;
  1963. continue;
  1964. }
  1965. }
  1966. }
  1967. }
  1968. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1969. const DeclarationNameInfo &DirName,
  1970. Scope *CurScope, SourceLocation Loc) {
  1971. DSAStack->push(DKind, DirName, CurScope, Loc);
  1972. PushExpressionEvaluationContext(
  1973. ExpressionEvaluationContext::PotentiallyEvaluated);
  1974. }
  1975. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1976. DSAStack->setClauseParsingMode(K);
  1977. }
  1978. void Sema::EndOpenMPClause() {
  1979. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1980. }
  1981. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  1982. ArrayRef<OMPClause *> Clauses);
  1983. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1984. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1985. // A variable of class type (or array thereof) that appears in a lastprivate
  1986. // clause requires an accessible, unambiguous default constructor for the
  1987. // class type, unless the list item is also specified in a firstprivate
  1988. // clause.
  1989. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1990. for (OMPClause *C : D->clauses()) {
  1991. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1992. SmallVector<Expr *, 8> PrivateCopies;
  1993. for (Expr *DE : Clause->varlists()) {
  1994. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1995. PrivateCopies.push_back(nullptr);
  1996. continue;
  1997. }
  1998. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1999. auto *VD = cast<VarDecl>(DRE->getDecl());
  2000. QualType Type = VD->getType().getNonReferenceType();
  2001. const DSAStackTy::DSAVarData DVar =
  2002. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2003. if (DVar.CKind == OMPC_lastprivate) {
  2004. // Generate helper private variable and initialize it with the
  2005. // default value. The address of the original variable is replaced
  2006. // by the address of the new private variable in CodeGen. This new
  2007. // variable is not added to IdResolver, so the code in the OpenMP
  2008. // region uses original variable for proper diagnostics.
  2009. VarDecl *VDPrivate = buildVarDecl(
  2010. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  2011. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  2012. ActOnUninitializedDecl(VDPrivate);
  2013. if (VDPrivate->isInvalidDecl()) {
  2014. PrivateCopies.push_back(nullptr);
  2015. continue;
  2016. }
  2017. PrivateCopies.push_back(buildDeclRefExpr(
  2018. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  2019. } else {
  2020. // The variable is also a firstprivate, so initialization sequence
  2021. // for private copy is generated already.
  2022. PrivateCopies.push_back(nullptr);
  2023. }
  2024. }
  2025. Clause->setPrivateCopies(PrivateCopies);
  2026. }
  2027. }
  2028. // Check allocate clauses.
  2029. if (!CurContext->isDependentContext())
  2030. checkAllocateClauses(*this, DSAStack, D->clauses());
  2031. }
  2032. DSAStack->pop();
  2033. DiscardCleanupsInEvaluationContext();
  2034. PopExpressionEvaluationContext();
  2035. }
  2036. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  2037. Expr *NumIterations, Sema &SemaRef,
  2038. Scope *S, DSAStackTy *Stack);
  2039. namespace {
  2040. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  2041. private:
  2042. Sema &SemaRef;
  2043. public:
  2044. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2045. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2046. NamedDecl *ND = Candidate.getCorrectionDecl();
  2047. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  2048. return VD->hasGlobalStorage() &&
  2049. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2050. SemaRef.getCurScope());
  2051. }
  2052. return false;
  2053. }
  2054. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2055. return std::make_unique<VarDeclFilterCCC>(*this);
  2056. }
  2057. };
  2058. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  2059. private:
  2060. Sema &SemaRef;
  2061. public:
  2062. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2063. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2064. NamedDecl *ND = Candidate.getCorrectionDecl();
  2065. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  2066. isa<FunctionDecl>(ND))) {
  2067. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2068. SemaRef.getCurScope());
  2069. }
  2070. return false;
  2071. }
  2072. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2073. return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
  2074. }
  2075. };
  2076. } // namespace
  2077. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  2078. CXXScopeSpec &ScopeSpec,
  2079. const DeclarationNameInfo &Id,
  2080. OpenMPDirectiveKind Kind) {
  2081. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  2082. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  2083. if (Lookup.isAmbiguous())
  2084. return ExprError();
  2085. VarDecl *VD;
  2086. if (!Lookup.isSingleResult()) {
  2087. VarDeclFilterCCC CCC(*this);
  2088. if (TypoCorrection Corrected =
  2089. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  2090. CTK_ErrorRecovery)) {
  2091. diagnoseTypo(Corrected,
  2092. PDiag(Lookup.empty()
  2093. ? diag::err_undeclared_var_use_suggest
  2094. : diag::err_omp_expected_var_arg_suggest)
  2095. << Id.getName());
  2096. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  2097. } else {
  2098. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  2099. : diag::err_omp_expected_var_arg)
  2100. << Id.getName();
  2101. return ExprError();
  2102. }
  2103. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  2104. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  2105. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  2106. return ExprError();
  2107. }
  2108. Lookup.suppressDiagnostics();
  2109. // OpenMP [2.9.2, Syntax, C/C++]
  2110. // Variables must be file-scope, namespace-scope, or static block-scope.
  2111. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  2112. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  2113. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  2114. bool IsDecl =
  2115. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2116. Diag(VD->getLocation(),
  2117. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2118. << VD;
  2119. return ExprError();
  2120. }
  2121. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  2122. NamedDecl *ND = CanonicalVD;
  2123. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  2124. // A threadprivate directive for file-scope variables must appear outside
  2125. // any definition or declaration.
  2126. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  2127. !getCurLexicalContext()->isTranslationUnit()) {
  2128. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2129. << getOpenMPDirectiveName(Kind) << VD;
  2130. bool IsDecl =
  2131. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2132. Diag(VD->getLocation(),
  2133. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2134. << VD;
  2135. return ExprError();
  2136. }
  2137. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  2138. // A threadprivate directive for static class member variables must appear
  2139. // in the class definition, in the same scope in which the member
  2140. // variables are declared.
  2141. if (CanonicalVD->isStaticDataMember() &&
  2142. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  2143. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2144. << getOpenMPDirectiveName(Kind) << VD;
  2145. bool IsDecl =
  2146. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2147. Diag(VD->getLocation(),
  2148. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2149. << VD;
  2150. return ExprError();
  2151. }
  2152. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  2153. // A threadprivate directive for namespace-scope variables must appear
  2154. // outside any definition or declaration other than the namespace
  2155. // definition itself.
  2156. if (CanonicalVD->getDeclContext()->isNamespace() &&
  2157. (!getCurLexicalContext()->isFileContext() ||
  2158. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  2159. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2160. << getOpenMPDirectiveName(Kind) << VD;
  2161. bool IsDecl =
  2162. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2163. Diag(VD->getLocation(),
  2164. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2165. << VD;
  2166. return ExprError();
  2167. }
  2168. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  2169. // A threadprivate directive for static block-scope variables must appear
  2170. // in the scope of the variable and not in a nested scope.
  2171. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  2172. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  2173. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2174. << getOpenMPDirectiveName(Kind) << VD;
  2175. bool IsDecl =
  2176. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2177. Diag(VD->getLocation(),
  2178. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2179. << VD;
  2180. return ExprError();
  2181. }
  2182. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  2183. // A threadprivate directive must lexically precede all references to any
  2184. // of the variables in its list.
  2185. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  2186. !DSAStack->isThreadPrivate(VD)) {
  2187. Diag(Id.getLoc(), diag::err_omp_var_used)
  2188. << getOpenMPDirectiveName(Kind) << VD;
  2189. return ExprError();
  2190. }
  2191. QualType ExprType = VD->getType().getNonReferenceType();
  2192. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  2193. SourceLocation(), VD,
  2194. /*RefersToEnclosingVariableOrCapture=*/false,
  2195. Id.getLoc(), ExprType, VK_LValue);
  2196. }
  2197. Sema::DeclGroupPtrTy
  2198. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  2199. ArrayRef<Expr *> VarList) {
  2200. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  2201. CurContext->addDecl(D);
  2202. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2203. }
  2204. return nullptr;
  2205. }
  2206. namespace {
  2207. class LocalVarRefChecker final
  2208. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  2209. Sema &SemaRef;
  2210. public:
  2211. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2212. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2213. if (VD->hasLocalStorage()) {
  2214. SemaRef.Diag(E->getBeginLoc(),
  2215. diag::err_omp_local_var_in_threadprivate_init)
  2216. << E->getSourceRange();
  2217. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  2218. << VD << VD->getSourceRange();
  2219. return true;
  2220. }
  2221. }
  2222. return false;
  2223. }
  2224. bool VisitStmt(const Stmt *S) {
  2225. for (const Stmt *Child : S->children()) {
  2226. if (Child && Visit(Child))
  2227. return true;
  2228. }
  2229. return false;
  2230. }
  2231. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  2232. };
  2233. } // namespace
  2234. OMPThreadPrivateDecl *
  2235. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  2236. SmallVector<Expr *, 8> Vars;
  2237. for (Expr *RefExpr : VarList) {
  2238. auto *DE = cast<DeclRefExpr>(RefExpr);
  2239. auto *VD = cast<VarDecl>(DE->getDecl());
  2240. SourceLocation ILoc = DE->getExprLoc();
  2241. // Mark variable as used.
  2242. VD->setReferenced();
  2243. VD->markUsed(Context);
  2244. QualType QType = VD->getType();
  2245. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2246. // It will be analyzed later.
  2247. Vars.push_back(DE);
  2248. continue;
  2249. }
  2250. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2251. // A threadprivate variable must not have an incomplete type.
  2252. if (RequireCompleteType(ILoc, VD->getType(),
  2253. diag::err_omp_threadprivate_incomplete_type)) {
  2254. continue;
  2255. }
  2256. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2257. // A threadprivate variable must not have a reference type.
  2258. if (VD->getType()->isReferenceType()) {
  2259. Diag(ILoc, diag::err_omp_ref_type_arg)
  2260. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  2261. bool IsDecl =
  2262. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2263. Diag(VD->getLocation(),
  2264. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2265. << VD;
  2266. continue;
  2267. }
  2268. // Check if this is a TLS variable. If TLS is not being supported, produce
  2269. // the corresponding diagnostic.
  2270. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  2271. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  2272. getLangOpts().OpenMPUseTLS &&
  2273. getASTContext().getTargetInfo().isTLSSupported())) ||
  2274. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2275. !VD->isLocalVarDecl())) {
  2276. Diag(ILoc, diag::err_omp_var_thread_local)
  2277. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  2278. bool IsDecl =
  2279. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2280. Diag(VD->getLocation(),
  2281. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2282. << VD;
  2283. continue;
  2284. }
  2285. // Check if initial value of threadprivate variable reference variable with
  2286. // local storage (it is not supported by runtime).
  2287. if (const Expr *Init = VD->getAnyInitializer()) {
  2288. LocalVarRefChecker Checker(*this);
  2289. if (Checker.Visit(Init))
  2290. continue;
  2291. }
  2292. Vars.push_back(RefExpr);
  2293. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2294. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2295. Context, SourceRange(Loc, Loc)));
  2296. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2297. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2298. }
  2299. OMPThreadPrivateDecl *D = nullptr;
  2300. if (!Vars.empty()) {
  2301. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2302. Vars);
  2303. D->setAccess(AS_public);
  2304. }
  2305. return D;
  2306. }
  2307. static OMPAllocateDeclAttr::AllocatorTypeTy
  2308. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  2309. if (!Allocator)
  2310. return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2311. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2312. Allocator->isInstantiationDependent() ||
  2313. Allocator->containsUnexpandedParameterPack())
  2314. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2315. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2316. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2317. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2318. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  2319. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  2320. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  2321. llvm::FoldingSetNodeID AEId, DAEId;
  2322. AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  2323. DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
  2324. if (AEId == DAEId) {
  2325. AllocatorKindRes = AllocatorKind;
  2326. break;
  2327. }
  2328. }
  2329. return AllocatorKindRes;
  2330. }
  2331. static bool checkPreviousOMPAllocateAttribute(
  2332. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  2333. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  2334. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  2335. return false;
  2336. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  2337. Expr *PrevAllocator = A->getAllocator();
  2338. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  2339. getAllocatorKind(S, Stack, PrevAllocator);
  2340. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  2341. if (AllocatorsMatch &&
  2342. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  2343. Allocator && PrevAllocator) {
  2344. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2345. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  2346. llvm::FoldingSetNodeID AEId, PAEId;
  2347. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  2348. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  2349. AllocatorsMatch = AEId == PAEId;
  2350. }
  2351. if (!AllocatorsMatch) {
  2352. SmallString<256> AllocatorBuffer;
  2353. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  2354. if (Allocator)
  2355. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  2356. SmallString<256> PrevAllocatorBuffer;
  2357. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  2358. if (PrevAllocator)
  2359. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  2360. S.getPrintingPolicy());
  2361. SourceLocation AllocatorLoc =
  2362. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  2363. SourceRange AllocatorRange =
  2364. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  2365. SourceLocation PrevAllocatorLoc =
  2366. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  2367. SourceRange PrevAllocatorRange =
  2368. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  2369. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  2370. << (Allocator ? 1 : 0) << AllocatorStream.str()
  2371. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  2372. << AllocatorRange;
  2373. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  2374. << PrevAllocatorRange;
  2375. return true;
  2376. }
  2377. return false;
  2378. }
  2379. static void
  2380. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  2381. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  2382. Expr *Allocator, SourceRange SR) {
  2383. if (VD->hasAttr<OMPAllocateDeclAttr>())
  2384. return;
  2385. if (Allocator &&
  2386. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2387. Allocator->isInstantiationDependent() ||
  2388. Allocator->containsUnexpandedParameterPack()))
  2389. return;
  2390. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  2391. Allocator, SR);
  2392. VD->addAttr(A);
  2393. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  2394. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2395. }
  2396. Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
  2397. SourceLocation Loc, ArrayRef<Expr *> VarList,
  2398. ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
  2399. assert(Clauses.size() <= 1 && "Expected at most one clause.");
  2400. Expr *Allocator = nullptr;
  2401. if (Clauses.empty()) {
  2402. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  2403. // allocate directives that appear in a target region must specify an
  2404. // allocator clause unless a requires directive with the dynamic_allocators
  2405. // clause is present in the same compilation unit.
  2406. if (LangOpts.OpenMPIsDevice &&
  2407. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  2408. targetDiag(Loc, diag::err_expected_allocator_clause);
  2409. } else {
  2410. Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
  2411. }
  2412. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  2413. getAllocatorKind(*this, DSAStack, Allocator);
  2414. SmallVector<Expr *, 8> Vars;
  2415. for (Expr *RefExpr : VarList) {
  2416. auto *DE = cast<DeclRefExpr>(RefExpr);
  2417. auto *VD = cast<VarDecl>(DE->getDecl());
  2418. // Check if this is a TLS variable or global register.
  2419. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2420. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2421. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2422. !VD->isLocalVarDecl()))
  2423. continue;
  2424. // If the used several times in the allocate directive, the same allocator
  2425. // must be used.
  2426. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  2427. AllocatorKind, Allocator))
  2428. continue;
  2429. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  2430. // If a list item has a static storage type, the allocator expression in the
  2431. // allocator clause must be a constant expression that evaluates to one of
  2432. // the predefined memory allocator values.
  2433. if (Allocator && VD->hasGlobalStorage()) {
  2434. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  2435. Diag(Allocator->getExprLoc(),
  2436. diag::err_omp_expected_predefined_allocator)
  2437. << Allocator->getSourceRange();
  2438. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  2439. VarDecl::DeclarationOnly;
  2440. Diag(VD->getLocation(),
  2441. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2442. << VD;
  2443. continue;
  2444. }
  2445. }
  2446. Vars.push_back(RefExpr);
  2447. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
  2448. DE->getSourceRange());
  2449. }
  2450. if (Vars.empty())
  2451. return nullptr;
  2452. if (!Owner)
  2453. Owner = getCurLexicalContext();
  2454. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2455. D->setAccess(AS_public);
  2456. Owner->addDecl(D);
  2457. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2458. }
  2459. Sema::DeclGroupPtrTy
  2460. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2461. ArrayRef<OMPClause *> ClauseList) {
  2462. OMPRequiresDecl *D = nullptr;
  2463. if (!CurContext->isFileContext()) {
  2464. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2465. } else {
  2466. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2467. if (D) {
  2468. CurContext->addDecl(D);
  2469. DSAStack->addRequiresDecl(D);
  2470. }
  2471. }
  2472. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2473. }
  2474. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2475. ArrayRef<OMPClause *> ClauseList) {
  2476. /// For target specific clauses, the requires directive cannot be
  2477. /// specified after the handling of any of the target regions in the
  2478. /// current compilation unit.
  2479. ArrayRef<SourceLocation> TargetLocations =
  2480. DSAStack->getEncounteredTargetLocs();
  2481. if (!TargetLocations.empty()) {
  2482. for (const OMPClause *CNew : ClauseList) {
  2483. // Check if any of the requires clauses affect target regions.
  2484. if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
  2485. isa<OMPUnifiedAddressClause>(CNew) ||
  2486. isa<OMPReverseOffloadClause>(CNew) ||
  2487. isa<OMPDynamicAllocatorsClause>(CNew)) {
  2488. Diag(Loc, diag::err_omp_target_before_requires)
  2489. << getOpenMPClauseName(CNew->getClauseKind());
  2490. for (SourceLocation TargetLoc : TargetLocations) {
  2491. Diag(TargetLoc, diag::note_omp_requires_encountered_target);
  2492. }
  2493. }
  2494. }
  2495. }
  2496. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2497. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2498. ClauseList);
  2499. return nullptr;
  2500. }
  2501. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2502. const ValueDecl *D,
  2503. const DSAStackTy::DSAVarData &DVar,
  2504. bool IsLoopIterVar = false) {
  2505. if (DVar.RefExpr) {
  2506. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2507. << getOpenMPClauseName(DVar.CKind);
  2508. return;
  2509. }
  2510. enum {
  2511. PDSA_StaticMemberShared,
  2512. PDSA_StaticLocalVarShared,
  2513. PDSA_LoopIterVarPrivate,
  2514. PDSA_LoopIterVarLinear,
  2515. PDSA_LoopIterVarLastprivate,
  2516. PDSA_ConstVarShared,
  2517. PDSA_GlobalVarShared,
  2518. PDSA_TaskVarFirstprivate,
  2519. PDSA_LocalVarPrivate,
  2520. PDSA_Implicit
  2521. } Reason = PDSA_Implicit;
  2522. bool ReportHint = false;
  2523. auto ReportLoc = D->getLocation();
  2524. auto *VD = dyn_cast<VarDecl>(D);
  2525. if (IsLoopIterVar) {
  2526. if (DVar.CKind == OMPC_private)
  2527. Reason = PDSA_LoopIterVarPrivate;
  2528. else if (DVar.CKind == OMPC_lastprivate)
  2529. Reason = PDSA_LoopIterVarLastprivate;
  2530. else
  2531. Reason = PDSA_LoopIterVarLinear;
  2532. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2533. DVar.CKind == OMPC_firstprivate) {
  2534. Reason = PDSA_TaskVarFirstprivate;
  2535. ReportLoc = DVar.ImplicitDSALoc;
  2536. } else if (VD && VD->isStaticLocal())
  2537. Reason = PDSA_StaticLocalVarShared;
  2538. else if (VD && VD->isStaticDataMember())
  2539. Reason = PDSA_StaticMemberShared;
  2540. else if (VD && VD->isFileVarDecl())
  2541. Reason = PDSA_GlobalVarShared;
  2542. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2543. Reason = PDSA_ConstVarShared;
  2544. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2545. ReportHint = true;
  2546. Reason = PDSA_LocalVarPrivate;
  2547. }
  2548. if (Reason != PDSA_Implicit) {
  2549. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2550. << Reason << ReportHint
  2551. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2552. } else if (DVar.ImplicitDSALoc.isValid()) {
  2553. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2554. << getOpenMPClauseName(DVar.CKind);
  2555. }
  2556. }
  2557. namespace {
  2558. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2559. DSAStackTy *Stack;
  2560. Sema &SemaRef;
  2561. bool ErrorFound = false;
  2562. CapturedStmt *CS = nullptr;
  2563. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2564. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2565. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2566. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2567. void VisitSubCaptures(OMPExecutableDirective *S) {
  2568. // Check implicitly captured variables.
  2569. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2570. return;
  2571. visitSubCaptures(S->getInnermostCapturedStmt());
  2572. }
  2573. public:
  2574. void VisitDeclRefExpr(DeclRefExpr *E) {
  2575. if (E->isTypeDependent() || E->isValueDependent() ||
  2576. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2577. return;
  2578. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2579. // Check the datasharing rules for the expressions in the clauses.
  2580. if (!CS) {
  2581. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  2582. if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
  2583. Visit(CED->getInit());
  2584. return;
  2585. }
  2586. } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
  2587. // Do not analyze internal variables and do not enclose them into
  2588. // implicit clauses.
  2589. return;
  2590. VD = VD->getCanonicalDecl();
  2591. // Skip internally declared variables.
  2592. if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
  2593. return;
  2594. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2595. // Check if the variable has explicit DSA set and stop analysis if it so.
  2596. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2597. return;
  2598. // Skip internally declared static variables.
  2599. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2600. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2601. if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
  2602. (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  2603. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2604. return;
  2605. SourceLocation ELoc = E->getExprLoc();
  2606. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2607. // The default(none) clause requires that each variable that is referenced
  2608. // in the construct, and does not have a predetermined data-sharing
  2609. // attribute, must have its data-sharing attribute explicitly determined
  2610. // by being listed in a data-sharing attribute clause.
  2611. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2612. isImplicitOrExplicitTaskingRegion(DKind) &&
  2613. VarsWithInheritedDSA.count(VD) == 0) {
  2614. VarsWithInheritedDSA[VD] = E;
  2615. return;
  2616. }
  2617. if (isOpenMPTargetExecutionDirective(DKind) &&
  2618. !Stack->isLoopControlVariable(VD).first) {
  2619. if (!Stack->checkMappableExprComponentListsForDecl(
  2620. VD, /*CurrentRegionOnly=*/true,
  2621. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2622. StackComponents,
  2623. OpenMPClauseKind) {
  2624. // Variable is used if it has been marked as an array, array
  2625. // section or the variable iself.
  2626. return StackComponents.size() == 1 ||
  2627. std::all_of(
  2628. std::next(StackComponents.rbegin()),
  2629. StackComponents.rend(),
  2630. [](const OMPClauseMappableExprCommon::
  2631. MappableComponent &MC) {
  2632. return MC.getAssociatedDeclaration() ==
  2633. nullptr &&
  2634. (isa<OMPArraySectionExpr>(
  2635. MC.getAssociatedExpression()) ||
  2636. isa<ArraySubscriptExpr>(
  2637. MC.getAssociatedExpression()));
  2638. });
  2639. })) {
  2640. bool IsFirstprivate = false;
  2641. // By default lambdas are captured as firstprivates.
  2642. if (const auto *RD =
  2643. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2644. IsFirstprivate = RD->isLambda();
  2645. IsFirstprivate =
  2646. IsFirstprivate ||
  2647. (VD->getType().getNonReferenceType()->isScalarType() &&
  2648. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2649. if (IsFirstprivate)
  2650. ImplicitFirstprivate.emplace_back(E);
  2651. else
  2652. ImplicitMap.emplace_back(E);
  2653. return;
  2654. }
  2655. }
  2656. // OpenMP [2.9.3.6, Restrictions, p.2]
  2657. // A list item that appears in a reduction clause of the innermost
  2658. // enclosing worksharing or parallel construct may not be accessed in an
  2659. // explicit task.
  2660. DVar = Stack->hasInnermostDSA(
  2661. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2662. [](OpenMPDirectiveKind K) {
  2663. return isOpenMPParallelDirective(K) ||
  2664. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2665. },
  2666. /*FromParent=*/true);
  2667. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2668. ErrorFound = true;
  2669. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2670. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2671. return;
  2672. }
  2673. // Define implicit data-sharing attributes for task.
  2674. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2675. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2676. !Stack->isLoopControlVariable(VD).first) {
  2677. ImplicitFirstprivate.push_back(E);
  2678. return;
  2679. }
  2680. // Store implicitly used globals with declare target link for parent
  2681. // target.
  2682. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  2683. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2684. Stack->addToParentTargetRegionLinkGlobals(E);
  2685. return;
  2686. }
  2687. }
  2688. }
  2689. void VisitMemberExpr(MemberExpr *E) {
  2690. if (E->isTypeDependent() || E->isValueDependent() ||
  2691. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2692. return;
  2693. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2694. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2695. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2696. if (!FD)
  2697. return;
  2698. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2699. // Check if the variable has explicit DSA set and stop analysis if it
  2700. // so.
  2701. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2702. return;
  2703. if (isOpenMPTargetExecutionDirective(DKind) &&
  2704. !Stack->isLoopControlVariable(FD).first &&
  2705. !Stack->checkMappableExprComponentListsForDecl(
  2706. FD, /*CurrentRegionOnly=*/true,
  2707. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2708. StackComponents,
  2709. OpenMPClauseKind) {
  2710. return isa<CXXThisExpr>(
  2711. cast<MemberExpr>(
  2712. StackComponents.back().getAssociatedExpression())
  2713. ->getBase()
  2714. ->IgnoreParens());
  2715. })) {
  2716. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2717. // A bit-field cannot appear in a map clause.
  2718. //
  2719. if (FD->isBitField())
  2720. return;
  2721. // Check to see if the member expression is referencing a class that
  2722. // has already been explicitly mapped
  2723. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2724. return;
  2725. ImplicitMap.emplace_back(E);
  2726. return;
  2727. }
  2728. SourceLocation ELoc = E->getExprLoc();
  2729. // OpenMP [2.9.3.6, Restrictions, p.2]
  2730. // A list item that appears in a reduction clause of the innermost
  2731. // enclosing worksharing or parallel construct may not be accessed in
  2732. // an explicit task.
  2733. DVar = Stack->hasInnermostDSA(
  2734. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2735. [](OpenMPDirectiveKind K) {
  2736. return isOpenMPParallelDirective(K) ||
  2737. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2738. },
  2739. /*FromParent=*/true);
  2740. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2741. ErrorFound = true;
  2742. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2743. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2744. return;
  2745. }
  2746. // Define implicit data-sharing attributes for task.
  2747. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2748. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2749. !Stack->isLoopControlVariable(FD).first) {
  2750. // Check if there is a captured expression for the current field in the
  2751. // region. Do not mark it as firstprivate unless there is no captured
  2752. // expression.
  2753. // TODO: try to make it firstprivate.
  2754. if (DVar.CKind != OMPC_unknown)
  2755. ImplicitFirstprivate.push_back(E);
  2756. }
  2757. return;
  2758. }
  2759. if (isOpenMPTargetExecutionDirective(DKind)) {
  2760. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2761. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2762. /*NoDiagnose=*/true))
  2763. return;
  2764. const auto *VD = cast<ValueDecl>(
  2765. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2766. if (!Stack->checkMappableExprComponentListsForDecl(
  2767. VD, /*CurrentRegionOnly=*/true,
  2768. [&CurComponents](
  2769. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2770. StackComponents,
  2771. OpenMPClauseKind) {
  2772. auto CCI = CurComponents.rbegin();
  2773. auto CCE = CurComponents.rend();
  2774. for (const auto &SC : llvm::reverse(StackComponents)) {
  2775. // Do both expressions have the same kind?
  2776. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2777. SC.getAssociatedExpression()->getStmtClass())
  2778. if (!(isa<OMPArraySectionExpr>(
  2779. SC.getAssociatedExpression()) &&
  2780. isa<ArraySubscriptExpr>(
  2781. CCI->getAssociatedExpression())))
  2782. return false;
  2783. const Decl *CCD = CCI->getAssociatedDeclaration();
  2784. const Decl *SCD = SC.getAssociatedDeclaration();
  2785. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2786. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2787. if (SCD != CCD)
  2788. return false;
  2789. std::advance(CCI, 1);
  2790. if (CCI == CCE)
  2791. break;
  2792. }
  2793. return true;
  2794. })) {
  2795. Visit(E->getBase());
  2796. }
  2797. } else {
  2798. Visit(E->getBase());
  2799. }
  2800. }
  2801. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2802. for (OMPClause *C : S->clauses()) {
  2803. // Skip analysis of arguments of implicitly defined firstprivate clause
  2804. // for task|target directives.
  2805. // Skip analysis of arguments of implicitly defined map clause for target
  2806. // directives.
  2807. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2808. C->isImplicit())) {
  2809. for (Stmt *CC : C->children()) {
  2810. if (CC)
  2811. Visit(CC);
  2812. }
  2813. }
  2814. }
  2815. // Check implicitly captured variables.
  2816. VisitSubCaptures(S);
  2817. }
  2818. void VisitStmt(Stmt *S) {
  2819. for (Stmt *C : S->children()) {
  2820. if (C) {
  2821. // Check implicitly captured variables in the task-based directives to
  2822. // check if they must be firstprivatized.
  2823. Visit(C);
  2824. }
  2825. }
  2826. }
  2827. void visitSubCaptures(CapturedStmt *S) {
  2828. for (const CapturedStmt::Capture &Cap : S->captures()) {
  2829. if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
  2830. continue;
  2831. VarDecl *VD = Cap.getCapturedVar();
  2832. // Do not try to map the variable if it or its sub-component was mapped
  2833. // already.
  2834. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2835. Stack->checkMappableExprComponentListsForDecl(
  2836. VD, /*CurrentRegionOnly=*/true,
  2837. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2838. OpenMPClauseKind) { return true; }))
  2839. continue;
  2840. DeclRefExpr *DRE = buildDeclRefExpr(
  2841. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2842. Cap.getLocation(), /*RefersToCapture=*/true);
  2843. Visit(DRE);
  2844. }
  2845. }
  2846. bool isErrorFound() const { return ErrorFound; }
  2847. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2848. return ImplicitFirstprivate;
  2849. }
  2850. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2851. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2852. return VarsWithInheritedDSA;
  2853. }
  2854. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2855. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  2856. // Process declare target link variables for the target directives.
  2857. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  2858. for (DeclRefExpr *E : Stack->getLinkGlobals())
  2859. Visit(E);
  2860. }
  2861. }
  2862. };
  2863. } // namespace
  2864. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2865. switch (DKind) {
  2866. case OMPD_parallel:
  2867. case OMPD_parallel_for:
  2868. case OMPD_parallel_for_simd:
  2869. case OMPD_parallel_sections:
  2870. case OMPD_teams:
  2871. case OMPD_teams_distribute:
  2872. case OMPD_teams_distribute_simd: {
  2873. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2874. QualType KmpInt32PtrTy =
  2875. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2876. Sema::CapturedParamNameType Params[] = {
  2877. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2878. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2879. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2880. };
  2881. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2882. Params);
  2883. break;
  2884. }
  2885. case OMPD_target_teams:
  2886. case OMPD_target_parallel:
  2887. case OMPD_target_parallel_for:
  2888. case OMPD_target_parallel_for_simd:
  2889. case OMPD_target_teams_distribute:
  2890. case OMPD_target_teams_distribute_simd: {
  2891. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2892. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2893. QualType KmpInt32PtrTy =
  2894. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2895. QualType Args[] = {VoidPtrTy};
  2896. FunctionProtoType::ExtProtoInfo EPI;
  2897. EPI.Variadic = true;
  2898. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2899. Sema::CapturedParamNameType Params[] = {
  2900. std::make_pair(".global_tid.", KmpInt32Ty),
  2901. std::make_pair(".part_id.", KmpInt32PtrTy),
  2902. std::make_pair(".privates.", VoidPtrTy),
  2903. std::make_pair(
  2904. ".copy_fn.",
  2905. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2906. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2907. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2908. };
  2909. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2910. Params, /*OpenMPCaptureLevel=*/0);
  2911. // Mark this captured region as inlined, because we don't use outlined
  2912. // function directly.
  2913. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2914. AlwaysInlineAttr::CreateImplicit(
  2915. Context, {}, AttributeCommonInfo::AS_Keyword,
  2916. AlwaysInlineAttr::Keyword_forceinline));
  2917. Sema::CapturedParamNameType ParamsTarget[] = {
  2918. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2919. };
  2920. // Start a captured region for 'target' with no implicit parameters.
  2921. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2922. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  2923. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2924. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2925. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2926. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2927. };
  2928. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2929. // the same implicit parameters.
  2930. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2931. ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
  2932. break;
  2933. }
  2934. case OMPD_target:
  2935. case OMPD_target_simd: {
  2936. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2937. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2938. QualType KmpInt32PtrTy =
  2939. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2940. QualType Args[] = {VoidPtrTy};
  2941. FunctionProtoType::ExtProtoInfo EPI;
  2942. EPI.Variadic = true;
  2943. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2944. Sema::CapturedParamNameType Params[] = {
  2945. std::make_pair(".global_tid.", KmpInt32Ty),
  2946. std::make_pair(".part_id.", KmpInt32PtrTy),
  2947. std::make_pair(".privates.", VoidPtrTy),
  2948. std::make_pair(
  2949. ".copy_fn.",
  2950. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2951. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2952. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2953. };
  2954. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2955. Params, /*OpenMPCaptureLevel=*/0);
  2956. // Mark this captured region as inlined, because we don't use outlined
  2957. // function directly.
  2958. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2959. AlwaysInlineAttr::CreateImplicit(
  2960. Context, {}, AttributeCommonInfo::AS_Keyword,
  2961. AlwaysInlineAttr::Keyword_forceinline));
  2962. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2963. std::make_pair(StringRef(), QualType()),
  2964. /*OpenMPCaptureLevel=*/1);
  2965. break;
  2966. }
  2967. case OMPD_simd:
  2968. case OMPD_for:
  2969. case OMPD_for_simd:
  2970. case OMPD_sections:
  2971. case OMPD_section:
  2972. case OMPD_single:
  2973. case OMPD_master:
  2974. case OMPD_critical:
  2975. case OMPD_taskgroup:
  2976. case OMPD_distribute:
  2977. case OMPD_distribute_simd:
  2978. case OMPD_ordered:
  2979. case OMPD_atomic:
  2980. case OMPD_target_data: {
  2981. Sema::CapturedParamNameType Params[] = {
  2982. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2983. };
  2984. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2985. Params);
  2986. break;
  2987. }
  2988. case OMPD_task: {
  2989. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2990. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2991. QualType KmpInt32PtrTy =
  2992. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2993. QualType Args[] = {VoidPtrTy};
  2994. FunctionProtoType::ExtProtoInfo EPI;
  2995. EPI.Variadic = true;
  2996. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2997. Sema::CapturedParamNameType Params[] = {
  2998. std::make_pair(".global_tid.", KmpInt32Ty),
  2999. std::make_pair(".part_id.", KmpInt32PtrTy),
  3000. std::make_pair(".privates.", VoidPtrTy),
  3001. std::make_pair(
  3002. ".copy_fn.",
  3003. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3004. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3005. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3006. };
  3007. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3008. Params);
  3009. // Mark this captured region as inlined, because we don't use outlined
  3010. // function directly.
  3011. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3012. AlwaysInlineAttr::CreateImplicit(
  3013. Context, {}, AttributeCommonInfo::AS_Keyword,
  3014. AlwaysInlineAttr::Keyword_forceinline));
  3015. break;
  3016. }
  3017. case OMPD_taskloop:
  3018. case OMPD_taskloop_simd:
  3019. case OMPD_master_taskloop:
  3020. case OMPD_master_taskloop_simd: {
  3021. QualType KmpInt32Ty =
  3022. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  3023. .withConst();
  3024. QualType KmpUInt64Ty =
  3025. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  3026. .withConst();
  3027. QualType KmpInt64Ty =
  3028. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  3029. .withConst();
  3030. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3031. QualType KmpInt32PtrTy =
  3032. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3033. QualType Args[] = {VoidPtrTy};
  3034. FunctionProtoType::ExtProtoInfo EPI;
  3035. EPI.Variadic = true;
  3036. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3037. Sema::CapturedParamNameType Params[] = {
  3038. std::make_pair(".global_tid.", KmpInt32Ty),
  3039. std::make_pair(".part_id.", KmpInt32PtrTy),
  3040. std::make_pair(".privates.", VoidPtrTy),
  3041. std::make_pair(
  3042. ".copy_fn.",
  3043. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3044. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3045. std::make_pair(".lb.", KmpUInt64Ty),
  3046. std::make_pair(".ub.", KmpUInt64Ty),
  3047. std::make_pair(".st.", KmpInt64Ty),
  3048. std::make_pair(".liter.", KmpInt32Ty),
  3049. std::make_pair(".reductions.", VoidPtrTy),
  3050. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3051. };
  3052. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3053. Params);
  3054. // Mark this captured region as inlined, because we don't use outlined
  3055. // function directly.
  3056. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3057. AlwaysInlineAttr::CreateImplicit(
  3058. Context, {}, AttributeCommonInfo::AS_Keyword,
  3059. AlwaysInlineAttr::Keyword_forceinline));
  3060. break;
  3061. }
  3062. case OMPD_parallel_master_taskloop: {
  3063. QualType KmpInt32Ty =
  3064. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  3065. .withConst();
  3066. QualType KmpUInt64Ty =
  3067. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  3068. .withConst();
  3069. QualType KmpInt64Ty =
  3070. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  3071. .withConst();
  3072. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3073. QualType KmpInt32PtrTy =
  3074. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3075. Sema::CapturedParamNameType ParamsParallel[] = {
  3076. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3077. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3078. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3079. };
  3080. // Start a captured region for 'parallel'.
  3081. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3082. ParamsParallel, /*OpenMPCaptureLevel=*/1);
  3083. QualType Args[] = {VoidPtrTy};
  3084. FunctionProtoType::ExtProtoInfo EPI;
  3085. EPI.Variadic = true;
  3086. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3087. Sema::CapturedParamNameType Params[] = {
  3088. std::make_pair(".global_tid.", KmpInt32Ty),
  3089. std::make_pair(".part_id.", KmpInt32PtrTy),
  3090. std::make_pair(".privates.", VoidPtrTy),
  3091. std::make_pair(
  3092. ".copy_fn.",
  3093. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3094. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3095. std::make_pair(".lb.", KmpUInt64Ty),
  3096. std::make_pair(".ub.", KmpUInt64Ty),
  3097. std::make_pair(".st.", KmpInt64Ty),
  3098. std::make_pair(".liter.", KmpInt32Ty),
  3099. std::make_pair(".reductions.", VoidPtrTy),
  3100. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3101. };
  3102. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3103. Params, /*OpenMPCaptureLevel=*/2);
  3104. // Mark this captured region as inlined, because we don't use outlined
  3105. // function directly.
  3106. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3107. AlwaysInlineAttr::CreateImplicit(
  3108. Context, {}, AttributeCommonInfo::AS_Keyword,
  3109. AlwaysInlineAttr::Keyword_forceinline));
  3110. break;
  3111. }
  3112. case OMPD_distribute_parallel_for_simd:
  3113. case OMPD_distribute_parallel_for: {
  3114. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3115. QualType KmpInt32PtrTy =
  3116. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3117. Sema::CapturedParamNameType Params[] = {
  3118. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3119. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3120. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3121. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3122. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3123. };
  3124. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3125. Params);
  3126. break;
  3127. }
  3128. case OMPD_target_teams_distribute_parallel_for:
  3129. case OMPD_target_teams_distribute_parallel_for_simd: {
  3130. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3131. QualType KmpInt32PtrTy =
  3132. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3133. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3134. QualType Args[] = {VoidPtrTy};
  3135. FunctionProtoType::ExtProtoInfo EPI;
  3136. EPI.Variadic = true;
  3137. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3138. Sema::CapturedParamNameType Params[] = {
  3139. std::make_pair(".global_tid.", KmpInt32Ty),
  3140. std::make_pair(".part_id.", KmpInt32PtrTy),
  3141. std::make_pair(".privates.", VoidPtrTy),
  3142. std::make_pair(
  3143. ".copy_fn.",
  3144. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3145. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3146. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3147. };
  3148. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3149. Params, /*OpenMPCaptureLevel=*/0);
  3150. // Mark this captured region as inlined, because we don't use outlined
  3151. // function directly.
  3152. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3153. AlwaysInlineAttr::CreateImplicit(
  3154. Context, {}, AttributeCommonInfo::AS_Keyword,
  3155. AlwaysInlineAttr::Keyword_forceinline));
  3156. Sema::CapturedParamNameType ParamsTarget[] = {
  3157. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3158. };
  3159. // Start a captured region for 'target' with no implicit parameters.
  3160. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3161. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  3162. Sema::CapturedParamNameType ParamsTeams[] = {
  3163. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3164. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3165. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3166. };
  3167. // Start a captured region for 'target' with no implicit parameters.
  3168. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3169. ParamsTeams, /*OpenMPCaptureLevel=*/2);
  3170. Sema::CapturedParamNameType ParamsParallel[] = {
  3171. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3172. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3173. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3174. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3175. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3176. };
  3177. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3178. // the same implicit parameters.
  3179. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3180. ParamsParallel, /*OpenMPCaptureLevel=*/3);
  3181. break;
  3182. }
  3183. case OMPD_teams_distribute_parallel_for:
  3184. case OMPD_teams_distribute_parallel_for_simd: {
  3185. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3186. QualType KmpInt32PtrTy =
  3187. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3188. Sema::CapturedParamNameType ParamsTeams[] = {
  3189. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3190. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3191. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3192. };
  3193. // Start a captured region for 'target' with no implicit parameters.
  3194. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3195. ParamsTeams, /*OpenMPCaptureLevel=*/0);
  3196. Sema::CapturedParamNameType ParamsParallel[] = {
  3197. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3198. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3199. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3200. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3201. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3202. };
  3203. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3204. // the same implicit parameters.
  3205. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3206. ParamsParallel, /*OpenMPCaptureLevel=*/1);
  3207. break;
  3208. }
  3209. case OMPD_target_update:
  3210. case OMPD_target_enter_data:
  3211. case OMPD_target_exit_data: {
  3212. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3213. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3214. QualType KmpInt32PtrTy =
  3215. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3216. QualType Args[] = {VoidPtrTy};
  3217. FunctionProtoType::ExtProtoInfo EPI;
  3218. EPI.Variadic = true;
  3219. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3220. Sema::CapturedParamNameType Params[] = {
  3221. std::make_pair(".global_tid.", KmpInt32Ty),
  3222. std::make_pair(".part_id.", KmpInt32PtrTy),
  3223. std::make_pair(".privates.", VoidPtrTy),
  3224. std::make_pair(
  3225. ".copy_fn.",
  3226. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3227. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3228. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3229. };
  3230. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3231. Params);
  3232. // Mark this captured region as inlined, because we don't use outlined
  3233. // function directly.
  3234. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3235. AlwaysInlineAttr::CreateImplicit(
  3236. Context, {}, AttributeCommonInfo::AS_Keyword,
  3237. AlwaysInlineAttr::Keyword_forceinline));
  3238. break;
  3239. }
  3240. case OMPD_threadprivate:
  3241. case OMPD_allocate:
  3242. case OMPD_taskyield:
  3243. case OMPD_barrier:
  3244. case OMPD_taskwait:
  3245. case OMPD_cancellation_point:
  3246. case OMPD_cancel:
  3247. case OMPD_flush:
  3248. case OMPD_declare_reduction:
  3249. case OMPD_declare_mapper:
  3250. case OMPD_declare_simd:
  3251. case OMPD_declare_target:
  3252. case OMPD_end_declare_target:
  3253. case OMPD_requires:
  3254. case OMPD_declare_variant:
  3255. llvm_unreachable("OpenMP Directive is not allowed");
  3256. case OMPD_unknown:
  3257. llvm_unreachable("Unknown OpenMP directive");
  3258. }
  3259. }
  3260. int Sema::getNumberOfConstructScopes(unsigned Level) const {
  3261. return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
  3262. }
  3263. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  3264. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3265. getOpenMPCaptureRegions(CaptureRegions, DKind);
  3266. return CaptureRegions.size();
  3267. }
  3268. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  3269. Expr *CaptureExpr, bool WithInit,
  3270. bool AsExpression) {
  3271. assert(CaptureExpr);
  3272. ASTContext &C = S.getASTContext();
  3273. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  3274. QualType Ty = Init->getType();
  3275. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  3276. if (S.getLangOpts().CPlusPlus) {
  3277. Ty = C.getLValueReferenceType(Ty);
  3278. } else {
  3279. Ty = C.getPointerType(Ty);
  3280. ExprResult Res =
  3281. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  3282. if (!Res.isUsable())
  3283. return nullptr;
  3284. Init = Res.get();
  3285. }
  3286. WithInit = true;
  3287. }
  3288. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  3289. CaptureExpr->getBeginLoc());
  3290. if (!WithInit)
  3291. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  3292. S.CurContext->addHiddenDecl(CED);
  3293. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  3294. return CED;
  3295. }
  3296. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  3297. bool WithInit) {
  3298. OMPCapturedExprDecl *CD;
  3299. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  3300. CD = cast<OMPCapturedExprDecl>(VD);
  3301. else
  3302. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  3303. /*AsExpression=*/false);
  3304. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3305. CaptureExpr->getExprLoc());
  3306. }
  3307. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  3308. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  3309. if (!Ref) {
  3310. OMPCapturedExprDecl *CD = buildCaptureDecl(
  3311. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  3312. /*WithInit=*/true, /*AsExpression=*/true);
  3313. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3314. CaptureExpr->getExprLoc());
  3315. }
  3316. ExprResult Res = Ref;
  3317. if (!S.getLangOpts().CPlusPlus &&
  3318. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  3319. Ref->getType()->isPointerType()) {
  3320. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  3321. if (!Res.isUsable())
  3322. return ExprError();
  3323. }
  3324. return S.DefaultLvalueConversion(Res.get());
  3325. }
  3326. namespace {
  3327. // OpenMP directives parsed in this section are represented as a
  3328. // CapturedStatement with an associated statement. If a syntax error
  3329. // is detected during the parsing of the associated statement, the
  3330. // compiler must abort processing and close the CapturedStatement.
  3331. //
  3332. // Combined directives such as 'target parallel' have more than one
  3333. // nested CapturedStatements. This RAII ensures that we unwind out
  3334. // of all the nested CapturedStatements when an error is found.
  3335. class CaptureRegionUnwinderRAII {
  3336. private:
  3337. Sema &S;
  3338. bool &ErrorFound;
  3339. OpenMPDirectiveKind DKind = OMPD_unknown;
  3340. public:
  3341. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  3342. OpenMPDirectiveKind DKind)
  3343. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  3344. ~CaptureRegionUnwinderRAII() {
  3345. if (ErrorFound) {
  3346. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  3347. while (--ThisCaptureLevel >= 0)
  3348. S.ActOnCapturedRegionError();
  3349. }
  3350. }
  3351. };
  3352. } // namespace
  3353. void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
  3354. // Capture variables captured by reference in lambdas for target-based
  3355. // directives.
  3356. if (!CurContext->isDependentContext() &&
  3357. (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
  3358. isOpenMPTargetDataManagementDirective(
  3359. DSAStack->getCurrentDirective()))) {
  3360. QualType Type = V->getType();
  3361. if (const auto *RD = Type.getCanonicalType()
  3362. .getNonReferenceType()
  3363. ->getAsCXXRecordDecl()) {
  3364. bool SavedForceCaptureByReferenceInTargetExecutable =
  3365. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  3366. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3367. /*V=*/true);
  3368. if (RD->isLambda()) {
  3369. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  3370. FieldDecl *ThisCapture;
  3371. RD->getCaptureFields(Captures, ThisCapture);
  3372. for (const LambdaCapture &LC : RD->captures()) {
  3373. if (LC.getCaptureKind() == LCK_ByRef) {
  3374. VarDecl *VD = LC.getCapturedVar();
  3375. DeclContext *VDC = VD->getDeclContext();
  3376. if (!VDC->Encloses(CurContext))
  3377. continue;
  3378. MarkVariableReferenced(LC.getLocation(), VD);
  3379. } else if (LC.getCaptureKind() == LCK_This) {
  3380. QualType ThisTy = getCurrentThisType();
  3381. if (!ThisTy.isNull() &&
  3382. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  3383. CheckCXXThisCapture(LC.getLocation());
  3384. }
  3385. }
  3386. }
  3387. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3388. SavedForceCaptureByReferenceInTargetExecutable);
  3389. }
  3390. }
  3391. }
  3392. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  3393. ArrayRef<OMPClause *> Clauses) {
  3394. bool ErrorFound = false;
  3395. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  3396. *this, ErrorFound, DSAStack->getCurrentDirective());
  3397. if (!S.isUsable()) {
  3398. ErrorFound = true;
  3399. return StmtError();
  3400. }
  3401. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3402. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  3403. OMPOrderedClause *OC = nullptr;
  3404. OMPScheduleClause *SC = nullptr;
  3405. SmallVector<const OMPLinearClause *, 4> LCs;
  3406. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  3407. // This is required for proper codegen.
  3408. for (OMPClause *Clause : Clauses) {
  3409. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  3410. Clause->getClauseKind() == OMPC_in_reduction) {
  3411. // Capture taskgroup task_reduction descriptors inside the tasking regions
  3412. // with the corresponding in_reduction items.
  3413. auto *IRC = cast<OMPInReductionClause>(Clause);
  3414. for (Expr *E : IRC->taskgroup_descriptors())
  3415. if (E)
  3416. MarkDeclarationsReferencedInExpr(E);
  3417. }
  3418. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  3419. Clause->getClauseKind() == OMPC_copyprivate ||
  3420. (getLangOpts().OpenMPUseTLS &&
  3421. getASTContext().getTargetInfo().isTLSSupported() &&
  3422. Clause->getClauseKind() == OMPC_copyin)) {
  3423. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  3424. // Mark all variables in private list clauses as used in inner region.
  3425. for (Stmt *VarRef : Clause->children()) {
  3426. if (auto *E = cast_or_null<Expr>(VarRef)) {
  3427. MarkDeclarationsReferencedInExpr(E);
  3428. }
  3429. }
  3430. DSAStack->setForceVarCapturing(/*V=*/false);
  3431. } else if (CaptureRegions.size() > 1 ||
  3432. CaptureRegions.back() != OMPD_unknown) {
  3433. if (auto *C = OMPClauseWithPreInit::get(Clause))
  3434. PICs.push_back(C);
  3435. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  3436. if (Expr *E = C->getPostUpdateExpr())
  3437. MarkDeclarationsReferencedInExpr(E);
  3438. }
  3439. }
  3440. if (Clause->getClauseKind() == OMPC_schedule)
  3441. SC = cast<OMPScheduleClause>(Clause);
  3442. else if (Clause->getClauseKind() == OMPC_ordered)
  3443. OC = cast<OMPOrderedClause>(Clause);
  3444. else if (Clause->getClauseKind() == OMPC_linear)
  3445. LCs.push_back(cast<OMPLinearClause>(Clause));
  3446. }
  3447. // OpenMP, 2.7.1 Loop Construct, Restrictions
  3448. // The nonmonotonic modifier cannot be specified if an ordered clause is
  3449. // specified.
  3450. if (SC &&
  3451. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  3452. SC->getSecondScheduleModifier() ==
  3453. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  3454. OC) {
  3455. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  3456. ? SC->getFirstScheduleModifierLoc()
  3457. : SC->getSecondScheduleModifierLoc(),
  3458. diag::err_omp_schedule_nonmonotonic_ordered)
  3459. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3460. ErrorFound = true;
  3461. }
  3462. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  3463. for (const OMPLinearClause *C : LCs) {
  3464. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  3465. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3466. }
  3467. ErrorFound = true;
  3468. }
  3469. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  3470. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  3471. OC->getNumForLoops()) {
  3472. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  3473. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  3474. ErrorFound = true;
  3475. }
  3476. if (ErrorFound) {
  3477. return StmtError();
  3478. }
  3479. StmtResult SR = S;
  3480. unsigned CompletedRegions = 0;
  3481. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  3482. // Mark all variables in private list clauses as used in inner region.
  3483. // Required for proper codegen of combined directives.
  3484. // TODO: add processing for other clauses.
  3485. if (ThisCaptureRegion != OMPD_unknown) {
  3486. for (const clang::OMPClauseWithPreInit *C : PICs) {
  3487. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  3488. // Find the particular capture region for the clause if the
  3489. // directive is a combined one with multiple capture regions.
  3490. // If the directive is not a combined one, the capture region
  3491. // associated with the clause is OMPD_unknown and is generated
  3492. // only once.
  3493. if (CaptureRegion == ThisCaptureRegion ||
  3494. CaptureRegion == OMPD_unknown) {
  3495. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  3496. for (Decl *D : DS->decls())
  3497. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  3498. }
  3499. }
  3500. }
  3501. }
  3502. if (++CompletedRegions == CaptureRegions.size())
  3503. DSAStack->setBodyComplete();
  3504. SR = ActOnCapturedRegionEnd(SR.get());
  3505. }
  3506. return SR;
  3507. }
  3508. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  3509. OpenMPDirectiveKind CancelRegion,
  3510. SourceLocation StartLoc) {
  3511. // CancelRegion is only needed for cancel and cancellation_point.
  3512. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  3513. return false;
  3514. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  3515. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  3516. return false;
  3517. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  3518. << getOpenMPDirectiveName(CancelRegion);
  3519. return true;
  3520. }
  3521. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  3522. OpenMPDirectiveKind CurrentRegion,
  3523. const DeclarationNameInfo &CurrentName,
  3524. OpenMPDirectiveKind CancelRegion,
  3525. SourceLocation StartLoc) {
  3526. if (Stack->getCurScope()) {
  3527. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  3528. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  3529. bool NestingProhibited = false;
  3530. bool CloseNesting = true;
  3531. bool OrphanSeen = false;
  3532. enum {
  3533. NoRecommend,
  3534. ShouldBeInParallelRegion,
  3535. ShouldBeInOrderedRegion,
  3536. ShouldBeInTargetRegion,
  3537. ShouldBeInTeamsRegion
  3538. } Recommend = NoRecommend;
  3539. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  3540. // OpenMP [2.16, Nesting of Regions]
  3541. // OpenMP constructs may not be nested inside a simd region.
  3542. // OpenMP [2.8.1,simd Construct, Restrictions]
  3543. // An ordered construct with the simd clause is the only OpenMP
  3544. // construct that can appear in the simd region.
  3545. // Allowing a SIMD construct nested in another SIMD construct is an
  3546. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  3547. // message.
  3548. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  3549. ? diag::err_omp_prohibited_region_simd
  3550. : diag::warn_omp_nesting_simd);
  3551. return CurrentRegion != OMPD_simd;
  3552. }
  3553. if (ParentRegion == OMPD_atomic) {
  3554. // OpenMP [2.16, Nesting of Regions]
  3555. // OpenMP constructs may not be nested inside an atomic region.
  3556. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  3557. return true;
  3558. }
  3559. if (CurrentRegion == OMPD_section) {
  3560. // OpenMP [2.7.2, sections Construct, Restrictions]
  3561. // Orphaned section directives are prohibited. That is, the section
  3562. // directives must appear within the sections construct and must not be
  3563. // encountered elsewhere in the sections region.
  3564. if (ParentRegion != OMPD_sections &&
  3565. ParentRegion != OMPD_parallel_sections) {
  3566. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  3567. << (ParentRegion != OMPD_unknown)
  3568. << getOpenMPDirectiveName(ParentRegion);
  3569. return true;
  3570. }
  3571. return false;
  3572. }
  3573. // Allow some constructs (except teams and cancellation constructs) to be
  3574. // orphaned (they could be used in functions, called from OpenMP regions
  3575. // with the required preconditions).
  3576. if (ParentRegion == OMPD_unknown &&
  3577. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  3578. CurrentRegion != OMPD_cancellation_point &&
  3579. CurrentRegion != OMPD_cancel)
  3580. return false;
  3581. if (CurrentRegion == OMPD_cancellation_point ||
  3582. CurrentRegion == OMPD_cancel) {
  3583. // OpenMP [2.16, Nesting of Regions]
  3584. // A cancellation point construct for which construct-type-clause is
  3585. // taskgroup must be nested inside a task construct. A cancellation
  3586. // point construct for which construct-type-clause is not taskgroup must
  3587. // be closely nested inside an OpenMP construct that matches the type
  3588. // specified in construct-type-clause.
  3589. // A cancel construct for which construct-type-clause is taskgroup must be
  3590. // nested inside a task construct. A cancel construct for which
  3591. // construct-type-clause is not taskgroup must be closely nested inside an
  3592. // OpenMP construct that matches the type specified in
  3593. // construct-type-clause.
  3594. NestingProhibited =
  3595. !((CancelRegion == OMPD_parallel &&
  3596. (ParentRegion == OMPD_parallel ||
  3597. ParentRegion == OMPD_target_parallel)) ||
  3598. (CancelRegion == OMPD_for &&
  3599. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  3600. ParentRegion == OMPD_target_parallel_for ||
  3601. ParentRegion == OMPD_distribute_parallel_for ||
  3602. ParentRegion == OMPD_teams_distribute_parallel_for ||
  3603. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  3604. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  3605. (CancelRegion == OMPD_sections &&
  3606. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  3607. ParentRegion == OMPD_parallel_sections)));
  3608. OrphanSeen = ParentRegion == OMPD_unknown;
  3609. } else if (CurrentRegion == OMPD_master) {
  3610. // OpenMP [2.16, Nesting of Regions]
  3611. // A master region may not be closely nested inside a worksharing,
  3612. // atomic, or explicit task region.
  3613. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3614. isOpenMPTaskingDirective(ParentRegion);
  3615. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  3616. // OpenMP [2.16, Nesting of Regions]
  3617. // A critical region may not be nested (closely or otherwise) inside a
  3618. // critical region with the same name. Note that this restriction is not
  3619. // sufficient to prevent deadlock.
  3620. SourceLocation PreviousCriticalLoc;
  3621. bool DeadLock = Stack->hasDirective(
  3622. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  3623. const DeclarationNameInfo &DNI,
  3624. SourceLocation Loc) {
  3625. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  3626. PreviousCriticalLoc = Loc;
  3627. return true;
  3628. }
  3629. return false;
  3630. },
  3631. false /* skip top directive */);
  3632. if (DeadLock) {
  3633. SemaRef.Diag(StartLoc,
  3634. diag::err_omp_prohibited_region_critical_same_name)
  3635. << CurrentName.getName();
  3636. if (PreviousCriticalLoc.isValid())
  3637. SemaRef.Diag(PreviousCriticalLoc,
  3638. diag::note_omp_previous_critical_region);
  3639. return true;
  3640. }
  3641. } else if (CurrentRegion == OMPD_barrier) {
  3642. // OpenMP [2.16, Nesting of Regions]
  3643. // A barrier region may not be closely nested inside a worksharing,
  3644. // explicit task, critical, ordered, atomic, or master region.
  3645. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3646. isOpenMPTaskingDirective(ParentRegion) ||
  3647. ParentRegion == OMPD_master ||
  3648. ParentRegion == OMPD_critical ||
  3649. ParentRegion == OMPD_ordered;
  3650. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3651. !isOpenMPParallelDirective(CurrentRegion) &&
  3652. !isOpenMPTeamsDirective(CurrentRegion)) {
  3653. // OpenMP [2.16, Nesting of Regions]
  3654. // A worksharing region may not be closely nested inside a worksharing,
  3655. // explicit task, critical, ordered, atomic, or master region.
  3656. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3657. isOpenMPTaskingDirective(ParentRegion) ||
  3658. ParentRegion == OMPD_master ||
  3659. ParentRegion == OMPD_critical ||
  3660. ParentRegion == OMPD_ordered;
  3661. Recommend = ShouldBeInParallelRegion;
  3662. } else if (CurrentRegion == OMPD_ordered) {
  3663. // OpenMP [2.16, Nesting of Regions]
  3664. // An ordered region may not be closely nested inside a critical,
  3665. // atomic, or explicit task region.
  3666. // An ordered region must be closely nested inside a loop region (or
  3667. // parallel loop region) with an ordered clause.
  3668. // OpenMP [2.8.1,simd Construct, Restrictions]
  3669. // An ordered construct with the simd clause is the only OpenMP construct
  3670. // that can appear in the simd region.
  3671. NestingProhibited = ParentRegion == OMPD_critical ||
  3672. isOpenMPTaskingDirective(ParentRegion) ||
  3673. !(isOpenMPSimdDirective(ParentRegion) ||
  3674. Stack->isParentOrderedRegion());
  3675. Recommend = ShouldBeInOrderedRegion;
  3676. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3677. // OpenMP [2.16, Nesting of Regions]
  3678. // If specified, a teams construct must be contained within a target
  3679. // construct.
  3680. NestingProhibited =
  3681. (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
  3682. (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
  3683. ParentRegion != OMPD_target);
  3684. OrphanSeen = ParentRegion == OMPD_unknown;
  3685. Recommend = ShouldBeInTargetRegion;
  3686. }
  3687. if (!NestingProhibited &&
  3688. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3689. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3690. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3691. // OpenMP [2.16, Nesting of Regions]
  3692. // distribute, parallel, parallel sections, parallel workshare, and the
  3693. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3694. // constructs that can be closely nested in the teams region.
  3695. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3696. !isOpenMPDistributeDirective(CurrentRegion);
  3697. Recommend = ShouldBeInParallelRegion;
  3698. }
  3699. if (!NestingProhibited &&
  3700. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3701. // OpenMP 4.5 [2.17 Nesting of Regions]
  3702. // The region associated with the distribute construct must be strictly
  3703. // nested inside a teams region
  3704. NestingProhibited =
  3705. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3706. Recommend = ShouldBeInTeamsRegion;
  3707. }
  3708. if (!NestingProhibited &&
  3709. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3710. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3711. // OpenMP 4.5 [2.17 Nesting of Regions]
  3712. // If a target, target update, target data, target enter data, or
  3713. // target exit data construct is encountered during execution of a
  3714. // target region, the behavior is unspecified.
  3715. NestingProhibited = Stack->hasDirective(
  3716. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3717. SourceLocation) {
  3718. if (isOpenMPTargetExecutionDirective(K)) {
  3719. OffendingRegion = K;
  3720. return true;
  3721. }
  3722. return false;
  3723. },
  3724. false /* don't skip top directive */);
  3725. CloseNesting = false;
  3726. }
  3727. if (NestingProhibited) {
  3728. if (OrphanSeen) {
  3729. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3730. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3731. } else {
  3732. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3733. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3734. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3735. }
  3736. return true;
  3737. }
  3738. }
  3739. return false;
  3740. }
  3741. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3742. ArrayRef<OMPClause *> Clauses,
  3743. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3744. bool ErrorFound = false;
  3745. unsigned NamedModifiersNumber = 0;
  3746. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3747. OMPD_unknown + 1);
  3748. SmallVector<SourceLocation, 4> NameModifierLoc;
  3749. for (const OMPClause *C : Clauses) {
  3750. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3751. // At most one if clause without a directive-name-modifier can appear on
  3752. // the directive.
  3753. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3754. if (FoundNameModifiers[CurNM]) {
  3755. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3756. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3757. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3758. ErrorFound = true;
  3759. } else if (CurNM != OMPD_unknown) {
  3760. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3761. ++NamedModifiersNumber;
  3762. }
  3763. FoundNameModifiers[CurNM] = IC;
  3764. if (CurNM == OMPD_unknown)
  3765. continue;
  3766. // Check if the specified name modifier is allowed for the current
  3767. // directive.
  3768. // At most one if clause with the particular directive-name-modifier can
  3769. // appear on the directive.
  3770. bool MatchFound = false;
  3771. for (auto NM : AllowedNameModifiers) {
  3772. if (CurNM == NM) {
  3773. MatchFound = true;
  3774. break;
  3775. }
  3776. }
  3777. if (!MatchFound) {
  3778. S.Diag(IC->getNameModifierLoc(),
  3779. diag::err_omp_wrong_if_directive_name_modifier)
  3780. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3781. ErrorFound = true;
  3782. }
  3783. }
  3784. }
  3785. // If any if clause on the directive includes a directive-name-modifier then
  3786. // all if clauses on the directive must include a directive-name-modifier.
  3787. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3788. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3789. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3790. diag::err_omp_no_more_if_clause);
  3791. } else {
  3792. std::string Values;
  3793. std::string Sep(", ");
  3794. unsigned AllowedCnt = 0;
  3795. unsigned TotalAllowedNum =
  3796. AllowedNameModifiers.size() - NamedModifiersNumber;
  3797. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3798. ++Cnt) {
  3799. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3800. if (!FoundNameModifiers[NM]) {
  3801. Values += "'";
  3802. Values += getOpenMPDirectiveName(NM);
  3803. Values += "'";
  3804. if (AllowedCnt + 2 == TotalAllowedNum)
  3805. Values += " or ";
  3806. else if (AllowedCnt + 1 != TotalAllowedNum)
  3807. Values += Sep;
  3808. ++AllowedCnt;
  3809. }
  3810. }
  3811. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3812. diag::err_omp_unnamed_if_clause)
  3813. << (TotalAllowedNum > 1) << Values;
  3814. }
  3815. for (SourceLocation Loc : NameModifierLoc) {
  3816. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3817. }
  3818. ErrorFound = true;
  3819. }
  3820. return ErrorFound;
  3821. }
  3822. static std::pair<ValueDecl *, bool>
  3823. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  3824. SourceRange &ERange, bool AllowArraySection = false) {
  3825. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  3826. RefExpr->containsUnexpandedParameterPack())
  3827. return std::make_pair(nullptr, true);
  3828. // OpenMP [3.1, C/C++]
  3829. // A list item is a variable name.
  3830. // OpenMP [2.9.3.3, Restrictions, p.1]
  3831. // A variable that is part of another variable (as an array or
  3832. // structure element) cannot appear in a private clause.
  3833. RefExpr = RefExpr->IgnoreParens();
  3834. enum {
  3835. NoArrayExpr = -1,
  3836. ArraySubscript = 0,
  3837. OMPArraySection = 1
  3838. } IsArrayExpr = NoArrayExpr;
  3839. if (AllowArraySection) {
  3840. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  3841. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  3842. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3843. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3844. RefExpr = Base;
  3845. IsArrayExpr = ArraySubscript;
  3846. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  3847. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  3848. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  3849. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  3850. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3851. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3852. RefExpr = Base;
  3853. IsArrayExpr = OMPArraySection;
  3854. }
  3855. }
  3856. ELoc = RefExpr->getExprLoc();
  3857. ERange = RefExpr->getSourceRange();
  3858. RefExpr = RefExpr->IgnoreParenImpCasts();
  3859. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3860. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  3861. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  3862. (S.getCurrentThisType().isNull() || !ME ||
  3863. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  3864. !isa<FieldDecl>(ME->getMemberDecl()))) {
  3865. if (IsArrayExpr != NoArrayExpr) {
  3866. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  3867. << ERange;
  3868. } else {
  3869. S.Diag(ELoc,
  3870. AllowArraySection
  3871. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  3872. : diag::err_omp_expected_var_name_member_expr)
  3873. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  3874. }
  3875. return std::make_pair(nullptr, false);
  3876. }
  3877. return std::make_pair(
  3878. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  3879. }
  3880. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  3881. ArrayRef<OMPClause *> Clauses) {
  3882. assert(!S.CurContext->isDependentContext() &&
  3883. "Expected non-dependent context.");
  3884. auto AllocateRange =
  3885. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  3886. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
  3887. DeclToCopy;
  3888. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  3889. return isOpenMPPrivate(C->getClauseKind());
  3890. });
  3891. for (OMPClause *Cl : PrivateRange) {
  3892. MutableArrayRef<Expr *>::iterator I, It, Et;
  3893. if (Cl->getClauseKind() == OMPC_private) {
  3894. auto *PC = cast<OMPPrivateClause>(Cl);
  3895. I = PC->private_copies().begin();
  3896. It = PC->varlist_begin();
  3897. Et = PC->varlist_end();
  3898. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  3899. auto *PC = cast<OMPFirstprivateClause>(Cl);
  3900. I = PC->private_copies().begin();
  3901. It = PC->varlist_begin();
  3902. Et = PC->varlist_end();
  3903. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  3904. auto *PC = cast<OMPLastprivateClause>(Cl);
  3905. I = PC->private_copies().begin();
  3906. It = PC->varlist_begin();
  3907. Et = PC->varlist_end();
  3908. } else if (Cl->getClauseKind() == OMPC_linear) {
  3909. auto *PC = cast<OMPLinearClause>(Cl);
  3910. I = PC->privates().begin();
  3911. It = PC->varlist_begin();
  3912. Et = PC->varlist_end();
  3913. } else if (Cl->getClauseKind() == OMPC_reduction) {
  3914. auto *PC = cast<OMPReductionClause>(Cl);
  3915. I = PC->privates().begin();
  3916. It = PC->varlist_begin();
  3917. Et = PC->varlist_end();
  3918. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  3919. auto *PC = cast<OMPTaskReductionClause>(Cl);
  3920. I = PC->privates().begin();
  3921. It = PC->varlist_begin();
  3922. Et = PC->varlist_end();
  3923. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  3924. auto *PC = cast<OMPInReductionClause>(Cl);
  3925. I = PC->privates().begin();
  3926. It = PC->varlist_begin();
  3927. Et = PC->varlist_end();
  3928. } else {
  3929. llvm_unreachable("Expected private clause.");
  3930. }
  3931. for (Expr *E : llvm::make_range(It, Et)) {
  3932. if (!*I) {
  3933. ++I;
  3934. continue;
  3935. }
  3936. SourceLocation ELoc;
  3937. SourceRange ERange;
  3938. Expr *SimpleRefExpr = E;
  3939. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  3940. /*AllowArraySection=*/true);
  3941. DeclToCopy.try_emplace(Res.first,
  3942. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  3943. ++I;
  3944. }
  3945. }
  3946. for (OMPClause *C : AllocateRange) {
  3947. auto *AC = cast<OMPAllocateClause>(C);
  3948. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  3949. getAllocatorKind(S, Stack, AC->getAllocator());
  3950. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  3951. // For task, taskloop or target directives, allocation requests to memory
  3952. // allocators with the trait access set to thread result in unspecified
  3953. // behavior.
  3954. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  3955. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  3956. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  3957. S.Diag(AC->getAllocator()->getExprLoc(),
  3958. diag::warn_omp_allocate_thread_on_task_target_directive)
  3959. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3960. }
  3961. for (Expr *E : AC->varlists()) {
  3962. SourceLocation ELoc;
  3963. SourceRange ERange;
  3964. Expr *SimpleRefExpr = E;
  3965. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  3966. ValueDecl *VD = Res.first;
  3967. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  3968. if (!isOpenMPPrivate(Data.CKind)) {
  3969. S.Diag(E->getExprLoc(),
  3970. diag::err_omp_expected_private_copy_for_allocate);
  3971. continue;
  3972. }
  3973. VarDecl *PrivateVD = DeclToCopy[VD];
  3974. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  3975. AllocatorKind, AC->getAllocator()))
  3976. continue;
  3977. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  3978. E->getSourceRange());
  3979. }
  3980. }
  3981. }
  3982. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3983. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3984. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3985. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3986. StmtResult Res = StmtError();
  3987. // First check CancelRegion which is then used in checkNestingOfRegions.
  3988. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3989. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3990. StartLoc))
  3991. return StmtError();
  3992. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3993. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3994. bool ErrorFound = false;
  3995. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3996. if (AStmt && !CurContext->isDependentContext()) {
  3997. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3998. // Check default data sharing attributes for referenced variables.
  3999. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  4000. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  4001. Stmt *S = AStmt;
  4002. while (--ThisCaptureLevel >= 0)
  4003. S = cast<CapturedStmt>(S)->getCapturedStmt();
  4004. DSAChecker.Visit(S);
  4005. if (!isOpenMPTargetDataManagementDirective(Kind) &&
  4006. !isOpenMPTaskingDirective(Kind)) {
  4007. // Visit subcaptures to generate implicit clauses for captured vars.
  4008. auto *CS = cast<CapturedStmt>(AStmt);
  4009. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  4010. getOpenMPCaptureRegions(CaptureRegions, Kind);
  4011. // Ignore outer tasking regions for target directives.
  4012. if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
  4013. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  4014. DSAChecker.visitSubCaptures(CS);
  4015. }
  4016. if (DSAChecker.isErrorFound())
  4017. return StmtError();
  4018. // Generate list of implicitly defined firstprivate variables.
  4019. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  4020. SmallVector<Expr *, 4> ImplicitFirstprivates(
  4021. DSAChecker.getImplicitFirstprivate().begin(),
  4022. DSAChecker.getImplicitFirstprivate().end());
  4023. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  4024. DSAChecker.getImplicitMap().end());
  4025. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  4026. for (OMPClause *C : Clauses) {
  4027. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  4028. for (Expr *E : IRC->taskgroup_descriptors())
  4029. if (E)
  4030. ImplicitFirstprivates.emplace_back(E);
  4031. }
  4032. }
  4033. if (!ImplicitFirstprivates.empty()) {
  4034. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  4035. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  4036. SourceLocation())) {
  4037. ClausesWithImplicit.push_back(Implicit);
  4038. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  4039. ImplicitFirstprivates.size();
  4040. } else {
  4041. ErrorFound = true;
  4042. }
  4043. }
  4044. if (!ImplicitMaps.empty()) {
  4045. CXXScopeSpec MapperIdScopeSpec;
  4046. DeclarationNameInfo MapperId;
  4047. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  4048. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  4049. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  4050. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  4051. ClausesWithImplicit.emplace_back(Implicit);
  4052. ErrorFound |=
  4053. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  4054. } else {
  4055. ErrorFound = true;
  4056. }
  4057. }
  4058. }
  4059. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  4060. switch (Kind) {
  4061. case OMPD_parallel:
  4062. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  4063. EndLoc);
  4064. AllowedNameModifiers.push_back(OMPD_parallel);
  4065. break;
  4066. case OMPD_simd:
  4067. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4068. VarsWithInheritedDSA);
  4069. break;
  4070. case OMPD_for:
  4071. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4072. VarsWithInheritedDSA);
  4073. break;
  4074. case OMPD_for_simd:
  4075. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4076. EndLoc, VarsWithInheritedDSA);
  4077. break;
  4078. case OMPD_sections:
  4079. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4080. EndLoc);
  4081. break;
  4082. case OMPD_section:
  4083. assert(ClausesWithImplicit.empty() &&
  4084. "No clauses are allowed for 'omp section' directive");
  4085. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  4086. break;
  4087. case OMPD_single:
  4088. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  4089. EndLoc);
  4090. break;
  4091. case OMPD_master:
  4092. assert(ClausesWithImplicit.empty() &&
  4093. "No clauses are allowed for 'omp master' directive");
  4094. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  4095. break;
  4096. case OMPD_critical:
  4097. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  4098. StartLoc, EndLoc);
  4099. break;
  4100. case OMPD_parallel_for:
  4101. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  4102. EndLoc, VarsWithInheritedDSA);
  4103. AllowedNameModifiers.push_back(OMPD_parallel);
  4104. break;
  4105. case OMPD_parallel_for_simd:
  4106. Res = ActOnOpenMPParallelForSimdDirective(
  4107. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4108. AllowedNameModifiers.push_back(OMPD_parallel);
  4109. break;
  4110. case OMPD_parallel_sections:
  4111. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  4112. StartLoc, EndLoc);
  4113. AllowedNameModifiers.push_back(OMPD_parallel);
  4114. break;
  4115. case OMPD_task:
  4116. Res =
  4117. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4118. AllowedNameModifiers.push_back(OMPD_task);
  4119. break;
  4120. case OMPD_taskyield:
  4121. assert(ClausesWithImplicit.empty() &&
  4122. "No clauses are allowed for 'omp taskyield' directive");
  4123. assert(AStmt == nullptr &&
  4124. "No associated statement allowed for 'omp taskyield' directive");
  4125. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  4126. break;
  4127. case OMPD_barrier:
  4128. assert(ClausesWithImplicit.empty() &&
  4129. "No clauses are allowed for 'omp barrier' directive");
  4130. assert(AStmt == nullptr &&
  4131. "No associated statement allowed for 'omp barrier' directive");
  4132. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  4133. break;
  4134. case OMPD_taskwait:
  4135. assert(ClausesWithImplicit.empty() &&
  4136. "No clauses are allowed for 'omp taskwait' directive");
  4137. assert(AStmt == nullptr &&
  4138. "No associated statement allowed for 'omp taskwait' directive");
  4139. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  4140. break;
  4141. case OMPD_taskgroup:
  4142. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  4143. EndLoc);
  4144. break;
  4145. case OMPD_flush:
  4146. assert(AStmt == nullptr &&
  4147. "No associated statement allowed for 'omp flush' directive");
  4148. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  4149. break;
  4150. case OMPD_ordered:
  4151. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  4152. EndLoc);
  4153. break;
  4154. case OMPD_atomic:
  4155. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  4156. EndLoc);
  4157. break;
  4158. case OMPD_teams:
  4159. Res =
  4160. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4161. break;
  4162. case OMPD_target:
  4163. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  4164. EndLoc);
  4165. AllowedNameModifiers.push_back(OMPD_target);
  4166. break;
  4167. case OMPD_target_parallel:
  4168. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  4169. StartLoc, EndLoc);
  4170. AllowedNameModifiers.push_back(OMPD_target);
  4171. AllowedNameModifiers.push_back(OMPD_parallel);
  4172. break;
  4173. case OMPD_target_parallel_for:
  4174. Res = ActOnOpenMPTargetParallelForDirective(
  4175. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4176. AllowedNameModifiers.push_back(OMPD_target);
  4177. AllowedNameModifiers.push_back(OMPD_parallel);
  4178. break;
  4179. case OMPD_cancellation_point:
  4180. assert(ClausesWithImplicit.empty() &&
  4181. "No clauses are allowed for 'omp cancellation point' directive");
  4182. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  4183. "cancellation point' directive");
  4184. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  4185. break;
  4186. case OMPD_cancel:
  4187. assert(AStmt == nullptr &&
  4188. "No associated statement allowed for 'omp cancel' directive");
  4189. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  4190. CancelRegion);
  4191. AllowedNameModifiers.push_back(OMPD_cancel);
  4192. break;
  4193. case OMPD_target_data:
  4194. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  4195. EndLoc);
  4196. AllowedNameModifiers.push_back(OMPD_target_data);
  4197. break;
  4198. case OMPD_target_enter_data:
  4199. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  4200. EndLoc, AStmt);
  4201. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  4202. break;
  4203. case OMPD_target_exit_data:
  4204. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  4205. EndLoc, AStmt);
  4206. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  4207. break;
  4208. case OMPD_taskloop:
  4209. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  4210. EndLoc, VarsWithInheritedDSA);
  4211. AllowedNameModifiers.push_back(OMPD_taskloop);
  4212. break;
  4213. case OMPD_taskloop_simd:
  4214. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4215. EndLoc, VarsWithInheritedDSA);
  4216. AllowedNameModifiers.push_back(OMPD_taskloop);
  4217. break;
  4218. case OMPD_master_taskloop:
  4219. Res = ActOnOpenMPMasterTaskLoopDirective(
  4220. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4221. AllowedNameModifiers.push_back(OMPD_taskloop);
  4222. break;
  4223. case OMPD_master_taskloop_simd:
  4224. Res = ActOnOpenMPMasterTaskLoopSimdDirective(
  4225. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4226. AllowedNameModifiers.push_back(OMPD_taskloop);
  4227. break;
  4228. case OMPD_parallel_master_taskloop:
  4229. Res = ActOnOpenMPParallelMasterTaskLoopDirective(
  4230. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4231. AllowedNameModifiers.push_back(OMPD_taskloop);
  4232. AllowedNameModifiers.push_back(OMPD_parallel);
  4233. break;
  4234. case OMPD_distribute:
  4235. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  4236. EndLoc, VarsWithInheritedDSA);
  4237. break;
  4238. case OMPD_target_update:
  4239. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  4240. EndLoc, AStmt);
  4241. AllowedNameModifiers.push_back(OMPD_target_update);
  4242. break;
  4243. case OMPD_distribute_parallel_for:
  4244. Res = ActOnOpenMPDistributeParallelForDirective(
  4245. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4246. AllowedNameModifiers.push_back(OMPD_parallel);
  4247. break;
  4248. case OMPD_distribute_parallel_for_simd:
  4249. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  4250. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4251. AllowedNameModifiers.push_back(OMPD_parallel);
  4252. break;
  4253. case OMPD_distribute_simd:
  4254. Res = ActOnOpenMPDistributeSimdDirective(
  4255. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4256. break;
  4257. case OMPD_target_parallel_for_simd:
  4258. Res = ActOnOpenMPTargetParallelForSimdDirective(
  4259. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4260. AllowedNameModifiers.push_back(OMPD_target);
  4261. AllowedNameModifiers.push_back(OMPD_parallel);
  4262. break;
  4263. case OMPD_target_simd:
  4264. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4265. EndLoc, VarsWithInheritedDSA);
  4266. AllowedNameModifiers.push_back(OMPD_target);
  4267. break;
  4268. case OMPD_teams_distribute:
  4269. Res = ActOnOpenMPTeamsDistributeDirective(
  4270. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4271. break;
  4272. case OMPD_teams_distribute_simd:
  4273. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  4274. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4275. break;
  4276. case OMPD_teams_distribute_parallel_for_simd:
  4277. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  4278. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4279. AllowedNameModifiers.push_back(OMPD_parallel);
  4280. break;
  4281. case OMPD_teams_distribute_parallel_for:
  4282. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  4283. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4284. AllowedNameModifiers.push_back(OMPD_parallel);
  4285. break;
  4286. case OMPD_target_teams:
  4287. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4288. EndLoc);
  4289. AllowedNameModifiers.push_back(OMPD_target);
  4290. break;
  4291. case OMPD_target_teams_distribute:
  4292. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  4293. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4294. AllowedNameModifiers.push_back(OMPD_target);
  4295. break;
  4296. case OMPD_target_teams_distribute_parallel_for:
  4297. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  4298. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4299. AllowedNameModifiers.push_back(OMPD_target);
  4300. AllowedNameModifiers.push_back(OMPD_parallel);
  4301. break;
  4302. case OMPD_target_teams_distribute_parallel_for_simd:
  4303. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  4304. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4305. AllowedNameModifiers.push_back(OMPD_target);
  4306. AllowedNameModifiers.push_back(OMPD_parallel);
  4307. break;
  4308. case OMPD_target_teams_distribute_simd:
  4309. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  4310. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4311. AllowedNameModifiers.push_back(OMPD_target);
  4312. break;
  4313. case OMPD_declare_target:
  4314. case OMPD_end_declare_target:
  4315. case OMPD_threadprivate:
  4316. case OMPD_allocate:
  4317. case OMPD_declare_reduction:
  4318. case OMPD_declare_mapper:
  4319. case OMPD_declare_simd:
  4320. case OMPD_requires:
  4321. case OMPD_declare_variant:
  4322. llvm_unreachable("OpenMP Directive is not allowed");
  4323. case OMPD_unknown:
  4324. llvm_unreachable("Unknown OpenMP directive");
  4325. }
  4326. ErrorFound = Res.isInvalid() || ErrorFound;
  4327. // Check variables in the clauses if default(none) was specified.
  4328. if (DSAStack->getDefaultDSA() == DSA_none) {
  4329. DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
  4330. for (OMPClause *C : Clauses) {
  4331. switch (C->getClauseKind()) {
  4332. case OMPC_num_threads:
  4333. case OMPC_dist_schedule:
  4334. // Do not analyse if no parent teams directive.
  4335. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
  4336. break;
  4337. continue;
  4338. case OMPC_if:
  4339. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
  4340. cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
  4341. break;
  4342. continue;
  4343. case OMPC_schedule:
  4344. break;
  4345. case OMPC_grainsize:
  4346. case OMPC_num_tasks:
  4347. case OMPC_final:
  4348. case OMPC_priority:
  4349. // Do not analyze if no parent parallel directive.
  4350. if (isOpenMPParallelDirective(DSAStack->getCurrentDirective()))
  4351. break;
  4352. continue;
  4353. case OMPC_ordered:
  4354. case OMPC_device:
  4355. case OMPC_num_teams:
  4356. case OMPC_thread_limit:
  4357. case OMPC_hint:
  4358. case OMPC_collapse:
  4359. case OMPC_safelen:
  4360. case OMPC_simdlen:
  4361. case OMPC_default:
  4362. case OMPC_proc_bind:
  4363. case OMPC_private:
  4364. case OMPC_firstprivate:
  4365. case OMPC_lastprivate:
  4366. case OMPC_shared:
  4367. case OMPC_reduction:
  4368. case OMPC_task_reduction:
  4369. case OMPC_in_reduction:
  4370. case OMPC_linear:
  4371. case OMPC_aligned:
  4372. case OMPC_copyin:
  4373. case OMPC_copyprivate:
  4374. case OMPC_nowait:
  4375. case OMPC_untied:
  4376. case OMPC_mergeable:
  4377. case OMPC_allocate:
  4378. case OMPC_read:
  4379. case OMPC_write:
  4380. case OMPC_update:
  4381. case OMPC_capture:
  4382. case OMPC_seq_cst:
  4383. case OMPC_depend:
  4384. case OMPC_threads:
  4385. case OMPC_simd:
  4386. case OMPC_map:
  4387. case OMPC_nogroup:
  4388. case OMPC_defaultmap:
  4389. case OMPC_to:
  4390. case OMPC_from:
  4391. case OMPC_use_device_ptr:
  4392. case OMPC_is_device_ptr:
  4393. continue;
  4394. case OMPC_allocator:
  4395. case OMPC_flush:
  4396. case OMPC_threadprivate:
  4397. case OMPC_uniform:
  4398. case OMPC_unknown:
  4399. case OMPC_unified_address:
  4400. case OMPC_unified_shared_memory:
  4401. case OMPC_reverse_offload:
  4402. case OMPC_dynamic_allocators:
  4403. case OMPC_atomic_default_mem_order:
  4404. case OMPC_device_type:
  4405. case OMPC_match:
  4406. llvm_unreachable("Unexpected clause");
  4407. }
  4408. for (Stmt *CC : C->children()) {
  4409. if (CC)
  4410. DSAChecker.Visit(CC);
  4411. }
  4412. }
  4413. for (auto &P : DSAChecker.getVarsWithInheritedDSA())
  4414. VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
  4415. }
  4416. for (const auto &P : VarsWithInheritedDSA) {
  4417. if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
  4418. continue;
  4419. ErrorFound = true;
  4420. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  4421. << P.first << P.second->getSourceRange();
  4422. Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
  4423. }
  4424. if (!AllowedNameModifiers.empty())
  4425. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  4426. ErrorFound;
  4427. if (ErrorFound)
  4428. return StmtError();
  4429. if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
  4430. Res.getAs<OMPExecutableDirective>()
  4431. ->getStructuredBlock()
  4432. ->setIsOMPStructuredBlock(true);
  4433. }
  4434. if (!CurContext->isDependentContext() &&
  4435. isOpenMPTargetExecutionDirective(Kind) &&
  4436. !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  4437. DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
  4438. DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
  4439. DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
  4440. // Register target to DSA Stack.
  4441. DSAStack->addTargetDirLocation(StartLoc);
  4442. }
  4443. return Res;
  4444. }
  4445. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  4446. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  4447. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  4448. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  4449. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  4450. assert(Aligneds.size() == Alignments.size());
  4451. assert(Linears.size() == LinModifiers.size());
  4452. assert(Linears.size() == Steps.size());
  4453. if (!DG || DG.get().isNull())
  4454. return DeclGroupPtrTy();
  4455. const int SimdId = 0;
  4456. if (!DG.get().isSingleDecl()) {
  4457. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4458. << SimdId;
  4459. return DG;
  4460. }
  4461. Decl *ADecl = DG.get().getSingleDecl();
  4462. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4463. ADecl = FTD->getTemplatedDecl();
  4464. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4465. if (!FD) {
  4466. Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
  4467. return DeclGroupPtrTy();
  4468. }
  4469. // OpenMP [2.8.2, declare simd construct, Description]
  4470. // The parameter of the simdlen clause must be a constant positive integer
  4471. // expression.
  4472. ExprResult SL;
  4473. if (Simdlen)
  4474. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  4475. // OpenMP [2.8.2, declare simd construct, Description]
  4476. // The special this pointer can be used as if was one of the arguments to the
  4477. // function in any of the linear, aligned, or uniform clauses.
  4478. // The uniform clause declares one or more arguments to have an invariant
  4479. // value for all concurrent invocations of the function in the execution of a
  4480. // single SIMD loop.
  4481. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  4482. const Expr *UniformedLinearThis = nullptr;
  4483. for (const Expr *E : Uniforms) {
  4484. E = E->IgnoreParenImpCasts();
  4485. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4486. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  4487. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4488. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4489. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  4490. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  4491. continue;
  4492. }
  4493. if (isa<CXXThisExpr>(E)) {
  4494. UniformedLinearThis = E;
  4495. continue;
  4496. }
  4497. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4498. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4499. }
  4500. // OpenMP [2.8.2, declare simd construct, Description]
  4501. // The aligned clause declares that the object to which each list item points
  4502. // is aligned to the number of bytes expressed in the optional parameter of
  4503. // the aligned clause.
  4504. // The special this pointer can be used as if was one of the arguments to the
  4505. // function in any of the linear, aligned, or uniform clauses.
  4506. // The type of list items appearing in the aligned clause must be array,
  4507. // pointer, reference to array, or reference to pointer.
  4508. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  4509. const Expr *AlignedThis = nullptr;
  4510. for (const Expr *E : Aligneds) {
  4511. E = E->IgnoreParenImpCasts();
  4512. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4513. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4514. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4515. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4516. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4517. ->getCanonicalDecl() == CanonPVD) {
  4518. // OpenMP [2.8.1, simd construct, Restrictions]
  4519. // A list-item cannot appear in more than one aligned clause.
  4520. if (AlignedArgs.count(CanonPVD) > 0) {
  4521. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4522. << 1 << E->getSourceRange();
  4523. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  4524. diag::note_omp_explicit_dsa)
  4525. << getOpenMPClauseName(OMPC_aligned);
  4526. continue;
  4527. }
  4528. AlignedArgs[CanonPVD] = E;
  4529. QualType QTy = PVD->getType()
  4530. .getNonReferenceType()
  4531. .getUnqualifiedType()
  4532. .getCanonicalType();
  4533. const Type *Ty = QTy.getTypePtrOrNull();
  4534. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  4535. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  4536. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  4537. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  4538. }
  4539. continue;
  4540. }
  4541. }
  4542. if (isa<CXXThisExpr>(E)) {
  4543. if (AlignedThis) {
  4544. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4545. << 2 << E->getSourceRange();
  4546. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4547. << getOpenMPClauseName(OMPC_aligned);
  4548. }
  4549. AlignedThis = E;
  4550. continue;
  4551. }
  4552. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4553. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4554. }
  4555. // The optional parameter of the aligned clause, alignment, must be a constant
  4556. // positive integer expression. If no optional parameter is specified,
  4557. // implementation-defined default alignments for SIMD instructions on the
  4558. // target platforms are assumed.
  4559. SmallVector<const Expr *, 4> NewAligns;
  4560. for (Expr *E : Alignments) {
  4561. ExprResult Align;
  4562. if (E)
  4563. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  4564. NewAligns.push_back(Align.get());
  4565. }
  4566. // OpenMP [2.8.2, declare simd construct, Description]
  4567. // The linear clause declares one or more list items to be private to a SIMD
  4568. // lane and to have a linear relationship with respect to the iteration space
  4569. // of a loop.
  4570. // The special this pointer can be used as if was one of the arguments to the
  4571. // function in any of the linear, aligned, or uniform clauses.
  4572. // When a linear-step expression is specified in a linear clause it must be
  4573. // either a constant integer expression or an integer-typed parameter that is
  4574. // specified in a uniform clause on the directive.
  4575. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  4576. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  4577. auto MI = LinModifiers.begin();
  4578. for (const Expr *E : Linears) {
  4579. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  4580. ++MI;
  4581. E = E->IgnoreParenImpCasts();
  4582. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4583. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4584. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4585. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4586. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4587. ->getCanonicalDecl() == CanonPVD) {
  4588. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  4589. // A list-item cannot appear in more than one linear clause.
  4590. if (LinearArgs.count(CanonPVD) > 0) {
  4591. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4592. << getOpenMPClauseName(OMPC_linear)
  4593. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  4594. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  4595. diag::note_omp_explicit_dsa)
  4596. << getOpenMPClauseName(OMPC_linear);
  4597. continue;
  4598. }
  4599. // Each argument can appear in at most one uniform or linear clause.
  4600. if (UniformedArgs.count(CanonPVD) > 0) {
  4601. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4602. << getOpenMPClauseName(OMPC_linear)
  4603. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  4604. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  4605. diag::note_omp_explicit_dsa)
  4606. << getOpenMPClauseName(OMPC_uniform);
  4607. continue;
  4608. }
  4609. LinearArgs[CanonPVD] = E;
  4610. if (E->isValueDependent() || E->isTypeDependent() ||
  4611. E->isInstantiationDependent() ||
  4612. E->containsUnexpandedParameterPack())
  4613. continue;
  4614. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  4615. PVD->getOriginalType());
  4616. continue;
  4617. }
  4618. }
  4619. if (isa<CXXThisExpr>(E)) {
  4620. if (UniformedLinearThis) {
  4621. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4622. << getOpenMPClauseName(OMPC_linear)
  4623. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  4624. << E->getSourceRange();
  4625. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4626. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  4627. : OMPC_linear);
  4628. continue;
  4629. }
  4630. UniformedLinearThis = E;
  4631. if (E->isValueDependent() || E->isTypeDependent() ||
  4632. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4633. continue;
  4634. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  4635. E->getType());
  4636. continue;
  4637. }
  4638. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4639. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4640. }
  4641. Expr *Step = nullptr;
  4642. Expr *NewStep = nullptr;
  4643. SmallVector<Expr *, 4> NewSteps;
  4644. for (Expr *E : Steps) {
  4645. // Skip the same step expression, it was checked already.
  4646. if (Step == E || !E) {
  4647. NewSteps.push_back(E ? NewStep : nullptr);
  4648. continue;
  4649. }
  4650. Step = E;
  4651. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  4652. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4653. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4654. if (UniformedArgs.count(CanonPVD) == 0) {
  4655. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  4656. << Step->getSourceRange();
  4657. } else if (E->isValueDependent() || E->isTypeDependent() ||
  4658. E->isInstantiationDependent() ||
  4659. E->containsUnexpandedParameterPack() ||
  4660. CanonPVD->getType()->hasIntegerRepresentation()) {
  4661. NewSteps.push_back(Step);
  4662. } else {
  4663. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  4664. << Step->getSourceRange();
  4665. }
  4666. continue;
  4667. }
  4668. NewStep = Step;
  4669. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  4670. !Step->isInstantiationDependent() &&
  4671. !Step->containsUnexpandedParameterPack()) {
  4672. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  4673. .get();
  4674. if (NewStep)
  4675. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  4676. }
  4677. NewSteps.push_back(NewStep);
  4678. }
  4679. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  4680. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  4681. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  4682. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  4683. const_cast<Expr **>(Linears.data()), Linears.size(),
  4684. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  4685. NewSteps.data(), NewSteps.size(), SR);
  4686. ADecl->addAttr(NewAttr);
  4687. return DG;
  4688. }
  4689. Optional<std::pair<FunctionDecl *, Expr *>>
  4690. Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
  4691. Expr *VariantRef, SourceRange SR) {
  4692. if (!DG || DG.get().isNull())
  4693. return None;
  4694. const int VariantId = 1;
  4695. // Must be applied only to single decl.
  4696. if (!DG.get().isSingleDecl()) {
  4697. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4698. << VariantId << SR;
  4699. return None;
  4700. }
  4701. Decl *ADecl = DG.get().getSingleDecl();
  4702. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4703. ADecl = FTD->getTemplatedDecl();
  4704. // Decl must be a function.
  4705. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4706. if (!FD) {
  4707. Diag(ADecl->getLocation(), diag::err_omp_function_expected)
  4708. << VariantId << SR;
  4709. return None;
  4710. }
  4711. auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
  4712. return FD->hasAttrs() &&
  4713. (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
  4714. FD->hasAttr<TargetAttr>());
  4715. };
  4716. // OpenMP is not compatible with CPU-specific attributes.
  4717. if (HasMultiVersionAttributes(FD)) {
  4718. Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
  4719. << SR;
  4720. return None;
  4721. }
  4722. // Allow #pragma omp declare variant only if the function is not used.
  4723. if (FD->isUsed(false))
  4724. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
  4725. << FD->getLocation();
  4726. // Check if the function was emitted already.
  4727. const FunctionDecl *Definition;
  4728. if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
  4729. (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
  4730. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
  4731. << FD->getLocation();
  4732. // The VariantRef must point to function.
  4733. if (!VariantRef) {
  4734. Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
  4735. return None;
  4736. }
  4737. // Do not check templates, wait until instantiation.
  4738. if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
  4739. VariantRef->containsUnexpandedParameterPack() ||
  4740. VariantRef->isInstantiationDependent() || FD->isDependentContext())
  4741. return std::make_pair(FD, VariantRef);
  4742. // Convert VariantRef expression to the type of the original function to
  4743. // resolve possible conflicts.
  4744. ExprResult VariantRefCast;
  4745. if (LangOpts.CPlusPlus) {
  4746. QualType FnPtrType;
  4747. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  4748. if (Method && !Method->isStatic()) {
  4749. const Type *ClassType =
  4750. Context.getTypeDeclType(Method->getParent()).getTypePtr();
  4751. FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
  4752. ExprResult ER;
  4753. {
  4754. // Build adrr_of unary op to correctly handle type checks for member
  4755. // functions.
  4756. Sema::TentativeAnalysisScope Trap(*this);
  4757. ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
  4758. VariantRef);
  4759. }
  4760. if (!ER.isUsable()) {
  4761. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4762. << VariantId << VariantRef->getSourceRange();
  4763. return None;
  4764. }
  4765. VariantRef = ER.get();
  4766. } else {
  4767. FnPtrType = Context.getPointerType(FD->getType());
  4768. }
  4769. ImplicitConversionSequence ICS =
  4770. TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
  4771. /*SuppressUserConversions=*/false,
  4772. /*AllowExplicit=*/false,
  4773. /*InOverloadResolution=*/false,
  4774. /*CStyle=*/false,
  4775. /*AllowObjCWritebackConversion=*/false);
  4776. if (ICS.isFailure()) {
  4777. Diag(VariantRef->getExprLoc(),
  4778. diag::err_omp_declare_variant_incompat_types)
  4779. << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
  4780. return None;
  4781. }
  4782. VariantRefCast = PerformImplicitConversion(
  4783. VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
  4784. if (!VariantRefCast.isUsable())
  4785. return None;
  4786. // Drop previously built artificial addr_of unary op for member functions.
  4787. if (Method && !Method->isStatic()) {
  4788. Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
  4789. if (auto *UO = dyn_cast<UnaryOperator>(
  4790. PossibleAddrOfVariantRef->IgnoreImplicit()))
  4791. VariantRefCast = UO->getSubExpr();
  4792. }
  4793. } else {
  4794. VariantRefCast = VariantRef;
  4795. }
  4796. ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
  4797. if (!ER.isUsable() ||
  4798. !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
  4799. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4800. << VariantId << VariantRef->getSourceRange();
  4801. return None;
  4802. }
  4803. // The VariantRef must point to function.
  4804. auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
  4805. if (!DRE) {
  4806. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4807. << VariantId << VariantRef->getSourceRange();
  4808. return None;
  4809. }
  4810. auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
  4811. if (!NewFD) {
  4812. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4813. << VariantId << VariantRef->getSourceRange();
  4814. return None;
  4815. }
  4816. // Check if variant function is not marked with declare variant directive.
  4817. if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
  4818. Diag(VariantRef->getExprLoc(),
  4819. diag::warn_omp_declare_variant_marked_as_declare_variant)
  4820. << VariantRef->getSourceRange();
  4821. SourceRange SR =
  4822. NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
  4823. Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
  4824. return None;
  4825. }
  4826. enum DoesntSupport {
  4827. VirtFuncs = 1,
  4828. Constructors = 3,
  4829. Destructors = 4,
  4830. DeletedFuncs = 5,
  4831. DefaultedFuncs = 6,
  4832. ConstexprFuncs = 7,
  4833. ConstevalFuncs = 8,
  4834. };
  4835. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  4836. if (CXXFD->isVirtual()) {
  4837. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4838. << VirtFuncs;
  4839. return None;
  4840. }
  4841. if (isa<CXXConstructorDecl>(FD)) {
  4842. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4843. << Constructors;
  4844. return None;
  4845. }
  4846. if (isa<CXXDestructorDecl>(FD)) {
  4847. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4848. << Destructors;
  4849. return None;
  4850. }
  4851. }
  4852. if (FD->isDeleted()) {
  4853. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4854. << DeletedFuncs;
  4855. return None;
  4856. }
  4857. if (FD->isDefaulted()) {
  4858. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4859. << DefaultedFuncs;
  4860. return None;
  4861. }
  4862. if (FD->isConstexpr()) {
  4863. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4864. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  4865. return None;
  4866. }
  4867. // Check general compatibility.
  4868. if (areMultiversionVariantFunctionsCompatible(
  4869. FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
  4870. PartialDiagnosticAt(
  4871. SR.getBegin(),
  4872. PDiag(diag::note_omp_declare_variant_specified_here) << SR),
  4873. PartialDiagnosticAt(
  4874. VariantRef->getExprLoc(),
  4875. PDiag(diag::err_omp_declare_variant_doesnt_support)),
  4876. PartialDiagnosticAt(VariantRef->getExprLoc(),
  4877. PDiag(diag::err_omp_declare_variant_diff)
  4878. << FD->getLocation()),
  4879. /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
  4880. /*CLinkageMayDiffer=*/true))
  4881. return None;
  4882. return std::make_pair(FD, cast<Expr>(DRE));
  4883. }
  4884. void Sema::ActOnOpenMPDeclareVariantDirective(
  4885. FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
  4886. const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
  4887. if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
  4888. Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
  4889. return;
  4890. Expr *Score = nullptr;
  4891. OMPDeclareVariantAttr::ScoreType ST = OMPDeclareVariantAttr::ScoreUnknown;
  4892. if (Data.CtxScore.isUsable()) {
  4893. ST = OMPDeclareVariantAttr::ScoreSpecified;
  4894. Score = Data.CtxScore.get();
  4895. if (!Score->isTypeDependent() && !Score->isValueDependent() &&
  4896. !Score->isInstantiationDependent() &&
  4897. !Score->containsUnexpandedParameterPack()) {
  4898. llvm::APSInt Result;
  4899. ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
  4900. if (ICE.isInvalid())
  4901. return;
  4902. }
  4903. }
  4904. auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
  4905. Context, VariantRef, Score, Data.CtxSet, ST, Data.Ctx,
  4906. Data.ImplVendors.begin(), Data.ImplVendors.size(), SR);
  4907. FD->addAttr(NewAttr);
  4908. }
  4909. void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
  4910. FunctionDecl *Func,
  4911. bool MightBeOdrUse) {
  4912. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  4913. if (!Func->isDependentContext() && Func->hasAttrs()) {
  4914. for (OMPDeclareVariantAttr *A :
  4915. Func->specific_attrs<OMPDeclareVariantAttr>()) {
  4916. // TODO: add checks for active OpenMP context where possible.
  4917. Expr *VariantRef = A->getVariantFuncRef();
  4918. auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
  4919. auto *F = cast<FunctionDecl>(DRE->getDecl());
  4920. if (!F->isDefined() && F->isTemplateInstantiation())
  4921. InstantiateFunctionDefinition(Loc, F->getFirstDecl());
  4922. MarkFunctionReferenced(Loc, F, MightBeOdrUse);
  4923. }
  4924. }
  4925. }
  4926. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  4927. Stmt *AStmt,
  4928. SourceLocation StartLoc,
  4929. SourceLocation EndLoc) {
  4930. if (!AStmt)
  4931. return StmtError();
  4932. auto *CS = cast<CapturedStmt>(AStmt);
  4933. // 1.2.2 OpenMP Language Terminology
  4934. // Structured block - An executable statement with a single entry at the
  4935. // top and a single exit at the bottom.
  4936. // The point of exit cannot be a branch out of the structured block.
  4937. // longjmp() and throw() must not violate the entry/exit criteria.
  4938. CS->getCapturedDecl()->setNothrow();
  4939. setFunctionHasBranchProtectedScope();
  4940. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4941. DSAStack->isCancelRegion());
  4942. }
  4943. namespace {
  4944. /// Iteration space of a single for loop.
  4945. struct LoopIterationSpace final {
  4946. /// True if the condition operator is the strict compare operator (<, > or
  4947. /// !=).
  4948. bool IsStrictCompare = false;
  4949. /// Condition of the loop.
  4950. Expr *PreCond = nullptr;
  4951. /// This expression calculates the number of iterations in the loop.
  4952. /// It is always possible to calculate it before starting the loop.
  4953. Expr *NumIterations = nullptr;
  4954. /// The loop counter variable.
  4955. Expr *CounterVar = nullptr;
  4956. /// Private loop counter variable.
  4957. Expr *PrivateCounterVar = nullptr;
  4958. /// This is initializer for the initial value of #CounterVar.
  4959. Expr *CounterInit = nullptr;
  4960. /// This is step for the #CounterVar used to generate its update:
  4961. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4962. Expr *CounterStep = nullptr;
  4963. /// Should step be subtracted?
  4964. bool Subtract = false;
  4965. /// Source range of the loop init.
  4966. SourceRange InitSrcRange;
  4967. /// Source range of the loop condition.
  4968. SourceRange CondSrcRange;
  4969. /// Source range of the loop increment.
  4970. SourceRange IncSrcRange;
  4971. /// Minimum value that can have the loop control variable. Used to support
  4972. /// non-rectangular loops. Applied only for LCV with the non-iterator types,
  4973. /// since only such variables can be used in non-loop invariant expressions.
  4974. Expr *MinValue = nullptr;
  4975. /// Maximum value that can have the loop control variable. Used to support
  4976. /// non-rectangular loops. Applied only for LCV with the non-iterator type,
  4977. /// since only such variables can be used in non-loop invariant expressions.
  4978. Expr *MaxValue = nullptr;
  4979. /// true, if the lower bound depends on the outer loop control var.
  4980. bool IsNonRectangularLB = false;
  4981. /// true, if the upper bound depends on the outer loop control var.
  4982. bool IsNonRectangularUB = false;
  4983. /// Index of the loop this loop depends on and forms non-rectangular loop
  4984. /// nest.
  4985. unsigned LoopDependentIdx = 0;
  4986. /// Final condition for the non-rectangular loop nest support. It is used to
  4987. /// check that the number of iterations for this particular counter must be
  4988. /// finished.
  4989. Expr *FinalCondition = nullptr;
  4990. };
  4991. /// Helper class for checking canonical form of the OpenMP loops and
  4992. /// extracting iteration space of each loop in the loop nest, that will be used
  4993. /// for IR generation.
  4994. class OpenMPIterationSpaceChecker {
  4995. /// Reference to Sema.
  4996. Sema &SemaRef;
  4997. /// Data-sharing stack.
  4998. DSAStackTy &Stack;
  4999. /// A location for diagnostics (when there is no some better location).
  5000. SourceLocation DefaultLoc;
  5001. /// A location for diagnostics (when increment is not compatible).
  5002. SourceLocation ConditionLoc;
  5003. /// A source location for referring to loop init later.
  5004. SourceRange InitSrcRange;
  5005. /// A source location for referring to condition later.
  5006. SourceRange ConditionSrcRange;
  5007. /// A source location for referring to increment later.
  5008. SourceRange IncrementSrcRange;
  5009. /// Loop variable.
  5010. ValueDecl *LCDecl = nullptr;
  5011. /// Reference to loop variable.
  5012. Expr *LCRef = nullptr;
  5013. /// Lower bound (initializer for the var).
  5014. Expr *LB = nullptr;
  5015. /// Upper bound.
  5016. Expr *UB = nullptr;
  5017. /// Loop step (increment).
  5018. Expr *Step = nullptr;
  5019. /// This flag is true when condition is one of:
  5020. /// Var < UB
  5021. /// Var <= UB
  5022. /// UB > Var
  5023. /// UB >= Var
  5024. /// This will have no value when the condition is !=
  5025. llvm::Optional<bool> TestIsLessOp;
  5026. /// This flag is true when condition is strict ( < or > ).
  5027. bool TestIsStrictOp = false;
  5028. /// This flag is true when step is subtracted on each iteration.
  5029. bool SubtractStep = false;
  5030. /// The outer loop counter this loop depends on (if any).
  5031. const ValueDecl *DepDecl = nullptr;
  5032. /// Contains number of loop (starts from 1) on which loop counter init
  5033. /// expression of this loop depends on.
  5034. Optional<unsigned> InitDependOnLC;
  5035. /// Contains number of loop (starts from 1) on which loop counter condition
  5036. /// expression of this loop depends on.
  5037. Optional<unsigned> CondDependOnLC;
  5038. /// Checks if the provide statement depends on the loop counter.
  5039. Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
  5040. /// Original condition required for checking of the exit condition for
  5041. /// non-rectangular loop.
  5042. Expr *Condition = nullptr;
  5043. public:
  5044. OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
  5045. SourceLocation DefaultLoc)
  5046. : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
  5047. ConditionLoc(DefaultLoc) {}
  5048. /// Check init-expr for canonical loop form and save loop counter
  5049. /// variable - #Var and its initialization value - #LB.
  5050. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  5051. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  5052. /// for less/greater and for strict/non-strict comparison.
  5053. bool checkAndSetCond(Expr *S);
  5054. /// Check incr-expr for canonical loop form and return true if it
  5055. /// does not conform, otherwise save loop step (#Step).
  5056. bool checkAndSetInc(Expr *S);
  5057. /// Return the loop counter variable.
  5058. ValueDecl *getLoopDecl() const { return LCDecl; }
  5059. /// Return the reference expression to loop counter variable.
  5060. Expr *getLoopDeclRefExpr() const { return LCRef; }
  5061. /// Source range of the loop init.
  5062. SourceRange getInitSrcRange() const { return InitSrcRange; }
  5063. /// Source range of the loop condition.
  5064. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  5065. /// Source range of the loop increment.
  5066. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  5067. /// True if the step should be subtracted.
  5068. bool shouldSubtractStep() const { return SubtractStep; }
  5069. /// True, if the compare operator is strict (<, > or !=).
  5070. bool isStrictTestOp() const { return TestIsStrictOp; }
  5071. /// Build the expression to calculate the number of iterations.
  5072. Expr *buildNumIterations(
  5073. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5074. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5075. /// Build the precondition expression for the loops.
  5076. Expr *
  5077. buildPreCond(Scope *S, Expr *Cond,
  5078. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5079. /// Build reference expression to the counter be used for codegen.
  5080. DeclRefExpr *
  5081. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5082. DSAStackTy &DSA) const;
  5083. /// Build reference expression to the private counter be used for
  5084. /// codegen.
  5085. Expr *buildPrivateCounterVar() const;
  5086. /// Build initialization of the counter be used for codegen.
  5087. Expr *buildCounterInit() const;
  5088. /// Build step of the counter be used for codegen.
  5089. Expr *buildCounterStep() const;
  5090. /// Build loop data with counter value for depend clauses in ordered
  5091. /// directives.
  5092. Expr *
  5093. buildOrderedLoopData(Scope *S, Expr *Counter,
  5094. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5095. SourceLocation Loc, Expr *Inc = nullptr,
  5096. OverloadedOperatorKind OOK = OO_Amp);
  5097. /// Builds the minimum value for the loop counter.
  5098. std::pair<Expr *, Expr *> buildMinMaxValues(
  5099. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5100. /// Builds final condition for the non-rectangular loops.
  5101. Expr *buildFinalCondition(Scope *S) const;
  5102. /// Return true if any expression is dependent.
  5103. bool dependent() const;
  5104. /// Returns true if the initializer forms non-rectangular loop.
  5105. bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
  5106. /// Returns true if the condition forms non-rectangular loop.
  5107. bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
  5108. /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
  5109. unsigned getLoopDependentIdx() const {
  5110. return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
  5111. }
  5112. private:
  5113. /// Check the right-hand side of an assignment in the increment
  5114. /// expression.
  5115. bool checkAndSetIncRHS(Expr *RHS);
  5116. /// Helper to set loop counter variable and its initializer.
  5117. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
  5118. bool EmitDiags);
  5119. /// Helper to set upper bound.
  5120. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  5121. SourceRange SR, SourceLocation SL);
  5122. /// Helper to set loop increment.
  5123. bool setStep(Expr *NewStep, bool Subtract);
  5124. };
  5125. bool OpenMPIterationSpaceChecker::dependent() const {
  5126. if (!LCDecl) {
  5127. assert(!LB && !UB && !Step);
  5128. return false;
  5129. }
  5130. return LCDecl->getType()->isDependentType() ||
  5131. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  5132. (Step && Step->isValueDependent());
  5133. }
  5134. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  5135. Expr *NewLCRefExpr,
  5136. Expr *NewLB, bool EmitDiags) {
  5137. // State consistency checking to ensure correct usage.
  5138. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  5139. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5140. if (!NewLCDecl || !NewLB)
  5141. return true;
  5142. LCDecl = getCanonicalDecl(NewLCDecl);
  5143. LCRef = NewLCRefExpr;
  5144. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  5145. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5146. if ((Ctor->isCopyOrMoveConstructor() ||
  5147. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5148. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5149. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  5150. LB = NewLB;
  5151. if (EmitDiags)
  5152. InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
  5153. return false;
  5154. }
  5155. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  5156. llvm::Optional<bool> LessOp,
  5157. bool StrictOp, SourceRange SR,
  5158. SourceLocation SL) {
  5159. // State consistency checking to ensure correct usage.
  5160. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  5161. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5162. if (!NewUB)
  5163. return true;
  5164. UB = NewUB;
  5165. if (LessOp)
  5166. TestIsLessOp = LessOp;
  5167. TestIsStrictOp = StrictOp;
  5168. ConditionSrcRange = SR;
  5169. ConditionLoc = SL;
  5170. CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
  5171. return false;
  5172. }
  5173. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  5174. // State consistency checking to ensure correct usage.
  5175. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  5176. if (!NewStep)
  5177. return true;
  5178. if (!NewStep->isValueDependent()) {
  5179. // Check that the step is integer expression.
  5180. SourceLocation StepLoc = NewStep->getBeginLoc();
  5181. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  5182. StepLoc, getExprAsWritten(NewStep));
  5183. if (Val.isInvalid())
  5184. return true;
  5185. NewStep = Val.get();
  5186. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  5187. // If test-expr is of form var relational-op b and relational-op is < or
  5188. // <= then incr-expr must cause var to increase on each iteration of the
  5189. // loop. If test-expr is of form var relational-op b and relational-op is
  5190. // > or >= then incr-expr must cause var to decrease on each iteration of
  5191. // the loop.
  5192. // If test-expr is of form b relational-op var and relational-op is < or
  5193. // <= then incr-expr must cause var to decrease on each iteration of the
  5194. // loop. If test-expr is of form b relational-op var and relational-op is
  5195. // > or >= then incr-expr must cause var to increase on each iteration of
  5196. // the loop.
  5197. llvm::APSInt Result;
  5198. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  5199. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  5200. bool IsConstNeg =
  5201. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  5202. bool IsConstPos =
  5203. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  5204. bool IsConstZero = IsConstant && !Result.getBoolValue();
  5205. // != with increment is treated as <; != with decrement is treated as >
  5206. if (!TestIsLessOp.hasValue())
  5207. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  5208. if (UB && (IsConstZero ||
  5209. (TestIsLessOp.getValue() ?
  5210. (IsConstNeg || (IsUnsigned && Subtract)) :
  5211. (IsConstPos || (IsUnsigned && !Subtract))))) {
  5212. SemaRef.Diag(NewStep->getExprLoc(),
  5213. diag::err_omp_loop_incr_not_compatible)
  5214. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  5215. SemaRef.Diag(ConditionLoc,
  5216. diag::note_omp_loop_cond_requres_compatible_incr)
  5217. << TestIsLessOp.getValue() << ConditionSrcRange;
  5218. return true;
  5219. }
  5220. if (TestIsLessOp.getValue() == Subtract) {
  5221. NewStep =
  5222. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  5223. .get();
  5224. Subtract = !Subtract;
  5225. }
  5226. }
  5227. Step = NewStep;
  5228. SubtractStep = Subtract;
  5229. return false;
  5230. }
  5231. namespace {
  5232. /// Checker for the non-rectangular loops. Checks if the initializer or
  5233. /// condition expression references loop counter variable.
  5234. class LoopCounterRefChecker final
  5235. : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
  5236. Sema &SemaRef;
  5237. DSAStackTy &Stack;
  5238. const ValueDecl *CurLCDecl = nullptr;
  5239. const ValueDecl *DepDecl = nullptr;
  5240. const ValueDecl *PrevDepDecl = nullptr;
  5241. bool IsInitializer = true;
  5242. unsigned BaseLoopId = 0;
  5243. bool checkDecl(const Expr *E, const ValueDecl *VD) {
  5244. if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
  5245. SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
  5246. << (IsInitializer ? 0 : 1);
  5247. return false;
  5248. }
  5249. const auto &&Data = Stack.isLoopControlVariable(VD);
  5250. // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
  5251. // The type of the loop iterator on which we depend may not have a random
  5252. // access iterator type.
  5253. if (Data.first && VD->getType()->isRecordType()) {
  5254. SmallString<128> Name;
  5255. llvm::raw_svector_ostream OS(Name);
  5256. VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5257. /*Qualified=*/true);
  5258. SemaRef.Diag(E->getExprLoc(),
  5259. diag::err_omp_wrong_dependency_iterator_type)
  5260. << OS.str();
  5261. SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
  5262. return false;
  5263. }
  5264. if (Data.first &&
  5265. (DepDecl || (PrevDepDecl &&
  5266. getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
  5267. if (!DepDecl && PrevDepDecl)
  5268. DepDecl = PrevDepDecl;
  5269. SmallString<128> Name;
  5270. llvm::raw_svector_ostream OS(Name);
  5271. DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5272. /*Qualified=*/true);
  5273. SemaRef.Diag(E->getExprLoc(),
  5274. diag::err_omp_invariant_or_linear_dependency)
  5275. << OS.str();
  5276. return false;
  5277. }
  5278. if (Data.first) {
  5279. DepDecl = VD;
  5280. BaseLoopId = Data.first;
  5281. }
  5282. return Data.first;
  5283. }
  5284. public:
  5285. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5286. const ValueDecl *VD = E->getDecl();
  5287. if (isa<VarDecl>(VD))
  5288. return checkDecl(E, VD);
  5289. return false;
  5290. }
  5291. bool VisitMemberExpr(const MemberExpr *E) {
  5292. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  5293. const ValueDecl *VD = E->getMemberDecl();
  5294. if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
  5295. return checkDecl(E, VD);
  5296. }
  5297. return false;
  5298. }
  5299. bool VisitStmt(const Stmt *S) {
  5300. bool Res = false;
  5301. for (const Stmt *Child : S->children())
  5302. Res = (Child && Visit(Child)) || Res;
  5303. return Res;
  5304. }
  5305. explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
  5306. const ValueDecl *CurLCDecl, bool IsInitializer,
  5307. const ValueDecl *PrevDepDecl = nullptr)
  5308. : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
  5309. PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
  5310. unsigned getBaseLoopId() const {
  5311. assert(CurLCDecl && "Expected loop dependency.");
  5312. return BaseLoopId;
  5313. }
  5314. const ValueDecl *getDepDecl() const {
  5315. assert(CurLCDecl && "Expected loop dependency.");
  5316. return DepDecl;
  5317. }
  5318. };
  5319. } // namespace
  5320. Optional<unsigned>
  5321. OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
  5322. bool IsInitializer) {
  5323. // Check for the non-rectangular loops.
  5324. LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
  5325. DepDecl);
  5326. if (LoopStmtChecker.Visit(S)) {
  5327. DepDecl = LoopStmtChecker.getDepDecl();
  5328. return LoopStmtChecker.getBaseLoopId();
  5329. }
  5330. return llvm::None;
  5331. }
  5332. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  5333. // Check init-expr for canonical loop form and save loop counter
  5334. // variable - #Var and its initialization value - #LB.
  5335. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  5336. // var = lb
  5337. // integer-type var = lb
  5338. // random-access-iterator-type var = lb
  5339. // pointer-type var = lb
  5340. //
  5341. if (!S) {
  5342. if (EmitDiags) {
  5343. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  5344. }
  5345. return true;
  5346. }
  5347. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5348. if (!ExprTemp->cleanupsHaveSideEffects())
  5349. S = ExprTemp->getSubExpr();
  5350. InitSrcRange = S->getSourceRange();
  5351. if (Expr *E = dyn_cast<Expr>(S))
  5352. S = E->IgnoreParens();
  5353. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5354. if (BO->getOpcode() == BO_Assign) {
  5355. Expr *LHS = BO->getLHS()->IgnoreParens();
  5356. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5357. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5358. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5359. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5360. EmitDiags);
  5361. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
  5362. }
  5363. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5364. if (ME->isArrow() &&
  5365. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5366. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5367. EmitDiags);
  5368. }
  5369. }
  5370. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  5371. if (DS->isSingleDecl()) {
  5372. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  5373. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  5374. // Accept non-canonical init form here but emit ext. warning.
  5375. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  5376. SemaRef.Diag(S->getBeginLoc(),
  5377. diag::ext_omp_loop_not_canonical_init)
  5378. << S->getSourceRange();
  5379. return setLCDeclAndLB(
  5380. Var,
  5381. buildDeclRefExpr(SemaRef, Var,
  5382. Var->getType().getNonReferenceType(),
  5383. DS->getBeginLoc()),
  5384. Var->getInit(), EmitDiags);
  5385. }
  5386. }
  5387. }
  5388. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5389. if (CE->getOperator() == OO_Equal) {
  5390. Expr *LHS = CE->getArg(0);
  5391. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5392. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5393. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5394. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5395. EmitDiags);
  5396. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
  5397. }
  5398. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5399. if (ME->isArrow() &&
  5400. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5401. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5402. EmitDiags);
  5403. }
  5404. }
  5405. }
  5406. if (dependent() || SemaRef.CurContext->isDependentContext())
  5407. return false;
  5408. if (EmitDiags) {
  5409. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  5410. << S->getSourceRange();
  5411. }
  5412. return true;
  5413. }
  5414. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  5415. /// variable (which may be the loop variable) if possible.
  5416. static const ValueDecl *getInitLCDecl(const Expr *E) {
  5417. if (!E)
  5418. return nullptr;
  5419. E = getExprAsWritten(E);
  5420. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  5421. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5422. if ((Ctor->isCopyOrMoveConstructor() ||
  5423. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5424. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5425. E = CE->getArg(0)->IgnoreParenImpCasts();
  5426. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  5427. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  5428. return getCanonicalDecl(VD);
  5429. }
  5430. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  5431. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5432. return getCanonicalDecl(ME->getMemberDecl());
  5433. return nullptr;
  5434. }
  5435. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  5436. // Check test-expr for canonical form, save upper-bound UB, flags for
  5437. // less/greater and for strict/non-strict comparison.
  5438. // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
  5439. // var relational-op b
  5440. // b relational-op var
  5441. //
  5442. bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
  5443. if (!S) {
  5444. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
  5445. << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
  5446. return true;
  5447. }
  5448. Condition = S;
  5449. S = getExprAsWritten(S);
  5450. SourceLocation CondLoc = S->getBeginLoc();
  5451. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5452. if (BO->isRelationalOp()) {
  5453. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5454. return setUB(BO->getRHS(),
  5455. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  5456. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5457. BO->getSourceRange(), BO->getOperatorLoc());
  5458. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  5459. return setUB(BO->getLHS(),
  5460. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  5461. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5462. BO->getSourceRange(), BO->getOperatorLoc());
  5463. } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
  5464. return setUB(
  5465. getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
  5466. /*LessOp=*/llvm::None,
  5467. /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
  5468. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5469. if (CE->getNumArgs() == 2) {
  5470. auto Op = CE->getOperator();
  5471. switch (Op) {
  5472. case OO_Greater:
  5473. case OO_GreaterEqual:
  5474. case OO_Less:
  5475. case OO_LessEqual:
  5476. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5477. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  5478. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5479. CE->getOperatorLoc());
  5480. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  5481. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  5482. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5483. CE->getOperatorLoc());
  5484. break;
  5485. case OO_ExclaimEqual:
  5486. if (IneqCondIsCanonical)
  5487. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
  5488. : CE->getArg(0),
  5489. /*LessOp=*/llvm::None,
  5490. /*StrictOp=*/true, CE->getSourceRange(),
  5491. CE->getOperatorLoc());
  5492. break;
  5493. default:
  5494. break;
  5495. }
  5496. }
  5497. }
  5498. if (dependent() || SemaRef.CurContext->isDependentContext())
  5499. return false;
  5500. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  5501. << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
  5502. return true;
  5503. }
  5504. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  5505. // RHS of canonical loop form increment can be:
  5506. // var + incr
  5507. // incr + var
  5508. // var - incr
  5509. //
  5510. RHS = RHS->IgnoreParenImpCasts();
  5511. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  5512. if (BO->isAdditiveOp()) {
  5513. bool IsAdd = BO->getOpcode() == BO_Add;
  5514. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5515. return setStep(BO->getRHS(), !IsAdd);
  5516. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  5517. return setStep(BO->getLHS(), /*Subtract=*/false);
  5518. }
  5519. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  5520. bool IsAdd = CE->getOperator() == OO_Plus;
  5521. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  5522. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5523. return setStep(CE->getArg(1), !IsAdd);
  5524. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  5525. return setStep(CE->getArg(0), /*Subtract=*/false);
  5526. }
  5527. }
  5528. if (dependent() || SemaRef.CurContext->isDependentContext())
  5529. return false;
  5530. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5531. << RHS->getSourceRange() << LCDecl;
  5532. return true;
  5533. }
  5534. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  5535. // Check incr-expr for canonical loop form and return true if it
  5536. // does not conform.
  5537. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  5538. // ++var
  5539. // var++
  5540. // --var
  5541. // var--
  5542. // var += incr
  5543. // var -= incr
  5544. // var = var + incr
  5545. // var = incr + var
  5546. // var = var - incr
  5547. //
  5548. if (!S) {
  5549. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  5550. return true;
  5551. }
  5552. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5553. if (!ExprTemp->cleanupsHaveSideEffects())
  5554. S = ExprTemp->getSubExpr();
  5555. IncrementSrcRange = S->getSourceRange();
  5556. S = S->IgnoreParens();
  5557. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  5558. if (UO->isIncrementDecrementOp() &&
  5559. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  5560. return setStep(SemaRef
  5561. .ActOnIntegerConstant(UO->getBeginLoc(),
  5562. (UO->isDecrementOp() ? -1 : 1))
  5563. .get(),
  5564. /*Subtract=*/false);
  5565. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5566. switch (BO->getOpcode()) {
  5567. case BO_AddAssign:
  5568. case BO_SubAssign:
  5569. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5570. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  5571. break;
  5572. case BO_Assign:
  5573. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5574. return checkAndSetIncRHS(BO->getRHS());
  5575. break;
  5576. default:
  5577. break;
  5578. }
  5579. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5580. switch (CE->getOperator()) {
  5581. case OO_PlusPlus:
  5582. case OO_MinusMinus:
  5583. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5584. return setStep(SemaRef
  5585. .ActOnIntegerConstant(
  5586. CE->getBeginLoc(),
  5587. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  5588. .get(),
  5589. /*Subtract=*/false);
  5590. break;
  5591. case OO_PlusEqual:
  5592. case OO_MinusEqual:
  5593. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5594. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  5595. break;
  5596. case OO_Equal:
  5597. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5598. return checkAndSetIncRHS(CE->getArg(1));
  5599. break;
  5600. default:
  5601. break;
  5602. }
  5603. }
  5604. if (dependent() || SemaRef.CurContext->isDependentContext())
  5605. return false;
  5606. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5607. << S->getSourceRange() << LCDecl;
  5608. return true;
  5609. }
  5610. static ExprResult
  5611. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  5612. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5613. if (SemaRef.CurContext->isDependentContext())
  5614. return ExprResult(Capture);
  5615. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  5616. return SemaRef.PerformImplicitConversion(
  5617. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  5618. /*AllowExplicit=*/true);
  5619. auto I = Captures.find(Capture);
  5620. if (I != Captures.end())
  5621. return buildCapture(SemaRef, Capture, I->second);
  5622. DeclRefExpr *Ref = nullptr;
  5623. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  5624. Captures[Capture] = Ref;
  5625. return Res;
  5626. }
  5627. /// Build the expression to calculate the number of iterations.
  5628. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  5629. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5630. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5631. ExprResult Diff;
  5632. QualType VarType = LCDecl->getType().getNonReferenceType();
  5633. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5634. SemaRef.getLangOpts().CPlusPlus) {
  5635. Expr *LBVal = LB;
  5636. Expr *UBVal = UB;
  5637. // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
  5638. // max(LB(MinVal), LB(MaxVal))
  5639. if (InitDependOnLC) {
  5640. const LoopIterationSpace &IS =
  5641. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5642. InitDependOnLC.getValueOr(
  5643. CondDependOnLC.getValueOr(0))];
  5644. if (!IS.MinValue || !IS.MaxValue)
  5645. return nullptr;
  5646. // OuterVar = Min
  5647. ExprResult MinValue =
  5648. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5649. if (!MinValue.isUsable())
  5650. return nullptr;
  5651. ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5652. IS.CounterVar, MinValue.get());
  5653. if (!LBMinVal.isUsable())
  5654. return nullptr;
  5655. // OuterVar = Min, LBVal
  5656. LBMinVal =
  5657. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
  5658. if (!LBMinVal.isUsable())
  5659. return nullptr;
  5660. // (OuterVar = Min, LBVal)
  5661. LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
  5662. if (!LBMinVal.isUsable())
  5663. return nullptr;
  5664. // OuterVar = Max
  5665. ExprResult MaxValue =
  5666. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5667. if (!MaxValue.isUsable())
  5668. return nullptr;
  5669. ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5670. IS.CounterVar, MaxValue.get());
  5671. if (!LBMaxVal.isUsable())
  5672. return nullptr;
  5673. // OuterVar = Max, LBVal
  5674. LBMaxVal =
  5675. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
  5676. if (!LBMaxVal.isUsable())
  5677. return nullptr;
  5678. // (OuterVar = Max, LBVal)
  5679. LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
  5680. if (!LBMaxVal.isUsable())
  5681. return nullptr;
  5682. Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
  5683. Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
  5684. if (!LBMin || !LBMax)
  5685. return nullptr;
  5686. // LB(MinVal) < LB(MaxVal)
  5687. ExprResult MinLessMaxRes =
  5688. SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
  5689. if (!MinLessMaxRes.isUsable())
  5690. return nullptr;
  5691. Expr *MinLessMax =
  5692. tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
  5693. if (!MinLessMax)
  5694. return nullptr;
  5695. if (TestIsLessOp.getValue()) {
  5696. // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
  5697. // LB(MaxVal))
  5698. ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5699. MinLessMax, LBMin, LBMax);
  5700. if (!MinLB.isUsable())
  5701. return nullptr;
  5702. LBVal = MinLB.get();
  5703. } else {
  5704. // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
  5705. // LB(MaxVal))
  5706. ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5707. MinLessMax, LBMax, LBMin);
  5708. if (!MaxLB.isUsable())
  5709. return nullptr;
  5710. LBVal = MaxLB.get();
  5711. }
  5712. }
  5713. // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
  5714. // min(UB(MinVal), UB(MaxVal))
  5715. if (CondDependOnLC) {
  5716. const LoopIterationSpace &IS =
  5717. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5718. InitDependOnLC.getValueOr(
  5719. CondDependOnLC.getValueOr(0))];
  5720. if (!IS.MinValue || !IS.MaxValue)
  5721. return nullptr;
  5722. // OuterVar = Min
  5723. ExprResult MinValue =
  5724. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5725. if (!MinValue.isUsable())
  5726. return nullptr;
  5727. ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5728. IS.CounterVar, MinValue.get());
  5729. if (!UBMinVal.isUsable())
  5730. return nullptr;
  5731. // OuterVar = Min, UBVal
  5732. UBMinVal =
  5733. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
  5734. if (!UBMinVal.isUsable())
  5735. return nullptr;
  5736. // (OuterVar = Min, UBVal)
  5737. UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
  5738. if (!UBMinVal.isUsable())
  5739. return nullptr;
  5740. // OuterVar = Max
  5741. ExprResult MaxValue =
  5742. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5743. if (!MaxValue.isUsable())
  5744. return nullptr;
  5745. ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5746. IS.CounterVar, MaxValue.get());
  5747. if (!UBMaxVal.isUsable())
  5748. return nullptr;
  5749. // OuterVar = Max, UBVal
  5750. UBMaxVal =
  5751. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
  5752. if (!UBMaxVal.isUsable())
  5753. return nullptr;
  5754. // (OuterVar = Max, UBVal)
  5755. UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
  5756. if (!UBMaxVal.isUsable())
  5757. return nullptr;
  5758. Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
  5759. Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
  5760. if (!UBMin || !UBMax)
  5761. return nullptr;
  5762. // UB(MinVal) > UB(MaxVal)
  5763. ExprResult MinGreaterMaxRes =
  5764. SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
  5765. if (!MinGreaterMaxRes.isUsable())
  5766. return nullptr;
  5767. Expr *MinGreaterMax =
  5768. tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
  5769. if (!MinGreaterMax)
  5770. return nullptr;
  5771. if (TestIsLessOp.getValue()) {
  5772. // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
  5773. // UB(MaxVal))
  5774. ExprResult MaxUB = SemaRef.ActOnConditionalOp(
  5775. DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
  5776. if (!MaxUB.isUsable())
  5777. return nullptr;
  5778. UBVal = MaxUB.get();
  5779. } else {
  5780. // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
  5781. // UB(MaxVal))
  5782. ExprResult MinUB = SemaRef.ActOnConditionalOp(
  5783. DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
  5784. if (!MinUB.isUsable())
  5785. return nullptr;
  5786. UBVal = MinUB.get();
  5787. }
  5788. }
  5789. // Upper - Lower
  5790. Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
  5791. Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
  5792. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5793. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5794. if (!Upper || !Lower)
  5795. return nullptr;
  5796. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5797. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  5798. // BuildBinOp already emitted error, this one is to point user to upper
  5799. // and lower bound, and to tell what is passed to 'operator-'.
  5800. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  5801. << Upper->getSourceRange() << Lower->getSourceRange();
  5802. return nullptr;
  5803. }
  5804. }
  5805. if (!Diff.isUsable())
  5806. return nullptr;
  5807. // Upper - Lower [- 1]
  5808. if (TestIsStrictOp)
  5809. Diff = SemaRef.BuildBinOp(
  5810. S, DefaultLoc, BO_Sub, Diff.get(),
  5811. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5812. if (!Diff.isUsable())
  5813. return nullptr;
  5814. // Upper - Lower [- 1] + Step
  5815. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5816. if (!NewStep.isUsable())
  5817. return nullptr;
  5818. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  5819. if (!Diff.isUsable())
  5820. return nullptr;
  5821. // Parentheses (for dumping/debugging purposes only).
  5822. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5823. if (!Diff.isUsable())
  5824. return nullptr;
  5825. // (Upper - Lower [- 1] + Step) / Step
  5826. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5827. if (!Diff.isUsable())
  5828. return nullptr;
  5829. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  5830. QualType Type = Diff.get()->getType();
  5831. ASTContext &C = SemaRef.Context;
  5832. bool UseVarType = VarType->hasIntegerRepresentation() &&
  5833. C.getTypeSize(Type) > C.getTypeSize(VarType);
  5834. if (!Type->isIntegerType() || UseVarType) {
  5835. unsigned NewSize =
  5836. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  5837. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  5838. : Type->hasSignedIntegerRepresentation();
  5839. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  5840. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  5841. Diff = SemaRef.PerformImplicitConversion(
  5842. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  5843. if (!Diff.isUsable())
  5844. return nullptr;
  5845. }
  5846. }
  5847. if (LimitedType) {
  5848. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  5849. if (NewSize != C.getTypeSize(Type)) {
  5850. if (NewSize < C.getTypeSize(Type)) {
  5851. assert(NewSize == 64 && "incorrect loop var size");
  5852. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  5853. << InitSrcRange << ConditionSrcRange;
  5854. }
  5855. QualType NewType = C.getIntTypeForBitwidth(
  5856. NewSize, Type->hasSignedIntegerRepresentation() ||
  5857. C.getTypeSize(Type) < NewSize);
  5858. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  5859. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  5860. Sema::AA_Converting, true);
  5861. if (!Diff.isUsable())
  5862. return nullptr;
  5863. }
  5864. }
  5865. }
  5866. return Diff.get();
  5867. }
  5868. std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
  5869. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5870. // Do not build for iterators, they cannot be used in non-rectangular loop
  5871. // nests.
  5872. if (LCDecl->getType()->isRecordType())
  5873. return std::make_pair(nullptr, nullptr);
  5874. // If we subtract, the min is in the condition, otherwise the min is in the
  5875. // init value.
  5876. Expr *MinExpr = nullptr;
  5877. Expr *MaxExpr = nullptr;
  5878. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  5879. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  5880. bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
  5881. : CondDependOnLC.hasValue();
  5882. bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
  5883. : InitDependOnLC.hasValue();
  5884. Expr *Lower =
  5885. LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5886. Expr *Upper =
  5887. UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5888. if (!Upper || !Lower)
  5889. return std::make_pair(nullptr, nullptr);
  5890. if (TestIsLessOp.getValue())
  5891. MinExpr = Lower;
  5892. else
  5893. MaxExpr = Upper;
  5894. // Build minimum/maximum value based on number of iterations.
  5895. ExprResult Diff;
  5896. QualType VarType = LCDecl->getType().getNonReferenceType();
  5897. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5898. if (!Diff.isUsable())
  5899. return std::make_pair(nullptr, nullptr);
  5900. // Upper - Lower [- 1]
  5901. if (TestIsStrictOp)
  5902. Diff = SemaRef.BuildBinOp(
  5903. S, DefaultLoc, BO_Sub, Diff.get(),
  5904. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5905. if (!Diff.isUsable())
  5906. return std::make_pair(nullptr, nullptr);
  5907. // Upper - Lower [- 1] + Step
  5908. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5909. if (!NewStep.isUsable())
  5910. return std::make_pair(nullptr, nullptr);
  5911. // Parentheses (for dumping/debugging purposes only).
  5912. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5913. if (!Diff.isUsable())
  5914. return std::make_pair(nullptr, nullptr);
  5915. // (Upper - Lower [- 1]) / Step
  5916. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5917. if (!Diff.isUsable())
  5918. return std::make_pair(nullptr, nullptr);
  5919. // ((Upper - Lower [- 1]) / Step) * Step
  5920. // Parentheses (for dumping/debugging purposes only).
  5921. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5922. if (!Diff.isUsable())
  5923. return std::make_pair(nullptr, nullptr);
  5924. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
  5925. if (!Diff.isUsable())
  5926. return std::make_pair(nullptr, nullptr);
  5927. // Convert to the original type or ptrdiff_t, if original type is pointer.
  5928. if (!VarType->isAnyPointerType() &&
  5929. !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
  5930. Diff = SemaRef.PerformImplicitConversion(
  5931. Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
  5932. } else if (VarType->isAnyPointerType() &&
  5933. !SemaRef.Context.hasSameType(
  5934. Diff.get()->getType(),
  5935. SemaRef.Context.getUnsignedPointerDiffType())) {
  5936. Diff = SemaRef.PerformImplicitConversion(
  5937. Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
  5938. Sema::AA_Converting, /*AllowExplicit=*/true);
  5939. }
  5940. if (!Diff.isUsable())
  5941. return std::make_pair(nullptr, nullptr);
  5942. // Parentheses (for dumping/debugging purposes only).
  5943. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5944. if (!Diff.isUsable())
  5945. return std::make_pair(nullptr, nullptr);
  5946. if (TestIsLessOp.getValue()) {
  5947. // MinExpr = Lower;
  5948. // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
  5949. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
  5950. if (!Diff.isUsable())
  5951. return std::make_pair(nullptr, nullptr);
  5952. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5953. if (!Diff.isUsable())
  5954. return std::make_pair(nullptr, nullptr);
  5955. MaxExpr = Diff.get();
  5956. } else {
  5957. // MaxExpr = Upper;
  5958. // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
  5959. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
  5960. if (!Diff.isUsable())
  5961. return std::make_pair(nullptr, nullptr);
  5962. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5963. if (!Diff.isUsable())
  5964. return std::make_pair(nullptr, nullptr);
  5965. MinExpr = Diff.get();
  5966. }
  5967. return std::make_pair(MinExpr, MaxExpr);
  5968. }
  5969. Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
  5970. if (InitDependOnLC || CondDependOnLC)
  5971. return Condition;
  5972. return nullptr;
  5973. }
  5974. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  5975. Scope *S, Expr *Cond,
  5976. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5977. // Do not build a precondition when the condition/initialization is dependent
  5978. // to prevent pessimistic early loop exit.
  5979. // TODO: this can be improved by calculating min/max values but not sure that
  5980. // it will be very effective.
  5981. if (CondDependOnLC || InitDependOnLC)
  5982. return SemaRef.PerformImplicitConversion(
  5983. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
  5984. SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5985. /*AllowExplicit=*/true).get();
  5986. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  5987. Sema::TentativeAnalysisScope Trap(SemaRef);
  5988. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  5989. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  5990. if (!NewLB.isUsable() || !NewUB.isUsable())
  5991. return nullptr;
  5992. ExprResult CondExpr =
  5993. SemaRef.BuildBinOp(S, DefaultLoc,
  5994. TestIsLessOp.getValue() ?
  5995. (TestIsStrictOp ? BO_LT : BO_LE) :
  5996. (TestIsStrictOp ? BO_GT : BO_GE),
  5997. NewLB.get(), NewUB.get());
  5998. if (CondExpr.isUsable()) {
  5999. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  6000. SemaRef.Context.BoolTy))
  6001. CondExpr = SemaRef.PerformImplicitConversion(
  6002. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  6003. /*AllowExplicit=*/true);
  6004. }
  6005. // Otherwise use original loop condition and evaluate it in runtime.
  6006. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  6007. }
  6008. /// Build reference expression to the counter be used for codegen.
  6009. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  6010. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  6011. DSAStackTy &DSA) const {
  6012. auto *VD = dyn_cast<VarDecl>(LCDecl);
  6013. if (!VD) {
  6014. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  6015. DeclRefExpr *Ref = buildDeclRefExpr(
  6016. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  6017. const DSAStackTy::DSAVarData Data =
  6018. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  6019. // If the loop control decl is explicitly marked as private, do not mark it
  6020. // as captured again.
  6021. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  6022. Captures.insert(std::make_pair(LCRef, Ref));
  6023. return Ref;
  6024. }
  6025. return cast<DeclRefExpr>(LCRef);
  6026. }
  6027. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  6028. if (LCDecl && !LCDecl->isInvalidDecl()) {
  6029. QualType Type = LCDecl->getType().getNonReferenceType();
  6030. VarDecl *PrivateVar = buildVarDecl(
  6031. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  6032. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  6033. isa<VarDecl>(LCDecl)
  6034. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  6035. : nullptr);
  6036. if (PrivateVar->isInvalidDecl())
  6037. return nullptr;
  6038. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  6039. }
  6040. return nullptr;
  6041. }
  6042. /// Build initialization of the counter to be used for codegen.
  6043. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  6044. /// Build step of the counter be used for codegen.
  6045. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  6046. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  6047. Scope *S, Expr *Counter,
  6048. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  6049. Expr *Inc, OverloadedOperatorKind OOK) {
  6050. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  6051. if (!Cnt)
  6052. return nullptr;
  6053. if (Inc) {
  6054. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  6055. "Expected only + or - operations for depend clauses.");
  6056. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  6057. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  6058. if (!Cnt)
  6059. return nullptr;
  6060. }
  6061. ExprResult Diff;
  6062. QualType VarType = LCDecl->getType().getNonReferenceType();
  6063. if (VarType->isIntegerType() || VarType->isPointerType() ||
  6064. SemaRef.getLangOpts().CPlusPlus) {
  6065. // Upper - Lower
  6066. Expr *Upper = TestIsLessOp.getValue()
  6067. ? Cnt
  6068. : tryBuildCapture(SemaRef, UB, Captures).get();
  6069. Expr *Lower = TestIsLessOp.getValue()
  6070. ? tryBuildCapture(SemaRef, LB, Captures).get()
  6071. : Cnt;
  6072. if (!Upper || !Lower)
  6073. return nullptr;
  6074. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  6075. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  6076. // BuildBinOp already emitted error, this one is to point user to upper
  6077. // and lower bound, and to tell what is passed to 'operator-'.
  6078. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  6079. << Upper->getSourceRange() << Lower->getSourceRange();
  6080. return nullptr;
  6081. }
  6082. }
  6083. if (!Diff.isUsable())
  6084. return nullptr;
  6085. // Parentheses (for dumping/debugging purposes only).
  6086. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  6087. if (!Diff.isUsable())
  6088. return nullptr;
  6089. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  6090. if (!NewStep.isUsable())
  6091. return nullptr;
  6092. // (Upper - Lower) / Step
  6093. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  6094. if (!Diff.isUsable())
  6095. return nullptr;
  6096. return Diff.get();
  6097. }
  6098. } // namespace
  6099. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  6100. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  6101. assert(Init && "Expected loop in canonical form.");
  6102. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  6103. if (AssociatedLoops > 0 &&
  6104. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  6105. DSAStack->loopStart();
  6106. OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
  6107. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  6108. if (ValueDecl *D = ISC.getLoopDecl()) {
  6109. auto *VD = dyn_cast<VarDecl>(D);
  6110. DeclRefExpr *PrivateRef = nullptr;
  6111. if (!VD) {
  6112. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  6113. VD = Private;
  6114. } else {
  6115. PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  6116. /*WithInit=*/false);
  6117. VD = cast<VarDecl>(PrivateRef->getDecl());
  6118. }
  6119. }
  6120. DSAStack->addLoopControlVariable(D, VD);
  6121. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  6122. if (LD != D->getCanonicalDecl()) {
  6123. DSAStack->resetPossibleLoopCounter();
  6124. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  6125. MarkDeclarationsReferencedInExpr(
  6126. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  6127. Var->getType().getNonLValueExprType(Context),
  6128. ForLoc, /*RefersToCapture=*/true));
  6129. }
  6130. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  6131. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
  6132. // Referenced in a Construct, C/C++]. The loop iteration variable in the
  6133. // associated for-loop of a simd construct with just one associated
  6134. // for-loop may be listed in a linear clause with a constant-linear-step
  6135. // that is the increment of the associated for-loop. The loop iteration
  6136. // variable(s) in the associated for-loop(s) of a for or parallel for
  6137. // construct may be listed in a private or lastprivate clause.
  6138. DSAStackTy::DSAVarData DVar =
  6139. DSAStack->getTopDSA(D, /*FromParent=*/false);
  6140. // If LoopVarRefExpr is nullptr it means the corresponding loop variable
  6141. // is declared in the loop and it is predetermined as a private.
  6142. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  6143. OpenMPClauseKind PredeterminedCKind =
  6144. isOpenMPSimdDirective(DKind)
  6145. ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
  6146. : OMPC_private;
  6147. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6148. DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
  6149. (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
  6150. DVar.CKind != OMPC_private))) ||
  6151. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  6152. DKind == OMPD_master_taskloop ||
  6153. DKind == OMPD_parallel_master_taskloop ||
  6154. isOpenMPDistributeDirective(DKind)) &&
  6155. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6156. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  6157. (DVar.CKind != OMPC_private || DVar.RefExpr)) {
  6158. Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  6159. << getOpenMPClauseName(DVar.CKind)
  6160. << getOpenMPDirectiveName(DKind)
  6161. << getOpenMPClauseName(PredeterminedCKind);
  6162. if (DVar.RefExpr == nullptr)
  6163. DVar.CKind = PredeterminedCKind;
  6164. reportOriginalDsa(*this, DSAStack, D, DVar,
  6165. /*IsLoopIterVar=*/true);
  6166. } else if (LoopDeclRefExpr) {
  6167. // Make the loop iteration variable private (for worksharing
  6168. // constructs), linear (for simd directives with the only one
  6169. // associated loop) or lastprivate (for simd directives with several
  6170. // collapsed or ordered loops).
  6171. if (DVar.CKind == OMPC_unknown)
  6172. DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
  6173. PrivateRef);
  6174. }
  6175. }
  6176. }
  6177. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  6178. }
  6179. }
  6180. /// Called on a for stmt to check and extract its iteration space
  6181. /// for further processing (such as collapsing).
  6182. static bool checkOpenMPIterationSpace(
  6183. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  6184. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  6185. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  6186. Expr *OrderedLoopCountExpr,
  6187. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6188. llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
  6189. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6190. // OpenMP [2.9.1, Canonical Loop Form]
  6191. // for (init-expr; test-expr; incr-expr) structured-block
  6192. // for (range-decl: range-expr) structured-block
  6193. auto *For = dyn_cast_or_null<ForStmt>(S);
  6194. auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
  6195. // Ranged for is supported only in OpenMP 5.0.
  6196. if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
  6197. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  6198. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  6199. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  6200. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  6201. if (TotalNestedLoopCount > 1) {
  6202. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  6203. SemaRef.Diag(DSA.getConstructLoc(),
  6204. diag::note_omp_collapse_ordered_expr)
  6205. << 2 << CollapseLoopCountExpr->getSourceRange()
  6206. << OrderedLoopCountExpr->getSourceRange();
  6207. else if (CollapseLoopCountExpr)
  6208. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6209. diag::note_omp_collapse_ordered_expr)
  6210. << 0 << CollapseLoopCountExpr->getSourceRange();
  6211. else
  6212. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6213. diag::note_omp_collapse_ordered_expr)
  6214. << 1 << OrderedLoopCountExpr->getSourceRange();
  6215. }
  6216. return true;
  6217. }
  6218. assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
  6219. "No loop body.");
  6220. OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
  6221. For ? For->getForLoc() : CXXFor->getForLoc());
  6222. // Check init.
  6223. Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
  6224. if (ISC.checkAndSetInit(Init))
  6225. return true;
  6226. bool HasErrors = false;
  6227. // Check loop variable's type.
  6228. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  6229. // OpenMP [2.6, Canonical Loop Form]
  6230. // Var is one of the following:
  6231. // A variable of signed or unsigned integer type.
  6232. // For C++, a variable of a random access iterator type.
  6233. // For C, a variable of a pointer type.
  6234. QualType VarType = LCDecl->getType().getNonReferenceType();
  6235. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  6236. !VarType->isPointerType() &&
  6237. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  6238. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  6239. << SemaRef.getLangOpts().CPlusPlus;
  6240. HasErrors = true;
  6241. }
  6242. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  6243. // a Construct
  6244. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  6245. // parallel for construct is (are) private.
  6246. // The loop iteration variable in the associated for-loop of a simd
  6247. // construct with just one associated for-loop is linear with a
  6248. // constant-linear-step that is the increment of the associated for-loop.
  6249. // Exclude loop var from the list of variables with implicitly defined data
  6250. // sharing attributes.
  6251. VarsWithImplicitDSA.erase(LCDecl);
  6252. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  6253. // Check test-expr.
  6254. HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
  6255. // Check incr-expr.
  6256. HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
  6257. }
  6258. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  6259. return HasErrors;
  6260. // Build the loop's iteration space representation.
  6261. ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
  6262. DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
  6263. ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
  6264. ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
  6265. (isOpenMPWorksharingDirective(DKind) ||
  6266. isOpenMPTaskLoopDirective(DKind) ||
  6267. isOpenMPDistributeDirective(DKind)),
  6268. Captures);
  6269. ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
  6270. ISC.buildCounterVar(Captures, DSA);
  6271. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
  6272. ISC.buildPrivateCounterVar();
  6273. ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
  6274. ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
  6275. ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
  6276. ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
  6277. ISC.getConditionSrcRange();
  6278. ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
  6279. ISC.getIncrementSrcRange();
  6280. ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
  6281. ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
  6282. ISC.isStrictTestOp();
  6283. std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
  6284. ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
  6285. ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
  6286. ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
  6287. ISC.buildFinalCondition(DSA.getCurScope());
  6288. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
  6289. ISC.doesInitDependOnLC();
  6290. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
  6291. ISC.doesCondDependOnLC();
  6292. ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
  6293. ISC.getLoopDependentIdx();
  6294. HasErrors |=
  6295. (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
  6296. ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
  6297. ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
  6298. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
  6299. ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
  6300. ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
  6301. if (!HasErrors && DSA.isOrderedRegion()) {
  6302. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  6303. if (CurrentNestedLoopCount <
  6304. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  6305. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  6306. CurrentNestedLoopCount,
  6307. ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
  6308. DSA.getOrderedRegionParam().second->setLoopCounter(
  6309. CurrentNestedLoopCount,
  6310. ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
  6311. }
  6312. }
  6313. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  6314. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  6315. // Erroneous case - clause has some problems.
  6316. continue;
  6317. }
  6318. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  6319. Pair.second.size() <= CurrentNestedLoopCount) {
  6320. // Erroneous case - clause has some problems.
  6321. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  6322. continue;
  6323. }
  6324. Expr *CntValue;
  6325. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  6326. CntValue = ISC.buildOrderedLoopData(
  6327. DSA.getCurScope(),
  6328. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6329. Pair.first->getDependencyLoc());
  6330. else
  6331. CntValue = ISC.buildOrderedLoopData(
  6332. DSA.getCurScope(),
  6333. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6334. Pair.first->getDependencyLoc(),
  6335. Pair.second[CurrentNestedLoopCount].first,
  6336. Pair.second[CurrentNestedLoopCount].second);
  6337. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  6338. }
  6339. }
  6340. return HasErrors;
  6341. }
  6342. /// Build 'VarRef = Start.
  6343. static ExprResult
  6344. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6345. ExprResult Start, bool IsNonRectangularLB,
  6346. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6347. // Build 'VarRef = Start.
  6348. ExprResult NewStart = IsNonRectangularLB
  6349. ? Start.get()
  6350. : tryBuildCapture(SemaRef, Start.get(), Captures);
  6351. if (!NewStart.isUsable())
  6352. return ExprError();
  6353. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  6354. VarRef.get()->getType())) {
  6355. NewStart = SemaRef.PerformImplicitConversion(
  6356. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  6357. /*AllowExplicit=*/true);
  6358. if (!NewStart.isUsable())
  6359. return ExprError();
  6360. }
  6361. ExprResult Init =
  6362. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6363. return Init;
  6364. }
  6365. /// Build 'VarRef = Start + Iter * Step'.
  6366. static ExprResult buildCounterUpdate(
  6367. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6368. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  6369. bool IsNonRectangularLB,
  6370. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  6371. // Add parentheses (for debugging purposes only).
  6372. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  6373. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  6374. !Step.isUsable())
  6375. return ExprError();
  6376. ExprResult NewStep = Step;
  6377. if (Captures)
  6378. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  6379. if (NewStep.isInvalid())
  6380. return ExprError();
  6381. ExprResult Update =
  6382. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  6383. if (!Update.isUsable())
  6384. return ExprError();
  6385. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  6386. // 'VarRef = Start (+|-) Iter * Step'.
  6387. if (!Start.isUsable())
  6388. return ExprError();
  6389. ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
  6390. if (!NewStart.isUsable())
  6391. return ExprError();
  6392. if (Captures && !IsNonRectangularLB)
  6393. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  6394. if (NewStart.isInvalid())
  6395. return ExprError();
  6396. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  6397. ExprResult SavedUpdate = Update;
  6398. ExprResult UpdateVal;
  6399. if (VarRef.get()->getType()->isOverloadableType() ||
  6400. NewStart.get()->getType()->isOverloadableType() ||
  6401. Update.get()->getType()->isOverloadableType()) {
  6402. Sema::TentativeAnalysisScope Trap(SemaRef);
  6403. Update =
  6404. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6405. if (Update.isUsable()) {
  6406. UpdateVal =
  6407. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  6408. VarRef.get(), SavedUpdate.get());
  6409. if (UpdateVal.isUsable()) {
  6410. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  6411. UpdateVal.get());
  6412. }
  6413. }
  6414. }
  6415. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  6416. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  6417. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  6418. NewStart.get(), SavedUpdate.get());
  6419. if (!Update.isUsable())
  6420. return ExprError();
  6421. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  6422. VarRef.get()->getType())) {
  6423. Update = SemaRef.PerformImplicitConversion(
  6424. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  6425. if (!Update.isUsable())
  6426. return ExprError();
  6427. }
  6428. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  6429. }
  6430. return Update;
  6431. }
  6432. /// Convert integer expression \a E to make it have at least \a Bits
  6433. /// bits.
  6434. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  6435. if (E == nullptr)
  6436. return ExprError();
  6437. ASTContext &C = SemaRef.Context;
  6438. QualType OldType = E->getType();
  6439. unsigned HasBits = C.getTypeSize(OldType);
  6440. if (HasBits >= Bits)
  6441. return ExprResult(E);
  6442. // OK to convert to signed, because new type has more bits than old.
  6443. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  6444. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  6445. true);
  6446. }
  6447. /// Check if the given expression \a E is a constant integer that fits
  6448. /// into \a Bits bits.
  6449. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  6450. if (E == nullptr)
  6451. return false;
  6452. llvm::APSInt Result;
  6453. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  6454. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  6455. return false;
  6456. }
  6457. /// Build preinits statement for the given declarations.
  6458. static Stmt *buildPreInits(ASTContext &Context,
  6459. MutableArrayRef<Decl *> PreInits) {
  6460. if (!PreInits.empty()) {
  6461. return new (Context) DeclStmt(
  6462. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  6463. SourceLocation(), SourceLocation());
  6464. }
  6465. return nullptr;
  6466. }
  6467. /// Build preinits statement for the given declarations.
  6468. static Stmt *
  6469. buildPreInits(ASTContext &Context,
  6470. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6471. if (!Captures.empty()) {
  6472. SmallVector<Decl *, 16> PreInits;
  6473. for (const auto &Pair : Captures)
  6474. PreInits.push_back(Pair.second->getDecl());
  6475. return buildPreInits(Context, PreInits);
  6476. }
  6477. return nullptr;
  6478. }
  6479. /// Build postupdate expression for the given list of postupdates expressions.
  6480. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  6481. Expr *PostUpdate = nullptr;
  6482. if (!PostUpdates.empty()) {
  6483. for (Expr *E : PostUpdates) {
  6484. Expr *ConvE = S.BuildCStyleCastExpr(
  6485. E->getExprLoc(),
  6486. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  6487. E->getExprLoc(), E)
  6488. .get();
  6489. PostUpdate = PostUpdate
  6490. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  6491. PostUpdate, ConvE)
  6492. .get()
  6493. : ConvE;
  6494. }
  6495. }
  6496. return PostUpdate;
  6497. }
  6498. /// Called on a for stmt to check itself and nested loops (if any).
  6499. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  6500. /// number of collapsed loops otherwise.
  6501. static unsigned
  6502. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  6503. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  6504. DSAStackTy &DSA,
  6505. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6506. OMPLoopDirective::HelperExprs &Built) {
  6507. unsigned NestedLoopCount = 1;
  6508. if (CollapseLoopCountExpr) {
  6509. // Found 'collapse' clause - calculate collapse number.
  6510. Expr::EvalResult Result;
  6511. if (!CollapseLoopCountExpr->isValueDependent() &&
  6512. CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  6513. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  6514. } else {
  6515. Built.clear(/*Size=*/1);
  6516. return 1;
  6517. }
  6518. }
  6519. unsigned OrderedLoopCount = 1;
  6520. if (OrderedLoopCountExpr) {
  6521. // Found 'ordered' clause - calculate collapse number.
  6522. Expr::EvalResult EVResult;
  6523. if (!OrderedLoopCountExpr->isValueDependent() &&
  6524. OrderedLoopCountExpr->EvaluateAsInt(EVResult,
  6525. SemaRef.getASTContext())) {
  6526. llvm::APSInt Result = EVResult.Val.getInt();
  6527. if (Result.getLimitedValue() < NestedLoopCount) {
  6528. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6529. diag::err_omp_wrong_ordered_loop_count)
  6530. << OrderedLoopCountExpr->getSourceRange();
  6531. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6532. diag::note_collapse_loop_count)
  6533. << CollapseLoopCountExpr->getSourceRange();
  6534. }
  6535. OrderedLoopCount = Result.getLimitedValue();
  6536. } else {
  6537. Built.clear(/*Size=*/1);
  6538. return 1;
  6539. }
  6540. }
  6541. // This is helper routine for loop directives (e.g., 'for', 'simd',
  6542. // 'for simd', etc.).
  6543. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  6544. SmallVector<LoopIterationSpace, 4> IterSpaces(
  6545. std::max(OrderedLoopCount, NestedLoopCount));
  6546. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  6547. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6548. if (checkOpenMPIterationSpace(
  6549. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6550. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6551. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6552. return 0;
  6553. // Move on to the next nested for loop, or to the loop body.
  6554. // OpenMP [2.8.1, simd construct, Restrictions]
  6555. // All loops associated with the construct must be perfectly nested; that
  6556. // is, there must be no intervening code nor any OpenMP directive between
  6557. // any two loops.
  6558. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  6559. CurStmt = For->getBody();
  6560. } else {
  6561. assert(isa<CXXForRangeStmt>(CurStmt) &&
  6562. "Expected canonical for or range-based for loops.");
  6563. CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
  6564. }
  6565. CurStmt = CurStmt->IgnoreContainers();
  6566. }
  6567. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  6568. if (checkOpenMPIterationSpace(
  6569. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6570. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6571. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6572. return 0;
  6573. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  6574. // Handle initialization of captured loop iterator variables.
  6575. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  6576. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  6577. Captures[DRE] = DRE;
  6578. }
  6579. }
  6580. // Move on to the next nested for loop, or to the loop body.
  6581. // OpenMP [2.8.1, simd construct, Restrictions]
  6582. // All loops associated with the construct must be perfectly nested; that
  6583. // is, there must be no intervening code nor any OpenMP directive between
  6584. // any two loops.
  6585. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  6586. CurStmt = For->getBody();
  6587. } else {
  6588. assert(isa<CXXForRangeStmt>(CurStmt) &&
  6589. "Expected canonical for or range-based for loops.");
  6590. CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
  6591. }
  6592. CurStmt = CurStmt->IgnoreContainers();
  6593. }
  6594. Built.clear(/* size */ NestedLoopCount);
  6595. if (SemaRef.CurContext->isDependentContext())
  6596. return NestedLoopCount;
  6597. // An example of what is generated for the following code:
  6598. //
  6599. // #pragma omp simd collapse(2) ordered(2)
  6600. // for (i = 0; i < NI; ++i)
  6601. // for (k = 0; k < NK; ++k)
  6602. // for (j = J0; j < NJ; j+=2) {
  6603. // <loop body>
  6604. // }
  6605. //
  6606. // We generate the code below.
  6607. // Note: the loop body may be outlined in CodeGen.
  6608. // Note: some counters may be C++ classes, operator- is used to find number of
  6609. // iterations and operator+= to calculate counter value.
  6610. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  6611. // or i64 is currently supported).
  6612. //
  6613. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  6614. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  6615. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  6616. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  6617. // // similar updates for vars in clauses (e.g. 'linear')
  6618. // <loop body (using local i and j)>
  6619. // }
  6620. // i = NI; // assign final values of counters
  6621. // j = NJ;
  6622. //
  6623. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  6624. // the iteration counts of the collapsed for loops.
  6625. // Precondition tests if there is at least one iteration (all conditions are
  6626. // true).
  6627. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  6628. Expr *N0 = IterSpaces[0].NumIterations;
  6629. ExprResult LastIteration32 =
  6630. widenIterationCount(/*Bits=*/32,
  6631. SemaRef
  6632. .PerformImplicitConversion(
  6633. N0->IgnoreImpCasts(), N0->getType(),
  6634. Sema::AA_Converting, /*AllowExplicit=*/true)
  6635. .get(),
  6636. SemaRef);
  6637. ExprResult LastIteration64 = widenIterationCount(
  6638. /*Bits=*/64,
  6639. SemaRef
  6640. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  6641. Sema::AA_Converting,
  6642. /*AllowExplicit=*/true)
  6643. .get(),
  6644. SemaRef);
  6645. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  6646. return NestedLoopCount;
  6647. ASTContext &C = SemaRef.Context;
  6648. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  6649. Scope *CurScope = DSA.getCurScope();
  6650. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  6651. if (PreCond.isUsable()) {
  6652. PreCond =
  6653. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  6654. PreCond.get(), IterSpaces[Cnt].PreCond);
  6655. }
  6656. Expr *N = IterSpaces[Cnt].NumIterations;
  6657. SourceLocation Loc = N->getExprLoc();
  6658. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  6659. if (LastIteration32.isUsable())
  6660. LastIteration32 = SemaRef.BuildBinOp(
  6661. CurScope, Loc, BO_Mul, LastIteration32.get(),
  6662. SemaRef
  6663. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6664. Sema::AA_Converting,
  6665. /*AllowExplicit=*/true)
  6666. .get());
  6667. if (LastIteration64.isUsable())
  6668. LastIteration64 = SemaRef.BuildBinOp(
  6669. CurScope, Loc, BO_Mul, LastIteration64.get(),
  6670. SemaRef
  6671. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6672. Sema::AA_Converting,
  6673. /*AllowExplicit=*/true)
  6674. .get());
  6675. }
  6676. // Choose either the 32-bit or 64-bit version.
  6677. ExprResult LastIteration = LastIteration64;
  6678. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  6679. (LastIteration32.isUsable() &&
  6680. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  6681. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  6682. fitsInto(
  6683. /*Bits=*/32,
  6684. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  6685. LastIteration64.get(), SemaRef))))
  6686. LastIteration = LastIteration32;
  6687. QualType VType = LastIteration.get()->getType();
  6688. QualType RealVType = VType;
  6689. QualType StrideVType = VType;
  6690. if (isOpenMPTaskLoopDirective(DKind)) {
  6691. VType =
  6692. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  6693. StrideVType =
  6694. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  6695. }
  6696. if (!LastIteration.isUsable())
  6697. return 0;
  6698. // Save the number of iterations.
  6699. ExprResult NumIterations = LastIteration;
  6700. {
  6701. LastIteration = SemaRef.BuildBinOp(
  6702. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  6703. LastIteration.get(),
  6704. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6705. if (!LastIteration.isUsable())
  6706. return 0;
  6707. }
  6708. // Calculate the last iteration number beforehand instead of doing this on
  6709. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  6710. llvm::APSInt Result;
  6711. bool IsConstant =
  6712. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  6713. ExprResult CalcLastIteration;
  6714. if (!IsConstant) {
  6715. ExprResult SaveRef =
  6716. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  6717. LastIteration = SaveRef;
  6718. // Prepare SaveRef + 1.
  6719. NumIterations = SemaRef.BuildBinOp(
  6720. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  6721. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6722. if (!NumIterations.isUsable())
  6723. return 0;
  6724. }
  6725. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  6726. // Build variables passed into runtime, necessary for worksharing directives.
  6727. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  6728. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6729. isOpenMPDistributeDirective(DKind)) {
  6730. // Lower bound variable, initialized with zero.
  6731. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  6732. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  6733. SemaRef.AddInitializerToDecl(LBDecl,
  6734. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6735. /*DirectInit*/ false);
  6736. // Upper bound variable, initialized with last iteration number.
  6737. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  6738. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  6739. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  6740. /*DirectInit*/ false);
  6741. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  6742. // This will be used to implement clause 'lastprivate'.
  6743. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  6744. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  6745. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  6746. SemaRef.AddInitializerToDecl(ILDecl,
  6747. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6748. /*DirectInit*/ false);
  6749. // Stride variable returned by runtime (we initialize it to 1 by default).
  6750. VarDecl *STDecl =
  6751. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  6752. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  6753. SemaRef.AddInitializerToDecl(STDecl,
  6754. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  6755. /*DirectInit*/ false);
  6756. // Build expression: UB = min(UB, LastIteration)
  6757. // It is necessary for CodeGen of directives with static scheduling.
  6758. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  6759. UB.get(), LastIteration.get());
  6760. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6761. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  6762. LastIteration.get(), UB.get());
  6763. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  6764. CondOp.get());
  6765. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  6766. // If we have a combined directive that combines 'distribute', 'for' or
  6767. // 'simd' we need to be able to access the bounds of the schedule of the
  6768. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  6769. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  6770. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6771. // Lower bound variable, initialized with zero.
  6772. VarDecl *CombLBDecl =
  6773. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  6774. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  6775. SemaRef.AddInitializerToDecl(
  6776. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6777. /*DirectInit*/ false);
  6778. // Upper bound variable, initialized with last iteration number.
  6779. VarDecl *CombUBDecl =
  6780. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  6781. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  6782. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  6783. /*DirectInit*/ false);
  6784. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  6785. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  6786. ExprResult CombCondOp =
  6787. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  6788. LastIteration.get(), CombUB.get());
  6789. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  6790. CombCondOp.get());
  6791. CombEUB =
  6792. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  6793. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  6794. // We expect to have at least 2 more parameters than the 'parallel'
  6795. // directive does - the lower and upper bounds of the previous schedule.
  6796. assert(CD->getNumParams() >= 4 &&
  6797. "Unexpected number of parameters in loop combined directive");
  6798. // Set the proper type for the bounds given what we learned from the
  6799. // enclosed loops.
  6800. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  6801. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  6802. // Previous lower and upper bounds are obtained from the region
  6803. // parameters.
  6804. PrevLB =
  6805. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  6806. PrevUB =
  6807. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  6808. }
  6809. }
  6810. // Build the iteration variable and its initialization before loop.
  6811. ExprResult IV;
  6812. ExprResult Init, CombInit;
  6813. {
  6814. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  6815. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  6816. Expr *RHS =
  6817. (isOpenMPWorksharingDirective(DKind) ||
  6818. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6819. ? LB.get()
  6820. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6821. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  6822. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  6823. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6824. Expr *CombRHS =
  6825. (isOpenMPWorksharingDirective(DKind) ||
  6826. isOpenMPTaskLoopDirective(DKind) ||
  6827. isOpenMPDistributeDirective(DKind))
  6828. ? CombLB.get()
  6829. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6830. CombInit =
  6831. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  6832. CombInit =
  6833. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  6834. }
  6835. }
  6836. bool UseStrictCompare =
  6837. RealVType->hasUnsignedIntegerRepresentation() &&
  6838. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  6839. return LIS.IsStrictCompare;
  6840. });
  6841. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  6842. // unsigned IV)) for worksharing loops.
  6843. SourceLocation CondLoc = AStmt->getBeginLoc();
  6844. Expr *BoundUB = UB.get();
  6845. if (UseStrictCompare) {
  6846. BoundUB =
  6847. SemaRef
  6848. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  6849. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6850. .get();
  6851. BoundUB =
  6852. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  6853. }
  6854. ExprResult Cond =
  6855. (isOpenMPWorksharingDirective(DKind) ||
  6856. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6857. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  6858. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  6859. BoundUB)
  6860. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6861. NumIterations.get());
  6862. ExprResult CombDistCond;
  6863. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6864. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6865. NumIterations.get());
  6866. }
  6867. ExprResult CombCond;
  6868. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6869. Expr *BoundCombUB = CombUB.get();
  6870. if (UseStrictCompare) {
  6871. BoundCombUB =
  6872. SemaRef
  6873. .BuildBinOp(
  6874. CurScope, CondLoc, BO_Add, BoundCombUB,
  6875. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6876. .get();
  6877. BoundCombUB =
  6878. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  6879. .get();
  6880. }
  6881. CombCond =
  6882. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6883. IV.get(), BoundCombUB);
  6884. }
  6885. // Loop increment (IV = IV + 1)
  6886. SourceLocation IncLoc = AStmt->getBeginLoc();
  6887. ExprResult Inc =
  6888. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  6889. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  6890. if (!Inc.isUsable())
  6891. return 0;
  6892. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  6893. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  6894. if (!Inc.isUsable())
  6895. return 0;
  6896. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  6897. // Used for directives with static scheduling.
  6898. // In combined construct, add combined version that use CombLB and CombUB
  6899. // base variables for the update
  6900. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  6901. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6902. isOpenMPDistributeDirective(DKind)) {
  6903. // LB + ST
  6904. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  6905. if (!NextLB.isUsable())
  6906. return 0;
  6907. // LB = LB + ST
  6908. NextLB =
  6909. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  6910. NextLB =
  6911. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  6912. if (!NextLB.isUsable())
  6913. return 0;
  6914. // UB + ST
  6915. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  6916. if (!NextUB.isUsable())
  6917. return 0;
  6918. // UB = UB + ST
  6919. NextUB =
  6920. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  6921. NextUB =
  6922. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  6923. if (!NextUB.isUsable())
  6924. return 0;
  6925. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6926. CombNextLB =
  6927. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  6928. if (!NextLB.isUsable())
  6929. return 0;
  6930. // LB = LB + ST
  6931. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  6932. CombNextLB.get());
  6933. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  6934. /*DiscardedValue*/ false);
  6935. if (!CombNextLB.isUsable())
  6936. return 0;
  6937. // UB + ST
  6938. CombNextUB =
  6939. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  6940. if (!CombNextUB.isUsable())
  6941. return 0;
  6942. // UB = UB + ST
  6943. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  6944. CombNextUB.get());
  6945. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  6946. /*DiscardedValue*/ false);
  6947. if (!CombNextUB.isUsable())
  6948. return 0;
  6949. }
  6950. }
  6951. // Create increment expression for distribute loop when combined in a same
  6952. // directive with for as IV = IV + ST; ensure upper bound expression based
  6953. // on PrevUB instead of NumIterations - used to implement 'for' when found
  6954. // in combination with 'distribute', like in 'distribute parallel for'
  6955. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  6956. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  6957. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6958. DistCond = SemaRef.BuildBinOp(
  6959. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  6960. assert(DistCond.isUsable() && "distribute cond expr was not built");
  6961. DistInc =
  6962. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  6963. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6964. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  6965. DistInc.get());
  6966. DistInc =
  6967. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  6968. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6969. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  6970. // construct
  6971. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  6972. ExprResult IsUBGreater =
  6973. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  6974. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6975. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  6976. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  6977. CondOp.get());
  6978. PrevEUB =
  6979. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  6980. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  6981. // parallel for is in combination with a distribute directive with
  6982. // schedule(static, 1)
  6983. Expr *BoundPrevUB = PrevUB.get();
  6984. if (UseStrictCompare) {
  6985. BoundPrevUB =
  6986. SemaRef
  6987. .BuildBinOp(
  6988. CurScope, CondLoc, BO_Add, BoundPrevUB,
  6989. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6990. .get();
  6991. BoundPrevUB =
  6992. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  6993. .get();
  6994. }
  6995. ParForInDistCond =
  6996. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6997. IV.get(), BoundPrevUB);
  6998. }
  6999. // Build updates and final values of the loop counters.
  7000. bool HasErrors = false;
  7001. Built.Counters.resize(NestedLoopCount);
  7002. Built.Inits.resize(NestedLoopCount);
  7003. Built.Updates.resize(NestedLoopCount);
  7004. Built.Finals.resize(NestedLoopCount);
  7005. Built.DependentCounters.resize(NestedLoopCount);
  7006. Built.DependentInits.resize(NestedLoopCount);
  7007. Built.FinalsConditions.resize(NestedLoopCount);
  7008. {
  7009. // We implement the following algorithm for obtaining the
  7010. // original loop iteration variable values based on the
  7011. // value of the collapsed loop iteration variable IV.
  7012. //
  7013. // Let n+1 be the number of collapsed loops in the nest.
  7014. // Iteration variables (I0, I1, .... In)
  7015. // Iteration counts (N0, N1, ... Nn)
  7016. //
  7017. // Acc = IV;
  7018. //
  7019. // To compute Ik for loop k, 0 <= k <= n, generate:
  7020. // Prod = N(k+1) * N(k+2) * ... * Nn;
  7021. // Ik = Acc / Prod;
  7022. // Acc -= Ik * Prod;
  7023. //
  7024. ExprResult Acc = IV;
  7025. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  7026. LoopIterationSpace &IS = IterSpaces[Cnt];
  7027. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  7028. ExprResult Iter;
  7029. // Compute prod
  7030. ExprResult Prod =
  7031. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  7032. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  7033. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  7034. IterSpaces[K].NumIterations);
  7035. // Iter = Acc / Prod
  7036. // If there is at least one more inner loop to avoid
  7037. // multiplication by 1.
  7038. if (Cnt + 1 < NestedLoopCount)
  7039. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  7040. Acc.get(), Prod.get());
  7041. else
  7042. Iter = Acc;
  7043. if (!Iter.isUsable()) {
  7044. HasErrors = true;
  7045. break;
  7046. }
  7047. // Update Acc:
  7048. // Acc -= Iter * Prod
  7049. // Check if there is at least one more inner loop to avoid
  7050. // multiplication by 1.
  7051. if (Cnt + 1 < NestedLoopCount)
  7052. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  7053. Iter.get(), Prod.get());
  7054. else
  7055. Prod = Iter;
  7056. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  7057. Acc.get(), Prod.get());
  7058. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  7059. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  7060. DeclRefExpr *CounterVar = buildDeclRefExpr(
  7061. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  7062. /*RefersToCapture=*/true);
  7063. ExprResult Init =
  7064. buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  7065. IS.CounterInit, IS.IsNonRectangularLB, Captures);
  7066. if (!Init.isUsable()) {
  7067. HasErrors = true;
  7068. break;
  7069. }
  7070. ExprResult Update = buildCounterUpdate(
  7071. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  7072. IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
  7073. if (!Update.isUsable()) {
  7074. HasErrors = true;
  7075. break;
  7076. }
  7077. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  7078. ExprResult Final =
  7079. buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  7080. IS.CounterInit, IS.NumIterations, IS.CounterStep,
  7081. IS.Subtract, IS.IsNonRectangularLB, &Captures);
  7082. if (!Final.isUsable()) {
  7083. HasErrors = true;
  7084. break;
  7085. }
  7086. if (!Update.isUsable() || !Final.isUsable()) {
  7087. HasErrors = true;
  7088. break;
  7089. }
  7090. // Save results
  7091. Built.Counters[Cnt] = IS.CounterVar;
  7092. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  7093. Built.Inits[Cnt] = Init.get();
  7094. Built.Updates[Cnt] = Update.get();
  7095. Built.Finals[Cnt] = Final.get();
  7096. Built.DependentCounters[Cnt] = nullptr;
  7097. Built.DependentInits[Cnt] = nullptr;
  7098. Built.FinalsConditions[Cnt] = nullptr;
  7099. if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
  7100. Built.DependentCounters[Cnt] =
  7101. Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7102. Built.DependentInits[Cnt] =
  7103. Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7104. Built.FinalsConditions[Cnt] = IS.FinalCondition;
  7105. }
  7106. }
  7107. }
  7108. if (HasErrors)
  7109. return 0;
  7110. // Save results
  7111. Built.IterationVarRef = IV.get();
  7112. Built.LastIteration = LastIteration.get();
  7113. Built.NumIterations = NumIterations.get();
  7114. Built.CalcLastIteration = SemaRef
  7115. .ActOnFinishFullExpr(CalcLastIteration.get(),
  7116. /*DiscardedValue=*/false)
  7117. .get();
  7118. Built.PreCond = PreCond.get();
  7119. Built.PreInits = buildPreInits(C, Captures);
  7120. Built.Cond = Cond.get();
  7121. Built.Init = Init.get();
  7122. Built.Inc = Inc.get();
  7123. Built.LB = LB.get();
  7124. Built.UB = UB.get();
  7125. Built.IL = IL.get();
  7126. Built.ST = ST.get();
  7127. Built.EUB = EUB.get();
  7128. Built.NLB = NextLB.get();
  7129. Built.NUB = NextUB.get();
  7130. Built.PrevLB = PrevLB.get();
  7131. Built.PrevUB = PrevUB.get();
  7132. Built.DistInc = DistInc.get();
  7133. Built.PrevEUB = PrevEUB.get();
  7134. Built.DistCombinedFields.LB = CombLB.get();
  7135. Built.DistCombinedFields.UB = CombUB.get();
  7136. Built.DistCombinedFields.EUB = CombEUB.get();
  7137. Built.DistCombinedFields.Init = CombInit.get();
  7138. Built.DistCombinedFields.Cond = CombCond.get();
  7139. Built.DistCombinedFields.NLB = CombNextLB.get();
  7140. Built.DistCombinedFields.NUB = CombNextUB.get();
  7141. Built.DistCombinedFields.DistCond = CombDistCond.get();
  7142. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  7143. return NestedLoopCount;
  7144. }
  7145. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7146. auto CollapseClauses =
  7147. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  7148. if (CollapseClauses.begin() != CollapseClauses.end())
  7149. return (*CollapseClauses.begin())->getNumForLoops();
  7150. return nullptr;
  7151. }
  7152. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7153. auto OrderedClauses =
  7154. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  7155. if (OrderedClauses.begin() != OrderedClauses.end())
  7156. return (*OrderedClauses.begin())->getNumForLoops();
  7157. return nullptr;
  7158. }
  7159. static bool checkSimdlenSafelenSpecified(Sema &S,
  7160. const ArrayRef<OMPClause *> Clauses) {
  7161. const OMPSafelenClause *Safelen = nullptr;
  7162. const OMPSimdlenClause *Simdlen = nullptr;
  7163. for (const OMPClause *Clause : Clauses) {
  7164. if (Clause->getClauseKind() == OMPC_safelen)
  7165. Safelen = cast<OMPSafelenClause>(Clause);
  7166. else if (Clause->getClauseKind() == OMPC_simdlen)
  7167. Simdlen = cast<OMPSimdlenClause>(Clause);
  7168. if (Safelen && Simdlen)
  7169. break;
  7170. }
  7171. if (Simdlen && Safelen) {
  7172. const Expr *SimdlenLength = Simdlen->getSimdlen();
  7173. const Expr *SafelenLength = Safelen->getSafelen();
  7174. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  7175. SimdlenLength->isInstantiationDependent() ||
  7176. SimdlenLength->containsUnexpandedParameterPack())
  7177. return false;
  7178. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  7179. SafelenLength->isInstantiationDependent() ||
  7180. SafelenLength->containsUnexpandedParameterPack())
  7181. return false;
  7182. Expr::EvalResult SimdlenResult, SafelenResult;
  7183. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  7184. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  7185. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  7186. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  7187. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  7188. // If both simdlen and safelen clauses are specified, the value of the
  7189. // simdlen parameter must be less than or equal to the value of the safelen
  7190. // parameter.
  7191. if (SimdlenRes > SafelenRes) {
  7192. S.Diag(SimdlenLength->getExprLoc(),
  7193. diag::err_omp_wrong_simdlen_safelen_values)
  7194. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  7195. return true;
  7196. }
  7197. }
  7198. return false;
  7199. }
  7200. StmtResult
  7201. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7202. SourceLocation StartLoc, SourceLocation EndLoc,
  7203. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7204. if (!AStmt)
  7205. return StmtError();
  7206. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7207. OMPLoopDirective::HelperExprs B;
  7208. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7209. // define the nested loops number.
  7210. unsigned NestedLoopCount = checkOpenMPLoop(
  7211. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7212. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7213. if (NestedLoopCount == 0)
  7214. return StmtError();
  7215. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7216. "omp simd loop exprs were not built");
  7217. if (!CurContext->isDependentContext()) {
  7218. // Finalize the clauses that need pre-built expressions for CodeGen.
  7219. for (OMPClause *C : Clauses) {
  7220. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7221. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7222. B.NumIterations, *this, CurScope,
  7223. DSAStack))
  7224. return StmtError();
  7225. }
  7226. }
  7227. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7228. return StmtError();
  7229. setFunctionHasBranchProtectedScope();
  7230. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7231. Clauses, AStmt, B);
  7232. }
  7233. StmtResult
  7234. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7235. SourceLocation StartLoc, SourceLocation EndLoc,
  7236. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7237. if (!AStmt)
  7238. return StmtError();
  7239. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7240. OMPLoopDirective::HelperExprs B;
  7241. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7242. // define the nested loops number.
  7243. unsigned NestedLoopCount = checkOpenMPLoop(
  7244. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7245. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7246. if (NestedLoopCount == 0)
  7247. return StmtError();
  7248. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7249. "omp for loop exprs were not built");
  7250. if (!CurContext->isDependentContext()) {
  7251. // Finalize the clauses that need pre-built expressions for CodeGen.
  7252. for (OMPClause *C : Clauses) {
  7253. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7254. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7255. B.NumIterations, *this, CurScope,
  7256. DSAStack))
  7257. return StmtError();
  7258. }
  7259. }
  7260. setFunctionHasBranchProtectedScope();
  7261. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7262. Clauses, AStmt, B, DSAStack->isCancelRegion());
  7263. }
  7264. StmtResult Sema::ActOnOpenMPForSimdDirective(
  7265. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7266. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7267. if (!AStmt)
  7268. return StmtError();
  7269. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7270. OMPLoopDirective::HelperExprs B;
  7271. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7272. // define the nested loops number.
  7273. unsigned NestedLoopCount =
  7274. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  7275. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7276. VarsWithImplicitDSA, B);
  7277. if (NestedLoopCount == 0)
  7278. return StmtError();
  7279. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7280. "omp for simd loop exprs were not built");
  7281. if (!CurContext->isDependentContext()) {
  7282. // Finalize the clauses that need pre-built expressions for CodeGen.
  7283. for (OMPClause *C : Clauses) {
  7284. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7285. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7286. B.NumIterations, *this, CurScope,
  7287. DSAStack))
  7288. return StmtError();
  7289. }
  7290. }
  7291. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7292. return StmtError();
  7293. setFunctionHasBranchProtectedScope();
  7294. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7295. Clauses, AStmt, B);
  7296. }
  7297. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7298. Stmt *AStmt,
  7299. SourceLocation StartLoc,
  7300. SourceLocation EndLoc) {
  7301. if (!AStmt)
  7302. return StmtError();
  7303. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7304. auto BaseStmt = AStmt;
  7305. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7306. BaseStmt = CS->getCapturedStmt();
  7307. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7308. auto S = C->children();
  7309. if (S.begin() == S.end())
  7310. return StmtError();
  7311. // All associated statements must be '#pragma omp section' except for
  7312. // the first one.
  7313. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7314. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7315. if (SectionStmt)
  7316. Diag(SectionStmt->getBeginLoc(),
  7317. diag::err_omp_sections_substmt_not_section);
  7318. return StmtError();
  7319. }
  7320. cast<OMPSectionDirective>(SectionStmt)
  7321. ->setHasCancel(DSAStack->isCancelRegion());
  7322. }
  7323. } else {
  7324. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  7325. return StmtError();
  7326. }
  7327. setFunctionHasBranchProtectedScope();
  7328. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7329. DSAStack->isCancelRegion());
  7330. }
  7331. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  7332. SourceLocation StartLoc,
  7333. SourceLocation EndLoc) {
  7334. if (!AStmt)
  7335. return StmtError();
  7336. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7337. setFunctionHasBranchProtectedScope();
  7338. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  7339. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  7340. DSAStack->isCancelRegion());
  7341. }
  7342. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  7343. Stmt *AStmt,
  7344. SourceLocation StartLoc,
  7345. SourceLocation EndLoc) {
  7346. if (!AStmt)
  7347. return StmtError();
  7348. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7349. setFunctionHasBranchProtectedScope();
  7350. // OpenMP [2.7.3, single Construct, Restrictions]
  7351. // The copyprivate clause must not be used with the nowait clause.
  7352. const OMPClause *Nowait = nullptr;
  7353. const OMPClause *Copyprivate = nullptr;
  7354. for (const OMPClause *Clause : Clauses) {
  7355. if (Clause->getClauseKind() == OMPC_nowait)
  7356. Nowait = Clause;
  7357. else if (Clause->getClauseKind() == OMPC_copyprivate)
  7358. Copyprivate = Clause;
  7359. if (Copyprivate && Nowait) {
  7360. Diag(Copyprivate->getBeginLoc(),
  7361. diag::err_omp_single_copyprivate_with_nowait);
  7362. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  7363. return StmtError();
  7364. }
  7365. }
  7366. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7367. }
  7368. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  7369. SourceLocation StartLoc,
  7370. SourceLocation EndLoc) {
  7371. if (!AStmt)
  7372. return StmtError();
  7373. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7374. setFunctionHasBranchProtectedScope();
  7375. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  7376. }
  7377. StmtResult Sema::ActOnOpenMPCriticalDirective(
  7378. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  7379. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  7380. if (!AStmt)
  7381. return StmtError();
  7382. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7383. bool ErrorFound = false;
  7384. llvm::APSInt Hint;
  7385. SourceLocation HintLoc;
  7386. bool DependentHint = false;
  7387. for (const OMPClause *C : Clauses) {
  7388. if (C->getClauseKind() == OMPC_hint) {
  7389. if (!DirName.getName()) {
  7390. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  7391. ErrorFound = true;
  7392. }
  7393. Expr *E = cast<OMPHintClause>(C)->getHint();
  7394. if (E->isTypeDependent() || E->isValueDependent() ||
  7395. E->isInstantiationDependent()) {
  7396. DependentHint = true;
  7397. } else {
  7398. Hint = E->EvaluateKnownConstInt(Context);
  7399. HintLoc = C->getBeginLoc();
  7400. }
  7401. }
  7402. }
  7403. if (ErrorFound)
  7404. return StmtError();
  7405. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  7406. if (Pair.first && DirName.getName() && !DependentHint) {
  7407. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  7408. Diag(StartLoc, diag::err_omp_critical_with_hint);
  7409. if (HintLoc.isValid())
  7410. Diag(HintLoc, diag::note_omp_critical_hint_here)
  7411. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  7412. else
  7413. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  7414. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  7415. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  7416. << 1
  7417. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  7418. /*Radix=*/10, /*Signed=*/false);
  7419. } else {
  7420. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  7421. }
  7422. }
  7423. }
  7424. setFunctionHasBranchProtectedScope();
  7425. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  7426. Clauses, AStmt);
  7427. if (!Pair.first && DirName.getName() && !DependentHint)
  7428. DSAStack->addCriticalWithHint(Dir, Hint);
  7429. return Dir;
  7430. }
  7431. StmtResult Sema::ActOnOpenMPParallelForDirective(
  7432. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7433. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7434. if (!AStmt)
  7435. return StmtError();
  7436. auto *CS = cast<CapturedStmt>(AStmt);
  7437. // 1.2.2 OpenMP Language Terminology
  7438. // Structured block - An executable statement with a single entry at the
  7439. // top and a single exit at the bottom.
  7440. // The point of exit cannot be a branch out of the structured block.
  7441. // longjmp() and throw() must not violate the entry/exit criteria.
  7442. CS->getCapturedDecl()->setNothrow();
  7443. OMPLoopDirective::HelperExprs B;
  7444. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7445. // define the nested loops number.
  7446. unsigned NestedLoopCount =
  7447. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  7448. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7449. VarsWithImplicitDSA, B);
  7450. if (NestedLoopCount == 0)
  7451. return StmtError();
  7452. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7453. "omp parallel for loop exprs were not built");
  7454. if (!CurContext->isDependentContext()) {
  7455. // Finalize the clauses that need pre-built expressions for CodeGen.
  7456. for (OMPClause *C : Clauses) {
  7457. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7458. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7459. B.NumIterations, *this, CurScope,
  7460. DSAStack))
  7461. return StmtError();
  7462. }
  7463. }
  7464. setFunctionHasBranchProtectedScope();
  7465. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  7466. NestedLoopCount, Clauses, AStmt, B,
  7467. DSAStack->isCancelRegion());
  7468. }
  7469. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  7470. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7471. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7472. if (!AStmt)
  7473. return StmtError();
  7474. auto *CS = cast<CapturedStmt>(AStmt);
  7475. // 1.2.2 OpenMP Language Terminology
  7476. // Structured block - An executable statement with a single entry at the
  7477. // top and a single exit at the bottom.
  7478. // The point of exit cannot be a branch out of the structured block.
  7479. // longjmp() and throw() must not violate the entry/exit criteria.
  7480. CS->getCapturedDecl()->setNothrow();
  7481. OMPLoopDirective::HelperExprs B;
  7482. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7483. // define the nested loops number.
  7484. unsigned NestedLoopCount =
  7485. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7486. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7487. VarsWithImplicitDSA, B);
  7488. if (NestedLoopCount == 0)
  7489. return StmtError();
  7490. if (!CurContext->isDependentContext()) {
  7491. // Finalize the clauses that need pre-built expressions for CodeGen.
  7492. for (OMPClause *C : Clauses) {
  7493. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7494. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7495. B.NumIterations, *this, CurScope,
  7496. DSAStack))
  7497. return StmtError();
  7498. }
  7499. }
  7500. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7501. return StmtError();
  7502. setFunctionHasBranchProtectedScope();
  7503. return OMPParallelForSimdDirective::Create(
  7504. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7505. }
  7506. StmtResult
  7507. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7508. Stmt *AStmt, SourceLocation StartLoc,
  7509. SourceLocation EndLoc) {
  7510. if (!AStmt)
  7511. return StmtError();
  7512. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7513. auto BaseStmt = AStmt;
  7514. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7515. BaseStmt = CS->getCapturedStmt();
  7516. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7517. auto S = C->children();
  7518. if (S.begin() == S.end())
  7519. return StmtError();
  7520. // All associated statements must be '#pragma omp section' except for
  7521. // the first one.
  7522. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7523. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7524. if (SectionStmt)
  7525. Diag(SectionStmt->getBeginLoc(),
  7526. diag::err_omp_parallel_sections_substmt_not_section);
  7527. return StmtError();
  7528. }
  7529. cast<OMPSectionDirective>(SectionStmt)
  7530. ->setHasCancel(DSAStack->isCancelRegion());
  7531. }
  7532. } else {
  7533. Diag(AStmt->getBeginLoc(),
  7534. diag::err_omp_parallel_sections_not_compound_stmt);
  7535. return StmtError();
  7536. }
  7537. setFunctionHasBranchProtectedScope();
  7538. return OMPParallelSectionsDirective::Create(
  7539. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  7540. }
  7541. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  7542. Stmt *AStmt, SourceLocation StartLoc,
  7543. SourceLocation EndLoc) {
  7544. if (!AStmt)
  7545. return StmtError();
  7546. auto *CS = cast<CapturedStmt>(AStmt);
  7547. // 1.2.2 OpenMP Language Terminology
  7548. // Structured block - An executable statement with a single entry at the
  7549. // top and a single exit at the bottom.
  7550. // The point of exit cannot be a branch out of the structured block.
  7551. // longjmp() and throw() must not violate the entry/exit criteria.
  7552. CS->getCapturedDecl()->setNothrow();
  7553. setFunctionHasBranchProtectedScope();
  7554. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7555. DSAStack->isCancelRegion());
  7556. }
  7557. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  7558. SourceLocation EndLoc) {
  7559. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  7560. }
  7561. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  7562. SourceLocation EndLoc) {
  7563. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  7564. }
  7565. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  7566. SourceLocation EndLoc) {
  7567. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  7568. }
  7569. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  7570. Stmt *AStmt,
  7571. SourceLocation StartLoc,
  7572. SourceLocation EndLoc) {
  7573. if (!AStmt)
  7574. return StmtError();
  7575. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7576. setFunctionHasBranchProtectedScope();
  7577. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7578. AStmt,
  7579. DSAStack->getTaskgroupReductionRef());
  7580. }
  7581. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  7582. SourceLocation StartLoc,
  7583. SourceLocation EndLoc) {
  7584. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  7585. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  7586. }
  7587. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  7588. Stmt *AStmt,
  7589. SourceLocation StartLoc,
  7590. SourceLocation EndLoc) {
  7591. const OMPClause *DependFound = nullptr;
  7592. const OMPClause *DependSourceClause = nullptr;
  7593. const OMPClause *DependSinkClause = nullptr;
  7594. bool ErrorFound = false;
  7595. const OMPThreadsClause *TC = nullptr;
  7596. const OMPSIMDClause *SC = nullptr;
  7597. for (const OMPClause *C : Clauses) {
  7598. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  7599. DependFound = C;
  7600. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  7601. if (DependSourceClause) {
  7602. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  7603. << getOpenMPDirectiveName(OMPD_ordered)
  7604. << getOpenMPClauseName(OMPC_depend) << 2;
  7605. ErrorFound = true;
  7606. } else {
  7607. DependSourceClause = C;
  7608. }
  7609. if (DependSinkClause) {
  7610. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7611. << 0;
  7612. ErrorFound = true;
  7613. }
  7614. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  7615. if (DependSourceClause) {
  7616. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7617. << 1;
  7618. ErrorFound = true;
  7619. }
  7620. DependSinkClause = C;
  7621. }
  7622. } else if (C->getClauseKind() == OMPC_threads) {
  7623. TC = cast<OMPThreadsClause>(C);
  7624. } else if (C->getClauseKind() == OMPC_simd) {
  7625. SC = cast<OMPSIMDClause>(C);
  7626. }
  7627. }
  7628. if (!ErrorFound && !SC &&
  7629. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  7630. // OpenMP [2.8.1,simd Construct, Restrictions]
  7631. // An ordered construct with the simd clause is the only OpenMP construct
  7632. // that can appear in the simd region.
  7633. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  7634. ErrorFound = true;
  7635. } else if (DependFound && (TC || SC)) {
  7636. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  7637. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  7638. ErrorFound = true;
  7639. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  7640. Diag(DependFound->getBeginLoc(),
  7641. diag::err_omp_ordered_directive_without_param);
  7642. ErrorFound = true;
  7643. } else if (TC || Clauses.empty()) {
  7644. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  7645. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  7646. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  7647. << (TC != nullptr);
  7648. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  7649. ErrorFound = true;
  7650. }
  7651. }
  7652. if ((!AStmt && !DependFound) || ErrorFound)
  7653. return StmtError();
  7654. if (AStmt) {
  7655. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7656. setFunctionHasBranchProtectedScope();
  7657. }
  7658. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7659. }
  7660. namespace {
  7661. /// Helper class for checking expression in 'omp atomic [update]'
  7662. /// construct.
  7663. class OpenMPAtomicUpdateChecker {
  7664. /// Error results for atomic update expressions.
  7665. enum ExprAnalysisErrorCode {
  7666. /// A statement is not an expression statement.
  7667. NotAnExpression,
  7668. /// Expression is not builtin binary or unary operation.
  7669. NotABinaryOrUnaryExpression,
  7670. /// Unary operation is not post-/pre- increment/decrement operation.
  7671. NotAnUnaryIncDecExpression,
  7672. /// An expression is not of scalar type.
  7673. NotAScalarType,
  7674. /// A binary operation is not an assignment operation.
  7675. NotAnAssignmentOp,
  7676. /// RHS part of the binary operation is not a binary expression.
  7677. NotABinaryExpression,
  7678. /// RHS part is not additive/multiplicative/shift/biwise binary
  7679. /// expression.
  7680. NotABinaryOperator,
  7681. /// RHS binary operation does not have reference to the updated LHS
  7682. /// part.
  7683. NotAnUpdateExpression,
  7684. /// No errors is found.
  7685. NoError
  7686. };
  7687. /// Reference to Sema.
  7688. Sema &SemaRef;
  7689. /// A location for note diagnostics (when error is found).
  7690. SourceLocation NoteLoc;
  7691. /// 'x' lvalue part of the source atomic expression.
  7692. Expr *X;
  7693. /// 'expr' rvalue part of the source atomic expression.
  7694. Expr *E;
  7695. /// Helper expression of the form
  7696. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7697. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7698. Expr *UpdateExpr;
  7699. /// Is 'x' a LHS in a RHS part of full update expression. It is
  7700. /// important for non-associative operations.
  7701. bool IsXLHSInRHSPart;
  7702. BinaryOperatorKind Op;
  7703. SourceLocation OpLoc;
  7704. /// true if the source expression is a postfix unary operation, false
  7705. /// if it is a prefix unary operation.
  7706. bool IsPostfixUpdate;
  7707. public:
  7708. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  7709. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  7710. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  7711. /// Check specified statement that it is suitable for 'atomic update'
  7712. /// constructs and extract 'x', 'expr' and Operation from the original
  7713. /// expression. If DiagId and NoteId == 0, then only check is performed
  7714. /// without error notification.
  7715. /// \param DiagId Diagnostic which should be emitted if error is found.
  7716. /// \param NoteId Diagnostic note for the main error message.
  7717. /// \return true if statement is not an update expression, false otherwise.
  7718. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  7719. /// Return the 'x' lvalue part of the source atomic expression.
  7720. Expr *getX() const { return X; }
  7721. /// Return the 'expr' rvalue part of the source atomic expression.
  7722. Expr *getExpr() const { return E; }
  7723. /// Return the update expression used in calculation of the updated
  7724. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7725. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7726. Expr *getUpdateExpr() const { return UpdateExpr; }
  7727. /// Return true if 'x' is LHS in RHS part of full update expression,
  7728. /// false otherwise.
  7729. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  7730. /// true if the source expression is a postfix unary operation, false
  7731. /// if it is a prefix unary operation.
  7732. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  7733. private:
  7734. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  7735. unsigned NoteId = 0);
  7736. };
  7737. } // namespace
  7738. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  7739. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  7740. ExprAnalysisErrorCode ErrorFound = NoError;
  7741. SourceLocation ErrorLoc, NoteLoc;
  7742. SourceRange ErrorRange, NoteRange;
  7743. // Allowed constructs are:
  7744. // x = x binop expr;
  7745. // x = expr binop x;
  7746. if (AtomicBinOp->getOpcode() == BO_Assign) {
  7747. X = AtomicBinOp->getLHS();
  7748. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  7749. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  7750. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  7751. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  7752. AtomicInnerBinOp->isBitwiseOp()) {
  7753. Op = AtomicInnerBinOp->getOpcode();
  7754. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  7755. Expr *LHS = AtomicInnerBinOp->getLHS();
  7756. Expr *RHS = AtomicInnerBinOp->getRHS();
  7757. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  7758. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  7759. /*Canonical=*/true);
  7760. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  7761. /*Canonical=*/true);
  7762. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  7763. /*Canonical=*/true);
  7764. if (XId == LHSId) {
  7765. E = RHS;
  7766. IsXLHSInRHSPart = true;
  7767. } else if (XId == RHSId) {
  7768. E = LHS;
  7769. IsXLHSInRHSPart = false;
  7770. } else {
  7771. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7772. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7773. NoteLoc = X->getExprLoc();
  7774. NoteRange = X->getSourceRange();
  7775. ErrorFound = NotAnUpdateExpression;
  7776. }
  7777. } else {
  7778. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7779. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7780. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  7781. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7782. ErrorFound = NotABinaryOperator;
  7783. }
  7784. } else {
  7785. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  7786. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  7787. ErrorFound = NotABinaryExpression;
  7788. }
  7789. } else {
  7790. ErrorLoc = AtomicBinOp->getExprLoc();
  7791. ErrorRange = AtomicBinOp->getSourceRange();
  7792. NoteLoc = AtomicBinOp->getOperatorLoc();
  7793. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7794. ErrorFound = NotAnAssignmentOp;
  7795. }
  7796. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7797. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7798. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7799. return true;
  7800. }
  7801. if (SemaRef.CurContext->isDependentContext())
  7802. E = X = UpdateExpr = nullptr;
  7803. return ErrorFound != NoError;
  7804. }
  7805. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  7806. unsigned NoteId) {
  7807. ExprAnalysisErrorCode ErrorFound = NoError;
  7808. SourceLocation ErrorLoc, NoteLoc;
  7809. SourceRange ErrorRange, NoteRange;
  7810. // Allowed constructs are:
  7811. // x++;
  7812. // x--;
  7813. // ++x;
  7814. // --x;
  7815. // x binop= expr;
  7816. // x = x binop expr;
  7817. // x = expr binop x;
  7818. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  7819. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  7820. if (AtomicBody->getType()->isScalarType() ||
  7821. AtomicBody->isInstantiationDependent()) {
  7822. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  7823. AtomicBody->IgnoreParenImpCasts())) {
  7824. // Check for Compound Assignment Operation
  7825. Op = BinaryOperator::getOpForCompoundAssignment(
  7826. AtomicCompAssignOp->getOpcode());
  7827. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  7828. E = AtomicCompAssignOp->getRHS();
  7829. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  7830. IsXLHSInRHSPart = true;
  7831. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  7832. AtomicBody->IgnoreParenImpCasts())) {
  7833. // Check for Binary Operation
  7834. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  7835. return true;
  7836. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  7837. AtomicBody->IgnoreParenImpCasts())) {
  7838. // Check for Unary Operation
  7839. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  7840. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  7841. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  7842. OpLoc = AtomicUnaryOp->getOperatorLoc();
  7843. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  7844. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  7845. IsXLHSInRHSPart = true;
  7846. } else {
  7847. ErrorFound = NotAnUnaryIncDecExpression;
  7848. ErrorLoc = AtomicUnaryOp->getExprLoc();
  7849. ErrorRange = AtomicUnaryOp->getSourceRange();
  7850. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  7851. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7852. }
  7853. } else if (!AtomicBody->isInstantiationDependent()) {
  7854. ErrorFound = NotABinaryOrUnaryExpression;
  7855. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  7856. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  7857. }
  7858. } else {
  7859. ErrorFound = NotAScalarType;
  7860. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  7861. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7862. }
  7863. } else {
  7864. ErrorFound = NotAnExpression;
  7865. NoteLoc = ErrorLoc = S->getBeginLoc();
  7866. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7867. }
  7868. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7869. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7870. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7871. return true;
  7872. }
  7873. if (SemaRef.CurContext->isDependentContext())
  7874. E = X = UpdateExpr = nullptr;
  7875. if (ErrorFound == NoError && E && X) {
  7876. // Build an update expression of form 'OpaqueValueExpr(x) binop
  7877. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  7878. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  7879. auto *OVEX = new (SemaRef.getASTContext())
  7880. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  7881. auto *OVEExpr = new (SemaRef.getASTContext())
  7882. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  7883. ExprResult Update =
  7884. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  7885. IsXLHSInRHSPart ? OVEExpr : OVEX);
  7886. if (Update.isInvalid())
  7887. return true;
  7888. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  7889. Sema::AA_Casting);
  7890. if (Update.isInvalid())
  7891. return true;
  7892. UpdateExpr = Update.get();
  7893. }
  7894. return ErrorFound != NoError;
  7895. }
  7896. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  7897. Stmt *AStmt,
  7898. SourceLocation StartLoc,
  7899. SourceLocation EndLoc) {
  7900. if (!AStmt)
  7901. return StmtError();
  7902. auto *CS = cast<CapturedStmt>(AStmt);
  7903. // 1.2.2 OpenMP Language Terminology
  7904. // Structured block - An executable statement with a single entry at the
  7905. // top and a single exit at the bottom.
  7906. // The point of exit cannot be a branch out of the structured block.
  7907. // longjmp() and throw() must not violate the entry/exit criteria.
  7908. OpenMPClauseKind AtomicKind = OMPC_unknown;
  7909. SourceLocation AtomicKindLoc;
  7910. for (const OMPClause *C : Clauses) {
  7911. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  7912. C->getClauseKind() == OMPC_update ||
  7913. C->getClauseKind() == OMPC_capture) {
  7914. if (AtomicKind != OMPC_unknown) {
  7915. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  7916. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  7917. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  7918. << getOpenMPClauseName(AtomicKind);
  7919. } else {
  7920. AtomicKind = C->getClauseKind();
  7921. AtomicKindLoc = C->getBeginLoc();
  7922. }
  7923. }
  7924. }
  7925. Stmt *Body = CS->getCapturedStmt();
  7926. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  7927. Body = EWC->getSubExpr();
  7928. Expr *X = nullptr;
  7929. Expr *V = nullptr;
  7930. Expr *E = nullptr;
  7931. Expr *UE = nullptr;
  7932. bool IsXLHSInRHSPart = false;
  7933. bool IsPostfixUpdate = false;
  7934. // OpenMP [2.12.6, atomic Construct]
  7935. // In the next expressions:
  7936. // * x and v (as applicable) are both l-value expressions with scalar type.
  7937. // * During the execution of an atomic region, multiple syntactic
  7938. // occurrences of x must designate the same storage location.
  7939. // * Neither of v and expr (as applicable) may access the storage location
  7940. // designated by x.
  7941. // * Neither of x and expr (as applicable) may access the storage location
  7942. // designated by v.
  7943. // * expr is an expression with scalar type.
  7944. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  7945. // * binop, binop=, ++, and -- are not overloaded operators.
  7946. // * The expression x binop expr must be numerically equivalent to x binop
  7947. // (expr). This requirement is satisfied if the operators in expr have
  7948. // precedence greater than binop, or by using parentheses around expr or
  7949. // subexpressions of expr.
  7950. // * The expression expr binop x must be numerically equivalent to (expr)
  7951. // binop x. This requirement is satisfied if the operators in expr have
  7952. // precedence equal to or greater than binop, or by using parentheses around
  7953. // expr or subexpressions of expr.
  7954. // * For forms that allow multiple occurrences of x, the number of times
  7955. // that x is evaluated is unspecified.
  7956. if (AtomicKind == OMPC_read) {
  7957. enum {
  7958. NotAnExpression,
  7959. NotAnAssignmentOp,
  7960. NotAScalarType,
  7961. NotAnLValue,
  7962. NoError
  7963. } ErrorFound = NoError;
  7964. SourceLocation ErrorLoc, NoteLoc;
  7965. SourceRange ErrorRange, NoteRange;
  7966. // If clause is read:
  7967. // v = x;
  7968. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7969. const auto *AtomicBinOp =
  7970. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7971. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7972. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  7973. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  7974. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7975. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  7976. if (!X->isLValue() || !V->isLValue()) {
  7977. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  7978. ErrorFound = NotAnLValue;
  7979. ErrorLoc = AtomicBinOp->getExprLoc();
  7980. ErrorRange = AtomicBinOp->getSourceRange();
  7981. NoteLoc = NotLValueExpr->getExprLoc();
  7982. NoteRange = NotLValueExpr->getSourceRange();
  7983. }
  7984. } else if (!X->isInstantiationDependent() ||
  7985. !V->isInstantiationDependent()) {
  7986. const Expr *NotScalarExpr =
  7987. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7988. ? V
  7989. : X;
  7990. ErrorFound = NotAScalarType;
  7991. ErrorLoc = AtomicBinOp->getExprLoc();
  7992. ErrorRange = AtomicBinOp->getSourceRange();
  7993. NoteLoc = NotScalarExpr->getExprLoc();
  7994. NoteRange = NotScalarExpr->getSourceRange();
  7995. }
  7996. } else if (!AtomicBody->isInstantiationDependent()) {
  7997. ErrorFound = NotAnAssignmentOp;
  7998. ErrorLoc = AtomicBody->getExprLoc();
  7999. ErrorRange = AtomicBody->getSourceRange();
  8000. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  8001. : AtomicBody->getExprLoc();
  8002. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  8003. : AtomicBody->getSourceRange();
  8004. }
  8005. } else {
  8006. ErrorFound = NotAnExpression;
  8007. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8008. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  8009. }
  8010. if (ErrorFound != NoError) {
  8011. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  8012. << ErrorRange;
  8013. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  8014. << NoteRange;
  8015. return StmtError();
  8016. }
  8017. if (CurContext->isDependentContext())
  8018. V = X = nullptr;
  8019. } else if (AtomicKind == OMPC_write) {
  8020. enum {
  8021. NotAnExpression,
  8022. NotAnAssignmentOp,
  8023. NotAScalarType,
  8024. NotAnLValue,
  8025. NoError
  8026. } ErrorFound = NoError;
  8027. SourceLocation ErrorLoc, NoteLoc;
  8028. SourceRange ErrorRange, NoteRange;
  8029. // If clause is write:
  8030. // x = expr;
  8031. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  8032. const auto *AtomicBinOp =
  8033. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  8034. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  8035. X = AtomicBinOp->getLHS();
  8036. E = AtomicBinOp->getRHS();
  8037. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  8038. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  8039. if (!X->isLValue()) {
  8040. ErrorFound = NotAnLValue;
  8041. ErrorLoc = AtomicBinOp->getExprLoc();
  8042. ErrorRange = AtomicBinOp->getSourceRange();
  8043. NoteLoc = X->getExprLoc();
  8044. NoteRange = X->getSourceRange();
  8045. }
  8046. } else if (!X->isInstantiationDependent() ||
  8047. !E->isInstantiationDependent()) {
  8048. const Expr *NotScalarExpr =
  8049. (X->isInstantiationDependent() || X->getType()->isScalarType())
  8050. ? E
  8051. : X;
  8052. ErrorFound = NotAScalarType;
  8053. ErrorLoc = AtomicBinOp->getExprLoc();
  8054. ErrorRange = AtomicBinOp->getSourceRange();
  8055. NoteLoc = NotScalarExpr->getExprLoc();
  8056. NoteRange = NotScalarExpr->getSourceRange();
  8057. }
  8058. } else if (!AtomicBody->isInstantiationDependent()) {
  8059. ErrorFound = NotAnAssignmentOp;
  8060. ErrorLoc = AtomicBody->getExprLoc();
  8061. ErrorRange = AtomicBody->getSourceRange();
  8062. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  8063. : AtomicBody->getExprLoc();
  8064. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  8065. : AtomicBody->getSourceRange();
  8066. }
  8067. } else {
  8068. ErrorFound = NotAnExpression;
  8069. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8070. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  8071. }
  8072. if (ErrorFound != NoError) {
  8073. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  8074. << ErrorRange;
  8075. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  8076. << NoteRange;
  8077. return StmtError();
  8078. }
  8079. if (CurContext->isDependentContext())
  8080. E = X = nullptr;
  8081. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  8082. // If clause is update:
  8083. // x++;
  8084. // x--;
  8085. // ++x;
  8086. // --x;
  8087. // x binop= expr;
  8088. // x = x binop expr;
  8089. // x = expr binop x;
  8090. OpenMPAtomicUpdateChecker Checker(*this);
  8091. if (Checker.checkStatement(
  8092. Body, (AtomicKind == OMPC_update)
  8093. ? diag::err_omp_atomic_update_not_expression_statement
  8094. : diag::err_omp_atomic_not_expression_statement,
  8095. diag::note_omp_atomic_update))
  8096. return StmtError();
  8097. if (!CurContext->isDependentContext()) {
  8098. E = Checker.getExpr();
  8099. X = Checker.getX();
  8100. UE = Checker.getUpdateExpr();
  8101. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8102. }
  8103. } else if (AtomicKind == OMPC_capture) {
  8104. enum {
  8105. NotAnAssignmentOp,
  8106. NotACompoundStatement,
  8107. NotTwoSubstatements,
  8108. NotASpecificExpression,
  8109. NoError
  8110. } ErrorFound = NoError;
  8111. SourceLocation ErrorLoc, NoteLoc;
  8112. SourceRange ErrorRange, NoteRange;
  8113. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  8114. // If clause is a capture:
  8115. // v = x++;
  8116. // v = x--;
  8117. // v = ++x;
  8118. // v = --x;
  8119. // v = x binop= expr;
  8120. // v = x = x binop expr;
  8121. // v = x = expr binop x;
  8122. const auto *AtomicBinOp =
  8123. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  8124. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  8125. V = AtomicBinOp->getLHS();
  8126. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  8127. OpenMPAtomicUpdateChecker Checker(*this);
  8128. if (Checker.checkStatement(
  8129. Body, diag::err_omp_atomic_capture_not_expression_statement,
  8130. diag::note_omp_atomic_update))
  8131. return StmtError();
  8132. E = Checker.getExpr();
  8133. X = Checker.getX();
  8134. UE = Checker.getUpdateExpr();
  8135. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8136. IsPostfixUpdate = Checker.isPostfixUpdate();
  8137. } else if (!AtomicBody->isInstantiationDependent()) {
  8138. ErrorLoc = AtomicBody->getExprLoc();
  8139. ErrorRange = AtomicBody->getSourceRange();
  8140. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  8141. : AtomicBody->getExprLoc();
  8142. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  8143. : AtomicBody->getSourceRange();
  8144. ErrorFound = NotAnAssignmentOp;
  8145. }
  8146. if (ErrorFound != NoError) {
  8147. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  8148. << ErrorRange;
  8149. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8150. return StmtError();
  8151. }
  8152. if (CurContext->isDependentContext())
  8153. UE = V = E = X = nullptr;
  8154. } else {
  8155. // If clause is a capture:
  8156. // { v = x; x = expr; }
  8157. // { v = x; x++; }
  8158. // { v = x; x--; }
  8159. // { v = x; ++x; }
  8160. // { v = x; --x; }
  8161. // { v = x; x binop= expr; }
  8162. // { v = x; x = x binop expr; }
  8163. // { v = x; x = expr binop x; }
  8164. // { x++; v = x; }
  8165. // { x--; v = x; }
  8166. // { ++x; v = x; }
  8167. // { --x; v = x; }
  8168. // { x binop= expr; v = x; }
  8169. // { x = x binop expr; v = x; }
  8170. // { x = expr binop x; v = x; }
  8171. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  8172. // Check that this is { expr1; expr2; }
  8173. if (CS->size() == 2) {
  8174. Stmt *First = CS->body_front();
  8175. Stmt *Second = CS->body_back();
  8176. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  8177. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  8178. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  8179. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  8180. // Need to find what subexpression is 'v' and what is 'x'.
  8181. OpenMPAtomicUpdateChecker Checker(*this);
  8182. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  8183. BinaryOperator *BinOp = nullptr;
  8184. if (IsUpdateExprFound) {
  8185. BinOp = dyn_cast<BinaryOperator>(First);
  8186. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8187. }
  8188. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8189. // { v = x; x++; }
  8190. // { v = x; x--; }
  8191. // { v = x; ++x; }
  8192. // { v = x; --x; }
  8193. // { v = x; x binop= expr; }
  8194. // { v = x; x = x binop expr; }
  8195. // { v = x; x = expr binop x; }
  8196. // Check that the first expression has form v = x.
  8197. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8198. llvm::FoldingSetNodeID XId, PossibleXId;
  8199. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8200. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8201. IsUpdateExprFound = XId == PossibleXId;
  8202. if (IsUpdateExprFound) {
  8203. V = BinOp->getLHS();
  8204. X = Checker.getX();
  8205. E = Checker.getExpr();
  8206. UE = Checker.getUpdateExpr();
  8207. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8208. IsPostfixUpdate = true;
  8209. }
  8210. }
  8211. if (!IsUpdateExprFound) {
  8212. IsUpdateExprFound = !Checker.checkStatement(First);
  8213. BinOp = nullptr;
  8214. if (IsUpdateExprFound) {
  8215. BinOp = dyn_cast<BinaryOperator>(Second);
  8216. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8217. }
  8218. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8219. // { x++; v = x; }
  8220. // { x--; v = x; }
  8221. // { ++x; v = x; }
  8222. // { --x; v = x; }
  8223. // { x binop= expr; v = x; }
  8224. // { x = x binop expr; v = x; }
  8225. // { x = expr binop x; v = x; }
  8226. // Check that the second expression has form v = x.
  8227. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8228. llvm::FoldingSetNodeID XId, PossibleXId;
  8229. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8230. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8231. IsUpdateExprFound = XId == PossibleXId;
  8232. if (IsUpdateExprFound) {
  8233. V = BinOp->getLHS();
  8234. X = Checker.getX();
  8235. E = Checker.getExpr();
  8236. UE = Checker.getUpdateExpr();
  8237. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8238. IsPostfixUpdate = false;
  8239. }
  8240. }
  8241. }
  8242. if (!IsUpdateExprFound) {
  8243. // { v = x; x = expr; }
  8244. auto *FirstExpr = dyn_cast<Expr>(First);
  8245. auto *SecondExpr = dyn_cast<Expr>(Second);
  8246. if (!FirstExpr || !SecondExpr ||
  8247. !(FirstExpr->isInstantiationDependent() ||
  8248. SecondExpr->isInstantiationDependent())) {
  8249. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  8250. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  8251. ErrorFound = NotAnAssignmentOp;
  8252. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  8253. : First->getBeginLoc();
  8254. NoteRange = ErrorRange = FirstBinOp
  8255. ? FirstBinOp->getSourceRange()
  8256. : SourceRange(ErrorLoc, ErrorLoc);
  8257. } else {
  8258. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  8259. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  8260. ErrorFound = NotAnAssignmentOp;
  8261. NoteLoc = ErrorLoc = SecondBinOp
  8262. ? SecondBinOp->getOperatorLoc()
  8263. : Second->getBeginLoc();
  8264. NoteRange = ErrorRange =
  8265. SecondBinOp ? SecondBinOp->getSourceRange()
  8266. : SourceRange(ErrorLoc, ErrorLoc);
  8267. } else {
  8268. Expr *PossibleXRHSInFirst =
  8269. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  8270. Expr *PossibleXLHSInSecond =
  8271. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  8272. llvm::FoldingSetNodeID X1Id, X2Id;
  8273. PossibleXRHSInFirst->Profile(X1Id, Context,
  8274. /*Canonical=*/true);
  8275. PossibleXLHSInSecond->Profile(X2Id, Context,
  8276. /*Canonical=*/true);
  8277. IsUpdateExprFound = X1Id == X2Id;
  8278. if (IsUpdateExprFound) {
  8279. V = FirstBinOp->getLHS();
  8280. X = SecondBinOp->getLHS();
  8281. E = SecondBinOp->getRHS();
  8282. UE = nullptr;
  8283. IsXLHSInRHSPart = false;
  8284. IsPostfixUpdate = true;
  8285. } else {
  8286. ErrorFound = NotASpecificExpression;
  8287. ErrorLoc = FirstBinOp->getExprLoc();
  8288. ErrorRange = FirstBinOp->getSourceRange();
  8289. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  8290. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  8291. }
  8292. }
  8293. }
  8294. }
  8295. }
  8296. } else {
  8297. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8298. NoteRange = ErrorRange =
  8299. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8300. ErrorFound = NotTwoSubstatements;
  8301. }
  8302. } else {
  8303. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8304. NoteRange = ErrorRange =
  8305. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8306. ErrorFound = NotACompoundStatement;
  8307. }
  8308. if (ErrorFound != NoError) {
  8309. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  8310. << ErrorRange;
  8311. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8312. return StmtError();
  8313. }
  8314. if (CurContext->isDependentContext())
  8315. UE = V = E = X = nullptr;
  8316. }
  8317. }
  8318. setFunctionHasBranchProtectedScope();
  8319. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  8320. X, V, E, UE, IsXLHSInRHSPart,
  8321. IsPostfixUpdate);
  8322. }
  8323. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  8324. Stmt *AStmt,
  8325. SourceLocation StartLoc,
  8326. SourceLocation EndLoc) {
  8327. if (!AStmt)
  8328. return StmtError();
  8329. auto *CS = cast<CapturedStmt>(AStmt);
  8330. // 1.2.2 OpenMP Language Terminology
  8331. // Structured block - An executable statement with a single entry at the
  8332. // top and a single exit at the bottom.
  8333. // The point of exit cannot be a branch out of the structured block.
  8334. // longjmp() and throw() must not violate the entry/exit criteria.
  8335. CS->getCapturedDecl()->setNothrow();
  8336. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  8337. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8338. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8339. // 1.2.2 OpenMP Language Terminology
  8340. // Structured block - An executable statement with a single entry at the
  8341. // top and a single exit at the bottom.
  8342. // The point of exit cannot be a branch out of the structured block.
  8343. // longjmp() and throw() must not violate the entry/exit criteria.
  8344. CS->getCapturedDecl()->setNothrow();
  8345. }
  8346. // OpenMP [2.16, Nesting of Regions]
  8347. // If specified, a teams construct must be contained within a target
  8348. // construct. That target construct must contain no statements or directives
  8349. // outside of the teams construct.
  8350. if (DSAStack->hasInnerTeamsRegion()) {
  8351. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  8352. bool OMPTeamsFound = true;
  8353. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  8354. auto I = CS->body_begin();
  8355. while (I != CS->body_end()) {
  8356. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  8357. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  8358. OMPTeamsFound) {
  8359. OMPTeamsFound = false;
  8360. break;
  8361. }
  8362. ++I;
  8363. }
  8364. assert(I != CS->body_end() && "Not found statement");
  8365. S = *I;
  8366. } else {
  8367. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  8368. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  8369. }
  8370. if (!OMPTeamsFound) {
  8371. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  8372. Diag(DSAStack->getInnerTeamsRegionLoc(),
  8373. diag::note_omp_nested_teams_construct_here);
  8374. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  8375. << isa<OMPExecutableDirective>(S);
  8376. return StmtError();
  8377. }
  8378. }
  8379. setFunctionHasBranchProtectedScope();
  8380. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8381. }
  8382. StmtResult
  8383. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  8384. Stmt *AStmt, SourceLocation StartLoc,
  8385. SourceLocation EndLoc) {
  8386. if (!AStmt)
  8387. return StmtError();
  8388. auto *CS = cast<CapturedStmt>(AStmt);
  8389. // 1.2.2 OpenMP Language Terminology
  8390. // Structured block - An executable statement with a single entry at the
  8391. // top and a single exit at the bottom.
  8392. // The point of exit cannot be a branch out of the structured block.
  8393. // longjmp() and throw() must not violate the entry/exit criteria.
  8394. CS->getCapturedDecl()->setNothrow();
  8395. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  8396. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8397. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8398. // 1.2.2 OpenMP Language Terminology
  8399. // Structured block - An executable statement with a single entry at the
  8400. // top and a single exit at the bottom.
  8401. // The point of exit cannot be a branch out of the structured block.
  8402. // longjmp() and throw() must not violate the entry/exit criteria.
  8403. CS->getCapturedDecl()->setNothrow();
  8404. }
  8405. setFunctionHasBranchProtectedScope();
  8406. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8407. AStmt);
  8408. }
  8409. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  8410. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8411. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8412. if (!AStmt)
  8413. return StmtError();
  8414. auto *CS = cast<CapturedStmt>(AStmt);
  8415. // 1.2.2 OpenMP Language Terminology
  8416. // Structured block - An executable statement with a single entry at the
  8417. // top and a single exit at the bottom.
  8418. // The point of exit cannot be a branch out of the structured block.
  8419. // longjmp() and throw() must not violate the entry/exit criteria.
  8420. CS->getCapturedDecl()->setNothrow();
  8421. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8422. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8423. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8424. // 1.2.2 OpenMP Language Terminology
  8425. // Structured block - An executable statement with a single entry at the
  8426. // top and a single exit at the bottom.
  8427. // The point of exit cannot be a branch out of the structured block.
  8428. // longjmp() and throw() must not violate the entry/exit criteria.
  8429. CS->getCapturedDecl()->setNothrow();
  8430. }
  8431. OMPLoopDirective::HelperExprs B;
  8432. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8433. // define the nested loops number.
  8434. unsigned NestedLoopCount =
  8435. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  8436. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8437. VarsWithImplicitDSA, B);
  8438. if (NestedLoopCount == 0)
  8439. return StmtError();
  8440. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8441. "omp target parallel for loop exprs were not built");
  8442. if (!CurContext->isDependentContext()) {
  8443. // Finalize the clauses that need pre-built expressions for CodeGen.
  8444. for (OMPClause *C : Clauses) {
  8445. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8446. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8447. B.NumIterations, *this, CurScope,
  8448. DSAStack))
  8449. return StmtError();
  8450. }
  8451. }
  8452. setFunctionHasBranchProtectedScope();
  8453. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  8454. NestedLoopCount, Clauses, AStmt,
  8455. B, DSAStack->isCancelRegion());
  8456. }
  8457. /// Check for existence of a map clause in the list of clauses.
  8458. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  8459. const OpenMPClauseKind K) {
  8460. return llvm::any_of(
  8461. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  8462. }
  8463. template <typename... Params>
  8464. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  8465. const Params... ClauseTypes) {
  8466. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  8467. }
  8468. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  8469. Stmt *AStmt,
  8470. SourceLocation StartLoc,
  8471. SourceLocation EndLoc) {
  8472. if (!AStmt)
  8473. return StmtError();
  8474. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8475. // OpenMP [2.10.1, Restrictions, p. 97]
  8476. // At least one map clause must appear on the directive.
  8477. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  8478. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8479. << "'map' or 'use_device_ptr'"
  8480. << getOpenMPDirectiveName(OMPD_target_data);
  8481. return StmtError();
  8482. }
  8483. setFunctionHasBranchProtectedScope();
  8484. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8485. AStmt);
  8486. }
  8487. StmtResult
  8488. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  8489. SourceLocation StartLoc,
  8490. SourceLocation EndLoc, Stmt *AStmt) {
  8491. if (!AStmt)
  8492. return StmtError();
  8493. auto *CS = cast<CapturedStmt>(AStmt);
  8494. // 1.2.2 OpenMP Language Terminology
  8495. // Structured block - An executable statement with a single entry at the
  8496. // top and a single exit at the bottom.
  8497. // The point of exit cannot be a branch out of the structured block.
  8498. // longjmp() and throw() must not violate the entry/exit criteria.
  8499. CS->getCapturedDecl()->setNothrow();
  8500. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  8501. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8502. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8503. // 1.2.2 OpenMP Language Terminology
  8504. // Structured block - An executable statement with a single entry at the
  8505. // top and a single exit at the bottom.
  8506. // The point of exit cannot be a branch out of the structured block.
  8507. // longjmp() and throw() must not violate the entry/exit criteria.
  8508. CS->getCapturedDecl()->setNothrow();
  8509. }
  8510. // OpenMP [2.10.2, Restrictions, p. 99]
  8511. // At least one map clause must appear on the directive.
  8512. if (!hasClauses(Clauses, OMPC_map)) {
  8513. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8514. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  8515. return StmtError();
  8516. }
  8517. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8518. AStmt);
  8519. }
  8520. StmtResult
  8521. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  8522. SourceLocation StartLoc,
  8523. SourceLocation EndLoc, Stmt *AStmt) {
  8524. if (!AStmt)
  8525. return StmtError();
  8526. auto *CS = cast<CapturedStmt>(AStmt);
  8527. // 1.2.2 OpenMP Language Terminology
  8528. // Structured block - An executable statement with a single entry at the
  8529. // top and a single exit at the bottom.
  8530. // The point of exit cannot be a branch out of the structured block.
  8531. // longjmp() and throw() must not violate the entry/exit criteria.
  8532. CS->getCapturedDecl()->setNothrow();
  8533. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  8534. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8535. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8536. // 1.2.2 OpenMP Language Terminology
  8537. // Structured block - An executable statement with a single entry at the
  8538. // top and a single exit at the bottom.
  8539. // The point of exit cannot be a branch out of the structured block.
  8540. // longjmp() and throw() must not violate the entry/exit criteria.
  8541. CS->getCapturedDecl()->setNothrow();
  8542. }
  8543. // OpenMP [2.10.3, Restrictions, p. 102]
  8544. // At least one map clause must appear on the directive.
  8545. if (!hasClauses(Clauses, OMPC_map)) {
  8546. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8547. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  8548. return StmtError();
  8549. }
  8550. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8551. AStmt);
  8552. }
  8553. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  8554. SourceLocation StartLoc,
  8555. SourceLocation EndLoc,
  8556. Stmt *AStmt) {
  8557. if (!AStmt)
  8558. return StmtError();
  8559. auto *CS = cast<CapturedStmt>(AStmt);
  8560. // 1.2.2 OpenMP Language Terminology
  8561. // Structured block - An executable statement with a single entry at the
  8562. // top and a single exit at the bottom.
  8563. // The point of exit cannot be a branch out of the structured block.
  8564. // longjmp() and throw() must not violate the entry/exit criteria.
  8565. CS->getCapturedDecl()->setNothrow();
  8566. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  8567. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8568. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8569. // 1.2.2 OpenMP Language Terminology
  8570. // Structured block - An executable statement with a single entry at the
  8571. // top and a single exit at the bottom.
  8572. // The point of exit cannot be a branch out of the structured block.
  8573. // longjmp() and throw() must not violate the entry/exit criteria.
  8574. CS->getCapturedDecl()->setNothrow();
  8575. }
  8576. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  8577. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  8578. return StmtError();
  8579. }
  8580. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8581. AStmt);
  8582. }
  8583. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  8584. Stmt *AStmt, SourceLocation StartLoc,
  8585. SourceLocation EndLoc) {
  8586. if (!AStmt)
  8587. return StmtError();
  8588. auto *CS = cast<CapturedStmt>(AStmt);
  8589. // 1.2.2 OpenMP Language Terminology
  8590. // Structured block - An executable statement with a single entry at the
  8591. // top and a single exit at the bottom.
  8592. // The point of exit cannot be a branch out of the structured block.
  8593. // longjmp() and throw() must not violate the entry/exit criteria.
  8594. CS->getCapturedDecl()->setNothrow();
  8595. setFunctionHasBranchProtectedScope();
  8596. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8597. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8598. }
  8599. StmtResult
  8600. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  8601. SourceLocation EndLoc,
  8602. OpenMPDirectiveKind CancelRegion) {
  8603. if (DSAStack->isParentNowaitRegion()) {
  8604. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  8605. return StmtError();
  8606. }
  8607. if (DSAStack->isParentOrderedRegion()) {
  8608. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  8609. return StmtError();
  8610. }
  8611. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  8612. CancelRegion);
  8613. }
  8614. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  8615. SourceLocation StartLoc,
  8616. SourceLocation EndLoc,
  8617. OpenMPDirectiveKind CancelRegion) {
  8618. if (DSAStack->isParentNowaitRegion()) {
  8619. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  8620. return StmtError();
  8621. }
  8622. if (DSAStack->isParentOrderedRegion()) {
  8623. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  8624. return StmtError();
  8625. }
  8626. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  8627. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8628. CancelRegion);
  8629. }
  8630. static bool checkGrainsizeNumTasksClauses(Sema &S,
  8631. ArrayRef<OMPClause *> Clauses) {
  8632. const OMPClause *PrevClause = nullptr;
  8633. bool ErrorFound = false;
  8634. for (const OMPClause *C : Clauses) {
  8635. if (C->getClauseKind() == OMPC_grainsize ||
  8636. C->getClauseKind() == OMPC_num_tasks) {
  8637. if (!PrevClause)
  8638. PrevClause = C;
  8639. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  8640. S.Diag(C->getBeginLoc(),
  8641. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  8642. << getOpenMPClauseName(C->getClauseKind())
  8643. << getOpenMPClauseName(PrevClause->getClauseKind());
  8644. S.Diag(PrevClause->getBeginLoc(),
  8645. diag::note_omp_previous_grainsize_num_tasks)
  8646. << getOpenMPClauseName(PrevClause->getClauseKind());
  8647. ErrorFound = true;
  8648. }
  8649. }
  8650. }
  8651. return ErrorFound;
  8652. }
  8653. static bool checkReductionClauseWithNogroup(Sema &S,
  8654. ArrayRef<OMPClause *> Clauses) {
  8655. const OMPClause *ReductionClause = nullptr;
  8656. const OMPClause *NogroupClause = nullptr;
  8657. for (const OMPClause *C : Clauses) {
  8658. if (C->getClauseKind() == OMPC_reduction) {
  8659. ReductionClause = C;
  8660. if (NogroupClause)
  8661. break;
  8662. continue;
  8663. }
  8664. if (C->getClauseKind() == OMPC_nogroup) {
  8665. NogroupClause = C;
  8666. if (ReductionClause)
  8667. break;
  8668. continue;
  8669. }
  8670. }
  8671. if (ReductionClause && NogroupClause) {
  8672. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  8673. << SourceRange(NogroupClause->getBeginLoc(),
  8674. NogroupClause->getEndLoc());
  8675. return true;
  8676. }
  8677. return false;
  8678. }
  8679. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  8680. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8681. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8682. if (!AStmt)
  8683. return StmtError();
  8684. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8685. OMPLoopDirective::HelperExprs B;
  8686. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8687. // define the nested loops number.
  8688. unsigned NestedLoopCount =
  8689. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  8690. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8691. VarsWithImplicitDSA, B);
  8692. if (NestedLoopCount == 0)
  8693. return StmtError();
  8694. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8695. "omp for loop exprs were not built");
  8696. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8697. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8698. // not appear on the same taskloop directive.
  8699. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8700. return StmtError();
  8701. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8702. // If a reduction clause is present on the taskloop directive, the nogroup
  8703. // clause must not be specified.
  8704. if (checkReductionClauseWithNogroup(*this, Clauses))
  8705. return StmtError();
  8706. setFunctionHasBranchProtectedScope();
  8707. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  8708. NestedLoopCount, Clauses, AStmt, B);
  8709. }
  8710. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  8711. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8712. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8713. if (!AStmt)
  8714. return StmtError();
  8715. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8716. OMPLoopDirective::HelperExprs B;
  8717. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8718. // define the nested loops number.
  8719. unsigned NestedLoopCount =
  8720. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  8721. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8722. VarsWithImplicitDSA, B);
  8723. if (NestedLoopCount == 0)
  8724. return StmtError();
  8725. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8726. "omp for loop exprs were not built");
  8727. if (!CurContext->isDependentContext()) {
  8728. // Finalize the clauses that need pre-built expressions for CodeGen.
  8729. for (OMPClause *C : Clauses) {
  8730. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8731. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8732. B.NumIterations, *this, CurScope,
  8733. DSAStack))
  8734. return StmtError();
  8735. }
  8736. }
  8737. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8738. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8739. // not appear on the same taskloop directive.
  8740. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8741. return StmtError();
  8742. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8743. // If a reduction clause is present on the taskloop directive, the nogroup
  8744. // clause must not be specified.
  8745. if (checkReductionClauseWithNogroup(*this, Clauses))
  8746. return StmtError();
  8747. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8748. return StmtError();
  8749. setFunctionHasBranchProtectedScope();
  8750. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  8751. NestedLoopCount, Clauses, AStmt, B);
  8752. }
  8753. StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
  8754. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8755. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8756. if (!AStmt)
  8757. return StmtError();
  8758. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8759. OMPLoopDirective::HelperExprs B;
  8760. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8761. // define the nested loops number.
  8762. unsigned NestedLoopCount =
  8763. checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
  8764. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8765. VarsWithImplicitDSA, B);
  8766. if (NestedLoopCount == 0)
  8767. return StmtError();
  8768. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8769. "omp for loop exprs were not built");
  8770. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8771. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8772. // not appear on the same taskloop directive.
  8773. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8774. return StmtError();
  8775. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8776. // If a reduction clause is present on the taskloop directive, the nogroup
  8777. // clause must not be specified.
  8778. if (checkReductionClauseWithNogroup(*this, Clauses))
  8779. return StmtError();
  8780. setFunctionHasBranchProtectedScope();
  8781. return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  8782. NestedLoopCount, Clauses, AStmt, B);
  8783. }
  8784. StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
  8785. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8786. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8787. if (!AStmt)
  8788. return StmtError();
  8789. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8790. OMPLoopDirective::HelperExprs B;
  8791. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8792. // define the nested loops number.
  8793. unsigned NestedLoopCount =
  8794. checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
  8795. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8796. VarsWithImplicitDSA, B);
  8797. if (NestedLoopCount == 0)
  8798. return StmtError();
  8799. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8800. "omp for loop exprs were not built");
  8801. if (!CurContext->isDependentContext()) {
  8802. // Finalize the clauses that need pre-built expressions for CodeGen.
  8803. for (OMPClause *C : Clauses) {
  8804. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8805. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8806. B.NumIterations, *this, CurScope,
  8807. DSAStack))
  8808. return StmtError();
  8809. }
  8810. }
  8811. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8812. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8813. // not appear on the same taskloop directive.
  8814. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8815. return StmtError();
  8816. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8817. // If a reduction clause is present on the taskloop directive, the nogroup
  8818. // clause must not be specified.
  8819. if (checkReductionClauseWithNogroup(*this, Clauses))
  8820. return StmtError();
  8821. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8822. return StmtError();
  8823. setFunctionHasBranchProtectedScope();
  8824. return OMPMasterTaskLoopSimdDirective::Create(
  8825. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8826. }
  8827. StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
  8828. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8829. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8830. if (!AStmt)
  8831. return StmtError();
  8832. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8833. auto *CS = cast<CapturedStmt>(AStmt);
  8834. // 1.2.2 OpenMP Language Terminology
  8835. // Structured block - An executable statement with a single entry at the
  8836. // top and a single exit at the bottom.
  8837. // The point of exit cannot be a branch out of the structured block.
  8838. // longjmp() and throw() must not violate the entry/exit criteria.
  8839. CS->getCapturedDecl()->setNothrow();
  8840. for (int ThisCaptureLevel =
  8841. getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
  8842. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8843. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8844. // 1.2.2 OpenMP Language Terminology
  8845. // Structured block - An executable statement with a single entry at the
  8846. // top and a single exit at the bottom.
  8847. // The point of exit cannot be a branch out of the structured block.
  8848. // longjmp() and throw() must not violate the entry/exit criteria.
  8849. CS->getCapturedDecl()->setNothrow();
  8850. }
  8851. OMPLoopDirective::HelperExprs B;
  8852. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8853. // define the nested loops number.
  8854. unsigned NestedLoopCount = checkOpenMPLoop(
  8855. OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
  8856. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  8857. VarsWithImplicitDSA, B);
  8858. if (NestedLoopCount == 0)
  8859. return StmtError();
  8860. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8861. "omp for loop exprs were not built");
  8862. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8863. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8864. // not appear on the same taskloop directive.
  8865. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8866. return StmtError();
  8867. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8868. // If a reduction clause is present on the taskloop directive, the nogroup
  8869. // clause must not be specified.
  8870. if (checkReductionClauseWithNogroup(*this, Clauses))
  8871. return StmtError();
  8872. setFunctionHasBranchProtectedScope();
  8873. return OMPParallelMasterTaskLoopDirective::Create(
  8874. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8875. }
  8876. StmtResult Sema::ActOnOpenMPDistributeDirective(
  8877. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8878. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8879. if (!AStmt)
  8880. return StmtError();
  8881. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8882. OMPLoopDirective::HelperExprs B;
  8883. // In presence of clause 'collapse' with number of loops, it will
  8884. // define the nested loops number.
  8885. unsigned NestedLoopCount =
  8886. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  8887. nullptr /*ordered not a clause on distribute*/, AStmt,
  8888. *this, *DSAStack, VarsWithImplicitDSA, B);
  8889. if (NestedLoopCount == 0)
  8890. return StmtError();
  8891. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8892. "omp for loop exprs were not built");
  8893. setFunctionHasBranchProtectedScope();
  8894. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  8895. NestedLoopCount, Clauses, AStmt, B);
  8896. }
  8897. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  8898. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8899. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8900. if (!AStmt)
  8901. return StmtError();
  8902. auto *CS = cast<CapturedStmt>(AStmt);
  8903. // 1.2.2 OpenMP Language Terminology
  8904. // Structured block - An executable statement with a single entry at the
  8905. // top and a single exit at the bottom.
  8906. // The point of exit cannot be a branch out of the structured block.
  8907. // longjmp() and throw() must not violate the entry/exit criteria.
  8908. CS->getCapturedDecl()->setNothrow();
  8909. for (int ThisCaptureLevel =
  8910. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  8911. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8912. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8913. // 1.2.2 OpenMP Language Terminology
  8914. // Structured block - An executable statement with a single entry at the
  8915. // top and a single exit at the bottom.
  8916. // The point of exit cannot be a branch out of the structured block.
  8917. // longjmp() and throw() must not violate the entry/exit criteria.
  8918. CS->getCapturedDecl()->setNothrow();
  8919. }
  8920. OMPLoopDirective::HelperExprs B;
  8921. // In presence of clause 'collapse' with number of loops, it will
  8922. // define the nested loops number.
  8923. unsigned NestedLoopCount = checkOpenMPLoop(
  8924. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  8925. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8926. VarsWithImplicitDSA, B);
  8927. if (NestedLoopCount == 0)
  8928. return StmtError();
  8929. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8930. "omp for loop exprs were not built");
  8931. setFunctionHasBranchProtectedScope();
  8932. return OMPDistributeParallelForDirective::Create(
  8933. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  8934. DSAStack->isCancelRegion());
  8935. }
  8936. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  8937. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8938. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8939. if (!AStmt)
  8940. return StmtError();
  8941. auto *CS = cast<CapturedStmt>(AStmt);
  8942. // 1.2.2 OpenMP Language Terminology
  8943. // Structured block - An executable statement with a single entry at the
  8944. // top and a single exit at the bottom.
  8945. // The point of exit cannot be a branch out of the structured block.
  8946. // longjmp() and throw() must not violate the entry/exit criteria.
  8947. CS->getCapturedDecl()->setNothrow();
  8948. for (int ThisCaptureLevel =
  8949. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  8950. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8951. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8952. // 1.2.2 OpenMP Language Terminology
  8953. // Structured block - An executable statement with a single entry at the
  8954. // top and a single exit at the bottom.
  8955. // The point of exit cannot be a branch out of the structured block.
  8956. // longjmp() and throw() must not violate the entry/exit criteria.
  8957. CS->getCapturedDecl()->setNothrow();
  8958. }
  8959. OMPLoopDirective::HelperExprs B;
  8960. // In presence of clause 'collapse' with number of loops, it will
  8961. // define the nested loops number.
  8962. unsigned NestedLoopCount = checkOpenMPLoop(
  8963. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8964. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8965. VarsWithImplicitDSA, B);
  8966. if (NestedLoopCount == 0)
  8967. return StmtError();
  8968. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8969. "omp for loop exprs were not built");
  8970. if (!CurContext->isDependentContext()) {
  8971. // Finalize the clauses that need pre-built expressions for CodeGen.
  8972. for (OMPClause *C : Clauses) {
  8973. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8974. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8975. B.NumIterations, *this, CurScope,
  8976. DSAStack))
  8977. return StmtError();
  8978. }
  8979. }
  8980. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8981. return StmtError();
  8982. setFunctionHasBranchProtectedScope();
  8983. return OMPDistributeParallelForSimdDirective::Create(
  8984. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8985. }
  8986. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  8987. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8988. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8989. if (!AStmt)
  8990. return StmtError();
  8991. auto *CS = cast<CapturedStmt>(AStmt);
  8992. // 1.2.2 OpenMP Language Terminology
  8993. // Structured block - An executable statement with a single entry at the
  8994. // top and a single exit at the bottom.
  8995. // The point of exit cannot be a branch out of the structured block.
  8996. // longjmp() and throw() must not violate the entry/exit criteria.
  8997. CS->getCapturedDecl()->setNothrow();
  8998. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  8999. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9000. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9001. // 1.2.2 OpenMP Language Terminology
  9002. // Structured block - An executable statement with a single entry at the
  9003. // top and a single exit at the bottom.
  9004. // The point of exit cannot be a branch out of the structured block.
  9005. // longjmp() and throw() must not violate the entry/exit criteria.
  9006. CS->getCapturedDecl()->setNothrow();
  9007. }
  9008. OMPLoopDirective::HelperExprs B;
  9009. // In presence of clause 'collapse' with number of loops, it will
  9010. // define the nested loops number.
  9011. unsigned NestedLoopCount =
  9012. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  9013. nullptr /*ordered not a clause on distribute*/, CS, *this,
  9014. *DSAStack, VarsWithImplicitDSA, B);
  9015. if (NestedLoopCount == 0)
  9016. return StmtError();
  9017. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9018. "omp for loop exprs were not built");
  9019. if (!CurContext->isDependentContext()) {
  9020. // Finalize the clauses that need pre-built expressions for CodeGen.
  9021. for (OMPClause *C : Clauses) {
  9022. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9023. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9024. B.NumIterations, *this, CurScope,
  9025. DSAStack))
  9026. return StmtError();
  9027. }
  9028. }
  9029. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9030. return StmtError();
  9031. setFunctionHasBranchProtectedScope();
  9032. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  9033. NestedLoopCount, Clauses, AStmt, B);
  9034. }
  9035. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  9036. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9037. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9038. if (!AStmt)
  9039. return StmtError();
  9040. auto *CS = cast<CapturedStmt>(AStmt);
  9041. // 1.2.2 OpenMP Language Terminology
  9042. // Structured block - An executable statement with a single entry at the
  9043. // top and a single exit at the bottom.
  9044. // The point of exit cannot be a branch out of the structured block.
  9045. // longjmp() and throw() must not violate the entry/exit criteria.
  9046. CS->getCapturedDecl()->setNothrow();
  9047. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  9048. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9049. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9050. // 1.2.2 OpenMP Language Terminology
  9051. // Structured block - An executable statement with a single entry at the
  9052. // top and a single exit at the bottom.
  9053. // The point of exit cannot be a branch out of the structured block.
  9054. // longjmp() and throw() must not violate the entry/exit criteria.
  9055. CS->getCapturedDecl()->setNothrow();
  9056. }
  9057. OMPLoopDirective::HelperExprs B;
  9058. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9059. // define the nested loops number.
  9060. unsigned NestedLoopCount = checkOpenMPLoop(
  9061. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  9062. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  9063. VarsWithImplicitDSA, B);
  9064. if (NestedLoopCount == 0)
  9065. return StmtError();
  9066. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9067. "omp target parallel for simd loop exprs were not built");
  9068. if (!CurContext->isDependentContext()) {
  9069. // Finalize the clauses that need pre-built expressions for CodeGen.
  9070. for (OMPClause *C : Clauses) {
  9071. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9072. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9073. B.NumIterations, *this, CurScope,
  9074. DSAStack))
  9075. return StmtError();
  9076. }
  9077. }
  9078. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9079. return StmtError();
  9080. setFunctionHasBranchProtectedScope();
  9081. return OMPTargetParallelForSimdDirective::Create(
  9082. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9083. }
  9084. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  9085. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9086. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9087. if (!AStmt)
  9088. return StmtError();
  9089. auto *CS = cast<CapturedStmt>(AStmt);
  9090. // 1.2.2 OpenMP Language Terminology
  9091. // Structured block - An executable statement with a single entry at the
  9092. // top and a single exit at the bottom.
  9093. // The point of exit cannot be a branch out of the structured block.
  9094. // longjmp() and throw() must not violate the entry/exit criteria.
  9095. CS->getCapturedDecl()->setNothrow();
  9096. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  9097. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9098. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9099. // 1.2.2 OpenMP Language Terminology
  9100. // Structured block - An executable statement with a single entry at the
  9101. // top and a single exit at the bottom.
  9102. // The point of exit cannot be a branch out of the structured block.
  9103. // longjmp() and throw() must not violate the entry/exit criteria.
  9104. CS->getCapturedDecl()->setNothrow();
  9105. }
  9106. OMPLoopDirective::HelperExprs B;
  9107. // In presence of clause 'collapse' with number of loops, it will define the
  9108. // nested loops number.
  9109. unsigned NestedLoopCount =
  9110. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  9111. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  9112. VarsWithImplicitDSA, B);
  9113. if (NestedLoopCount == 0)
  9114. return StmtError();
  9115. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9116. "omp target simd loop exprs were not built");
  9117. if (!CurContext->isDependentContext()) {
  9118. // Finalize the clauses that need pre-built expressions for CodeGen.
  9119. for (OMPClause *C : Clauses) {
  9120. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9121. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9122. B.NumIterations, *this, CurScope,
  9123. DSAStack))
  9124. return StmtError();
  9125. }
  9126. }
  9127. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9128. return StmtError();
  9129. setFunctionHasBranchProtectedScope();
  9130. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  9131. NestedLoopCount, Clauses, AStmt, B);
  9132. }
  9133. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  9134. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9135. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9136. if (!AStmt)
  9137. return StmtError();
  9138. auto *CS = cast<CapturedStmt>(AStmt);
  9139. // 1.2.2 OpenMP Language Terminology
  9140. // Structured block - An executable statement with a single entry at the
  9141. // top and a single exit at the bottom.
  9142. // The point of exit cannot be a branch out of the structured block.
  9143. // longjmp() and throw() must not violate the entry/exit criteria.
  9144. CS->getCapturedDecl()->setNothrow();
  9145. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  9146. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9147. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9148. // 1.2.2 OpenMP Language Terminology
  9149. // Structured block - An executable statement with a single entry at the
  9150. // top and a single exit at the bottom.
  9151. // The point of exit cannot be a branch out of the structured block.
  9152. // longjmp() and throw() must not violate the entry/exit criteria.
  9153. CS->getCapturedDecl()->setNothrow();
  9154. }
  9155. OMPLoopDirective::HelperExprs B;
  9156. // In presence of clause 'collapse' with number of loops, it will
  9157. // define the nested loops number.
  9158. unsigned NestedLoopCount =
  9159. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  9160. nullptr /*ordered not a clause on distribute*/, CS, *this,
  9161. *DSAStack, VarsWithImplicitDSA, B);
  9162. if (NestedLoopCount == 0)
  9163. return StmtError();
  9164. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9165. "omp teams distribute loop exprs were not built");
  9166. setFunctionHasBranchProtectedScope();
  9167. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9168. return OMPTeamsDistributeDirective::Create(
  9169. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9170. }
  9171. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  9172. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9173. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9174. if (!AStmt)
  9175. return StmtError();
  9176. auto *CS = cast<CapturedStmt>(AStmt);
  9177. // 1.2.2 OpenMP Language Terminology
  9178. // Structured block - An executable statement with a single entry at the
  9179. // top and a single exit at the bottom.
  9180. // The point of exit cannot be a branch out of the structured block.
  9181. // longjmp() and throw() must not violate the entry/exit criteria.
  9182. CS->getCapturedDecl()->setNothrow();
  9183. for (int ThisCaptureLevel =
  9184. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  9185. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9186. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9187. // 1.2.2 OpenMP Language Terminology
  9188. // Structured block - An executable statement with a single entry at the
  9189. // top and a single exit at the bottom.
  9190. // The point of exit cannot be a branch out of the structured block.
  9191. // longjmp() and throw() must not violate the entry/exit criteria.
  9192. CS->getCapturedDecl()->setNothrow();
  9193. }
  9194. OMPLoopDirective::HelperExprs B;
  9195. // In presence of clause 'collapse' with number of loops, it will
  9196. // define the nested loops number.
  9197. unsigned NestedLoopCount = checkOpenMPLoop(
  9198. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  9199. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9200. VarsWithImplicitDSA, B);
  9201. if (NestedLoopCount == 0)
  9202. return StmtError();
  9203. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9204. "omp teams distribute simd loop exprs were not built");
  9205. if (!CurContext->isDependentContext()) {
  9206. // Finalize the clauses that need pre-built expressions for CodeGen.
  9207. for (OMPClause *C : Clauses) {
  9208. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9209. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9210. B.NumIterations, *this, CurScope,
  9211. DSAStack))
  9212. return StmtError();
  9213. }
  9214. }
  9215. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9216. return StmtError();
  9217. setFunctionHasBranchProtectedScope();
  9218. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9219. return OMPTeamsDistributeSimdDirective::Create(
  9220. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9221. }
  9222. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  9223. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9224. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9225. if (!AStmt)
  9226. return StmtError();
  9227. auto *CS = cast<CapturedStmt>(AStmt);
  9228. // 1.2.2 OpenMP Language Terminology
  9229. // Structured block - An executable statement with a single entry at the
  9230. // top and a single exit at the bottom.
  9231. // The point of exit cannot be a branch out of the structured block.
  9232. // longjmp() and throw() must not violate the entry/exit criteria.
  9233. CS->getCapturedDecl()->setNothrow();
  9234. for (int ThisCaptureLevel =
  9235. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  9236. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9237. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9238. // 1.2.2 OpenMP Language Terminology
  9239. // Structured block - An executable statement with a single entry at the
  9240. // top and a single exit at the bottom.
  9241. // The point of exit cannot be a branch out of the structured block.
  9242. // longjmp() and throw() must not violate the entry/exit criteria.
  9243. CS->getCapturedDecl()->setNothrow();
  9244. }
  9245. OMPLoopDirective::HelperExprs B;
  9246. // In presence of clause 'collapse' with number of loops, it will
  9247. // define the nested loops number.
  9248. unsigned NestedLoopCount = checkOpenMPLoop(
  9249. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  9250. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9251. VarsWithImplicitDSA, B);
  9252. if (NestedLoopCount == 0)
  9253. return StmtError();
  9254. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9255. "omp for loop exprs were not built");
  9256. if (!CurContext->isDependentContext()) {
  9257. // Finalize the clauses that need pre-built expressions for CodeGen.
  9258. for (OMPClause *C : Clauses) {
  9259. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9260. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9261. B.NumIterations, *this, CurScope,
  9262. DSAStack))
  9263. return StmtError();
  9264. }
  9265. }
  9266. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9267. return StmtError();
  9268. setFunctionHasBranchProtectedScope();
  9269. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9270. return OMPTeamsDistributeParallelForSimdDirective::Create(
  9271. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9272. }
  9273. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  9274. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9275. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9276. if (!AStmt)
  9277. return StmtError();
  9278. auto *CS = cast<CapturedStmt>(AStmt);
  9279. // 1.2.2 OpenMP Language Terminology
  9280. // Structured block - An executable statement with a single entry at the
  9281. // top and a single exit at the bottom.
  9282. // The point of exit cannot be a branch out of the structured block.
  9283. // longjmp() and throw() must not violate the entry/exit criteria.
  9284. CS->getCapturedDecl()->setNothrow();
  9285. for (int ThisCaptureLevel =
  9286. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  9287. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9288. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9289. // 1.2.2 OpenMP Language Terminology
  9290. // Structured block - An executable statement with a single entry at the
  9291. // top and a single exit at the bottom.
  9292. // The point of exit cannot be a branch out of the structured block.
  9293. // longjmp() and throw() must not violate the entry/exit criteria.
  9294. CS->getCapturedDecl()->setNothrow();
  9295. }
  9296. OMPLoopDirective::HelperExprs B;
  9297. // In presence of clause 'collapse' with number of loops, it will
  9298. // define the nested loops number.
  9299. unsigned NestedLoopCount = checkOpenMPLoop(
  9300. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9301. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9302. VarsWithImplicitDSA, B);
  9303. if (NestedLoopCount == 0)
  9304. return StmtError();
  9305. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9306. "omp for loop exprs were not built");
  9307. setFunctionHasBranchProtectedScope();
  9308. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9309. return OMPTeamsDistributeParallelForDirective::Create(
  9310. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9311. DSAStack->isCancelRegion());
  9312. }
  9313. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  9314. Stmt *AStmt,
  9315. SourceLocation StartLoc,
  9316. SourceLocation EndLoc) {
  9317. if (!AStmt)
  9318. return StmtError();
  9319. auto *CS = cast<CapturedStmt>(AStmt);
  9320. // 1.2.2 OpenMP Language Terminology
  9321. // Structured block - An executable statement with a single entry at the
  9322. // top and a single exit at the bottom.
  9323. // The point of exit cannot be a branch out of the structured block.
  9324. // longjmp() and throw() must not violate the entry/exit criteria.
  9325. CS->getCapturedDecl()->setNothrow();
  9326. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  9327. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9328. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9329. // 1.2.2 OpenMP Language Terminology
  9330. // Structured block - An executable statement with a single entry at the
  9331. // top and a single exit at the bottom.
  9332. // The point of exit cannot be a branch out of the structured block.
  9333. // longjmp() and throw() must not violate the entry/exit criteria.
  9334. CS->getCapturedDecl()->setNothrow();
  9335. }
  9336. setFunctionHasBranchProtectedScope();
  9337. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  9338. AStmt);
  9339. }
  9340. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  9341. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9342. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9343. if (!AStmt)
  9344. return StmtError();
  9345. auto *CS = cast<CapturedStmt>(AStmt);
  9346. // 1.2.2 OpenMP Language Terminology
  9347. // Structured block - An executable statement with a single entry at the
  9348. // top and a single exit at the bottom.
  9349. // The point of exit cannot be a branch out of the structured block.
  9350. // longjmp() and throw() must not violate the entry/exit criteria.
  9351. CS->getCapturedDecl()->setNothrow();
  9352. for (int ThisCaptureLevel =
  9353. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  9354. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9355. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9356. // 1.2.2 OpenMP Language Terminology
  9357. // Structured block - An executable statement with a single entry at the
  9358. // top and a single exit at the bottom.
  9359. // The point of exit cannot be a branch out of the structured block.
  9360. // longjmp() and throw() must not violate the entry/exit criteria.
  9361. CS->getCapturedDecl()->setNothrow();
  9362. }
  9363. OMPLoopDirective::HelperExprs B;
  9364. // In presence of clause 'collapse' with number of loops, it will
  9365. // define the nested loops number.
  9366. unsigned NestedLoopCount = checkOpenMPLoop(
  9367. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  9368. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9369. VarsWithImplicitDSA, B);
  9370. if (NestedLoopCount == 0)
  9371. return StmtError();
  9372. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9373. "omp target teams distribute loop exprs were not built");
  9374. setFunctionHasBranchProtectedScope();
  9375. return OMPTargetTeamsDistributeDirective::Create(
  9376. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9377. }
  9378. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  9379. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9380. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9381. if (!AStmt)
  9382. return StmtError();
  9383. auto *CS = cast<CapturedStmt>(AStmt);
  9384. // 1.2.2 OpenMP Language Terminology
  9385. // Structured block - An executable statement with a single entry at the
  9386. // top and a single exit at the bottom.
  9387. // The point of exit cannot be a branch out of the structured block.
  9388. // longjmp() and throw() must not violate the entry/exit criteria.
  9389. CS->getCapturedDecl()->setNothrow();
  9390. for (int ThisCaptureLevel =
  9391. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  9392. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9393. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9394. // 1.2.2 OpenMP Language Terminology
  9395. // Structured block - An executable statement with a single entry at the
  9396. // top and a single exit at the bottom.
  9397. // The point of exit cannot be a branch out of the structured block.
  9398. // longjmp() and throw() must not violate the entry/exit criteria.
  9399. CS->getCapturedDecl()->setNothrow();
  9400. }
  9401. OMPLoopDirective::HelperExprs B;
  9402. // In presence of clause 'collapse' with number of loops, it will
  9403. // define the nested loops number.
  9404. unsigned NestedLoopCount = checkOpenMPLoop(
  9405. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9406. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9407. VarsWithImplicitDSA, B);
  9408. if (NestedLoopCount == 0)
  9409. return StmtError();
  9410. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9411. "omp target teams distribute parallel for loop exprs were not built");
  9412. if (!CurContext->isDependentContext()) {
  9413. // Finalize the clauses that need pre-built expressions for CodeGen.
  9414. for (OMPClause *C : Clauses) {
  9415. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9416. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9417. B.NumIterations, *this, CurScope,
  9418. DSAStack))
  9419. return StmtError();
  9420. }
  9421. }
  9422. setFunctionHasBranchProtectedScope();
  9423. return OMPTargetTeamsDistributeParallelForDirective::Create(
  9424. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9425. DSAStack->isCancelRegion());
  9426. }
  9427. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  9428. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9429. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9430. if (!AStmt)
  9431. return StmtError();
  9432. auto *CS = cast<CapturedStmt>(AStmt);
  9433. // 1.2.2 OpenMP Language Terminology
  9434. // Structured block - An executable statement with a single entry at the
  9435. // top and a single exit at the bottom.
  9436. // The point of exit cannot be a branch out of the structured block.
  9437. // longjmp() and throw() must not violate the entry/exit criteria.
  9438. CS->getCapturedDecl()->setNothrow();
  9439. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  9440. OMPD_target_teams_distribute_parallel_for_simd);
  9441. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9442. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9443. // 1.2.2 OpenMP Language Terminology
  9444. // Structured block - An executable statement with a single entry at the
  9445. // top and a single exit at the bottom.
  9446. // The point of exit cannot be a branch out of the structured block.
  9447. // longjmp() and throw() must not violate the entry/exit criteria.
  9448. CS->getCapturedDecl()->setNothrow();
  9449. }
  9450. OMPLoopDirective::HelperExprs B;
  9451. // In presence of clause 'collapse' with number of loops, it will
  9452. // define the nested loops number.
  9453. unsigned NestedLoopCount =
  9454. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  9455. getCollapseNumberExpr(Clauses),
  9456. nullptr /*ordered not a clause on distribute*/, CS, *this,
  9457. *DSAStack, VarsWithImplicitDSA, B);
  9458. if (NestedLoopCount == 0)
  9459. return StmtError();
  9460. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9461. "omp target teams distribute parallel for simd loop exprs were not "
  9462. "built");
  9463. if (!CurContext->isDependentContext()) {
  9464. // Finalize the clauses that need pre-built expressions for CodeGen.
  9465. for (OMPClause *C : Clauses) {
  9466. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9467. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9468. B.NumIterations, *this, CurScope,
  9469. DSAStack))
  9470. return StmtError();
  9471. }
  9472. }
  9473. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9474. return StmtError();
  9475. setFunctionHasBranchProtectedScope();
  9476. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  9477. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9478. }
  9479. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  9480. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9481. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9482. if (!AStmt)
  9483. return StmtError();
  9484. auto *CS = cast<CapturedStmt>(AStmt);
  9485. // 1.2.2 OpenMP Language Terminology
  9486. // Structured block - An executable statement with a single entry at the
  9487. // top and a single exit at the bottom.
  9488. // The point of exit cannot be a branch out of the structured block.
  9489. // longjmp() and throw() must not violate the entry/exit criteria.
  9490. CS->getCapturedDecl()->setNothrow();
  9491. for (int ThisCaptureLevel =
  9492. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  9493. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9494. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9495. // 1.2.2 OpenMP Language Terminology
  9496. // Structured block - An executable statement with a single entry at the
  9497. // top and a single exit at the bottom.
  9498. // The point of exit cannot be a branch out of the structured block.
  9499. // longjmp() and throw() must not violate the entry/exit criteria.
  9500. CS->getCapturedDecl()->setNothrow();
  9501. }
  9502. OMPLoopDirective::HelperExprs B;
  9503. // In presence of clause 'collapse' with number of loops, it will
  9504. // define the nested loops number.
  9505. unsigned NestedLoopCount = checkOpenMPLoop(
  9506. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  9507. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9508. VarsWithImplicitDSA, B);
  9509. if (NestedLoopCount == 0)
  9510. return StmtError();
  9511. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9512. "omp target teams distribute simd loop exprs were not built");
  9513. if (!CurContext->isDependentContext()) {
  9514. // Finalize the clauses that need pre-built expressions for CodeGen.
  9515. for (OMPClause *C : Clauses) {
  9516. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9517. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9518. B.NumIterations, *this, CurScope,
  9519. DSAStack))
  9520. return StmtError();
  9521. }
  9522. }
  9523. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9524. return StmtError();
  9525. setFunctionHasBranchProtectedScope();
  9526. return OMPTargetTeamsDistributeSimdDirective::Create(
  9527. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9528. }
  9529. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  9530. SourceLocation StartLoc,
  9531. SourceLocation LParenLoc,
  9532. SourceLocation EndLoc) {
  9533. OMPClause *Res = nullptr;
  9534. switch (Kind) {
  9535. case OMPC_final:
  9536. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  9537. break;
  9538. case OMPC_num_threads:
  9539. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9540. break;
  9541. case OMPC_safelen:
  9542. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9543. break;
  9544. case OMPC_simdlen:
  9545. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9546. break;
  9547. case OMPC_allocator:
  9548. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  9549. break;
  9550. case OMPC_collapse:
  9551. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  9552. break;
  9553. case OMPC_ordered:
  9554. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  9555. break;
  9556. case OMPC_device:
  9557. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  9558. break;
  9559. case OMPC_num_teams:
  9560. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9561. break;
  9562. case OMPC_thread_limit:
  9563. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  9564. break;
  9565. case OMPC_priority:
  9566. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  9567. break;
  9568. case OMPC_grainsize:
  9569. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  9570. break;
  9571. case OMPC_num_tasks:
  9572. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  9573. break;
  9574. case OMPC_hint:
  9575. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  9576. break;
  9577. case OMPC_if:
  9578. case OMPC_default:
  9579. case OMPC_proc_bind:
  9580. case OMPC_schedule:
  9581. case OMPC_private:
  9582. case OMPC_firstprivate:
  9583. case OMPC_lastprivate:
  9584. case OMPC_shared:
  9585. case OMPC_reduction:
  9586. case OMPC_task_reduction:
  9587. case OMPC_in_reduction:
  9588. case OMPC_linear:
  9589. case OMPC_aligned:
  9590. case OMPC_copyin:
  9591. case OMPC_copyprivate:
  9592. case OMPC_nowait:
  9593. case OMPC_untied:
  9594. case OMPC_mergeable:
  9595. case OMPC_threadprivate:
  9596. case OMPC_allocate:
  9597. case OMPC_flush:
  9598. case OMPC_read:
  9599. case OMPC_write:
  9600. case OMPC_update:
  9601. case OMPC_capture:
  9602. case OMPC_seq_cst:
  9603. case OMPC_depend:
  9604. case OMPC_threads:
  9605. case OMPC_simd:
  9606. case OMPC_map:
  9607. case OMPC_nogroup:
  9608. case OMPC_dist_schedule:
  9609. case OMPC_defaultmap:
  9610. case OMPC_unknown:
  9611. case OMPC_uniform:
  9612. case OMPC_to:
  9613. case OMPC_from:
  9614. case OMPC_use_device_ptr:
  9615. case OMPC_is_device_ptr:
  9616. case OMPC_unified_address:
  9617. case OMPC_unified_shared_memory:
  9618. case OMPC_reverse_offload:
  9619. case OMPC_dynamic_allocators:
  9620. case OMPC_atomic_default_mem_order:
  9621. case OMPC_device_type:
  9622. case OMPC_match:
  9623. llvm_unreachable("Clause is not allowed.");
  9624. }
  9625. return Res;
  9626. }
  9627. // An OpenMP directive such as 'target parallel' has two captured regions:
  9628. // for the 'target' and 'parallel' respectively. This function returns
  9629. // the region in which to capture expressions associated with a clause.
  9630. // A return value of OMPD_unknown signifies that the expression should not
  9631. // be captured.
  9632. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  9633. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  9634. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  9635. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  9636. switch (CKind) {
  9637. case OMPC_if:
  9638. switch (DKind) {
  9639. case OMPD_target_parallel:
  9640. case OMPD_target_parallel_for:
  9641. case OMPD_target_parallel_for_simd:
  9642. // If this clause applies to the nested 'parallel' region, capture within
  9643. // the 'target' region, otherwise do not capture.
  9644. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9645. CaptureRegion = OMPD_target;
  9646. break;
  9647. case OMPD_target_teams_distribute_parallel_for:
  9648. case OMPD_target_teams_distribute_parallel_for_simd:
  9649. // If this clause applies to the nested 'parallel' region, capture within
  9650. // the 'teams' region, otherwise do not capture.
  9651. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9652. CaptureRegion = OMPD_teams;
  9653. break;
  9654. case OMPD_teams_distribute_parallel_for:
  9655. case OMPD_teams_distribute_parallel_for_simd:
  9656. CaptureRegion = OMPD_teams;
  9657. break;
  9658. case OMPD_target_update:
  9659. case OMPD_target_enter_data:
  9660. case OMPD_target_exit_data:
  9661. CaptureRegion = OMPD_task;
  9662. break;
  9663. case OMPD_parallel_master_taskloop:
  9664. if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
  9665. CaptureRegion = OMPD_parallel;
  9666. break;
  9667. case OMPD_cancel:
  9668. case OMPD_parallel:
  9669. case OMPD_parallel_sections:
  9670. case OMPD_parallel_for:
  9671. case OMPD_parallel_for_simd:
  9672. case OMPD_target:
  9673. case OMPD_target_simd:
  9674. case OMPD_target_teams:
  9675. case OMPD_target_teams_distribute:
  9676. case OMPD_target_teams_distribute_simd:
  9677. case OMPD_distribute_parallel_for:
  9678. case OMPD_distribute_parallel_for_simd:
  9679. case OMPD_task:
  9680. case OMPD_taskloop:
  9681. case OMPD_taskloop_simd:
  9682. case OMPD_master_taskloop:
  9683. case OMPD_master_taskloop_simd:
  9684. case OMPD_target_data:
  9685. // Do not capture if-clause expressions.
  9686. break;
  9687. case OMPD_threadprivate:
  9688. case OMPD_allocate:
  9689. case OMPD_taskyield:
  9690. case OMPD_barrier:
  9691. case OMPD_taskwait:
  9692. case OMPD_cancellation_point:
  9693. case OMPD_flush:
  9694. case OMPD_declare_reduction:
  9695. case OMPD_declare_mapper:
  9696. case OMPD_declare_simd:
  9697. case OMPD_declare_variant:
  9698. case OMPD_declare_target:
  9699. case OMPD_end_declare_target:
  9700. case OMPD_teams:
  9701. case OMPD_simd:
  9702. case OMPD_for:
  9703. case OMPD_for_simd:
  9704. case OMPD_sections:
  9705. case OMPD_section:
  9706. case OMPD_single:
  9707. case OMPD_master:
  9708. case OMPD_critical:
  9709. case OMPD_taskgroup:
  9710. case OMPD_distribute:
  9711. case OMPD_ordered:
  9712. case OMPD_atomic:
  9713. case OMPD_distribute_simd:
  9714. case OMPD_teams_distribute:
  9715. case OMPD_teams_distribute_simd:
  9716. case OMPD_requires:
  9717. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  9718. case OMPD_unknown:
  9719. llvm_unreachable("Unknown OpenMP directive");
  9720. }
  9721. break;
  9722. case OMPC_num_threads:
  9723. switch (DKind) {
  9724. case OMPD_target_parallel:
  9725. case OMPD_target_parallel_for:
  9726. case OMPD_target_parallel_for_simd:
  9727. CaptureRegion = OMPD_target;
  9728. break;
  9729. case OMPD_teams_distribute_parallel_for:
  9730. case OMPD_teams_distribute_parallel_for_simd:
  9731. case OMPD_target_teams_distribute_parallel_for:
  9732. case OMPD_target_teams_distribute_parallel_for_simd:
  9733. CaptureRegion = OMPD_teams;
  9734. break;
  9735. case OMPD_parallel:
  9736. case OMPD_parallel_sections:
  9737. case OMPD_parallel_for:
  9738. case OMPD_parallel_for_simd:
  9739. case OMPD_distribute_parallel_for:
  9740. case OMPD_distribute_parallel_for_simd:
  9741. case OMPD_parallel_master_taskloop:
  9742. // Do not capture num_threads-clause expressions.
  9743. break;
  9744. case OMPD_target_data:
  9745. case OMPD_target_enter_data:
  9746. case OMPD_target_exit_data:
  9747. case OMPD_target_update:
  9748. case OMPD_target:
  9749. case OMPD_target_simd:
  9750. case OMPD_target_teams:
  9751. case OMPD_target_teams_distribute:
  9752. case OMPD_target_teams_distribute_simd:
  9753. case OMPD_cancel:
  9754. case OMPD_task:
  9755. case OMPD_taskloop:
  9756. case OMPD_taskloop_simd:
  9757. case OMPD_master_taskloop:
  9758. case OMPD_master_taskloop_simd:
  9759. case OMPD_threadprivate:
  9760. case OMPD_allocate:
  9761. case OMPD_taskyield:
  9762. case OMPD_barrier:
  9763. case OMPD_taskwait:
  9764. case OMPD_cancellation_point:
  9765. case OMPD_flush:
  9766. case OMPD_declare_reduction:
  9767. case OMPD_declare_mapper:
  9768. case OMPD_declare_simd:
  9769. case OMPD_declare_variant:
  9770. case OMPD_declare_target:
  9771. case OMPD_end_declare_target:
  9772. case OMPD_teams:
  9773. case OMPD_simd:
  9774. case OMPD_for:
  9775. case OMPD_for_simd:
  9776. case OMPD_sections:
  9777. case OMPD_section:
  9778. case OMPD_single:
  9779. case OMPD_master:
  9780. case OMPD_critical:
  9781. case OMPD_taskgroup:
  9782. case OMPD_distribute:
  9783. case OMPD_ordered:
  9784. case OMPD_atomic:
  9785. case OMPD_distribute_simd:
  9786. case OMPD_teams_distribute:
  9787. case OMPD_teams_distribute_simd:
  9788. case OMPD_requires:
  9789. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  9790. case OMPD_unknown:
  9791. llvm_unreachable("Unknown OpenMP directive");
  9792. }
  9793. break;
  9794. case OMPC_num_teams:
  9795. switch (DKind) {
  9796. case OMPD_target_teams:
  9797. case OMPD_target_teams_distribute:
  9798. case OMPD_target_teams_distribute_simd:
  9799. case OMPD_target_teams_distribute_parallel_for:
  9800. case OMPD_target_teams_distribute_parallel_for_simd:
  9801. CaptureRegion = OMPD_target;
  9802. break;
  9803. case OMPD_teams_distribute_parallel_for:
  9804. case OMPD_teams_distribute_parallel_for_simd:
  9805. case OMPD_teams:
  9806. case OMPD_teams_distribute:
  9807. case OMPD_teams_distribute_simd:
  9808. // Do not capture num_teams-clause expressions.
  9809. break;
  9810. case OMPD_distribute_parallel_for:
  9811. case OMPD_distribute_parallel_for_simd:
  9812. case OMPD_task:
  9813. case OMPD_taskloop:
  9814. case OMPD_taskloop_simd:
  9815. case OMPD_master_taskloop:
  9816. case OMPD_master_taskloop_simd:
  9817. case OMPD_parallel_master_taskloop:
  9818. case OMPD_target_data:
  9819. case OMPD_target_enter_data:
  9820. case OMPD_target_exit_data:
  9821. case OMPD_target_update:
  9822. case OMPD_cancel:
  9823. case OMPD_parallel:
  9824. case OMPD_parallel_sections:
  9825. case OMPD_parallel_for:
  9826. case OMPD_parallel_for_simd:
  9827. case OMPD_target:
  9828. case OMPD_target_simd:
  9829. case OMPD_target_parallel:
  9830. case OMPD_target_parallel_for:
  9831. case OMPD_target_parallel_for_simd:
  9832. case OMPD_threadprivate:
  9833. case OMPD_allocate:
  9834. case OMPD_taskyield:
  9835. case OMPD_barrier:
  9836. case OMPD_taskwait:
  9837. case OMPD_cancellation_point:
  9838. case OMPD_flush:
  9839. case OMPD_declare_reduction:
  9840. case OMPD_declare_mapper:
  9841. case OMPD_declare_simd:
  9842. case OMPD_declare_variant:
  9843. case OMPD_declare_target:
  9844. case OMPD_end_declare_target:
  9845. case OMPD_simd:
  9846. case OMPD_for:
  9847. case OMPD_for_simd:
  9848. case OMPD_sections:
  9849. case OMPD_section:
  9850. case OMPD_single:
  9851. case OMPD_master:
  9852. case OMPD_critical:
  9853. case OMPD_taskgroup:
  9854. case OMPD_distribute:
  9855. case OMPD_ordered:
  9856. case OMPD_atomic:
  9857. case OMPD_distribute_simd:
  9858. case OMPD_requires:
  9859. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9860. case OMPD_unknown:
  9861. llvm_unreachable("Unknown OpenMP directive");
  9862. }
  9863. break;
  9864. case OMPC_thread_limit:
  9865. switch (DKind) {
  9866. case OMPD_target_teams:
  9867. case OMPD_target_teams_distribute:
  9868. case OMPD_target_teams_distribute_simd:
  9869. case OMPD_target_teams_distribute_parallel_for:
  9870. case OMPD_target_teams_distribute_parallel_for_simd:
  9871. CaptureRegion = OMPD_target;
  9872. break;
  9873. case OMPD_teams_distribute_parallel_for:
  9874. case OMPD_teams_distribute_parallel_for_simd:
  9875. case OMPD_teams:
  9876. case OMPD_teams_distribute:
  9877. case OMPD_teams_distribute_simd:
  9878. // Do not capture thread_limit-clause expressions.
  9879. break;
  9880. case OMPD_distribute_parallel_for:
  9881. case OMPD_distribute_parallel_for_simd:
  9882. case OMPD_task:
  9883. case OMPD_taskloop:
  9884. case OMPD_taskloop_simd:
  9885. case OMPD_master_taskloop:
  9886. case OMPD_master_taskloop_simd:
  9887. case OMPD_parallel_master_taskloop:
  9888. case OMPD_target_data:
  9889. case OMPD_target_enter_data:
  9890. case OMPD_target_exit_data:
  9891. case OMPD_target_update:
  9892. case OMPD_cancel:
  9893. case OMPD_parallel:
  9894. case OMPD_parallel_sections:
  9895. case OMPD_parallel_for:
  9896. case OMPD_parallel_for_simd:
  9897. case OMPD_target:
  9898. case OMPD_target_simd:
  9899. case OMPD_target_parallel:
  9900. case OMPD_target_parallel_for:
  9901. case OMPD_target_parallel_for_simd:
  9902. case OMPD_threadprivate:
  9903. case OMPD_allocate:
  9904. case OMPD_taskyield:
  9905. case OMPD_barrier:
  9906. case OMPD_taskwait:
  9907. case OMPD_cancellation_point:
  9908. case OMPD_flush:
  9909. case OMPD_declare_reduction:
  9910. case OMPD_declare_mapper:
  9911. case OMPD_declare_simd:
  9912. case OMPD_declare_variant:
  9913. case OMPD_declare_target:
  9914. case OMPD_end_declare_target:
  9915. case OMPD_simd:
  9916. case OMPD_for:
  9917. case OMPD_for_simd:
  9918. case OMPD_sections:
  9919. case OMPD_section:
  9920. case OMPD_single:
  9921. case OMPD_master:
  9922. case OMPD_critical:
  9923. case OMPD_taskgroup:
  9924. case OMPD_distribute:
  9925. case OMPD_ordered:
  9926. case OMPD_atomic:
  9927. case OMPD_distribute_simd:
  9928. case OMPD_requires:
  9929. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  9930. case OMPD_unknown:
  9931. llvm_unreachable("Unknown OpenMP directive");
  9932. }
  9933. break;
  9934. case OMPC_schedule:
  9935. switch (DKind) {
  9936. case OMPD_parallel_for:
  9937. case OMPD_parallel_for_simd:
  9938. case OMPD_distribute_parallel_for:
  9939. case OMPD_distribute_parallel_for_simd:
  9940. case OMPD_teams_distribute_parallel_for:
  9941. case OMPD_teams_distribute_parallel_for_simd:
  9942. case OMPD_target_parallel_for:
  9943. case OMPD_target_parallel_for_simd:
  9944. case OMPD_target_teams_distribute_parallel_for:
  9945. case OMPD_target_teams_distribute_parallel_for_simd:
  9946. CaptureRegion = OMPD_parallel;
  9947. break;
  9948. case OMPD_for:
  9949. case OMPD_for_simd:
  9950. // Do not capture schedule-clause expressions.
  9951. break;
  9952. case OMPD_task:
  9953. case OMPD_taskloop:
  9954. case OMPD_taskloop_simd:
  9955. case OMPD_master_taskloop:
  9956. case OMPD_master_taskloop_simd:
  9957. case OMPD_parallel_master_taskloop:
  9958. case OMPD_target_data:
  9959. case OMPD_target_enter_data:
  9960. case OMPD_target_exit_data:
  9961. case OMPD_target_update:
  9962. case OMPD_teams:
  9963. case OMPD_teams_distribute:
  9964. case OMPD_teams_distribute_simd:
  9965. case OMPD_target_teams_distribute:
  9966. case OMPD_target_teams_distribute_simd:
  9967. case OMPD_target:
  9968. case OMPD_target_simd:
  9969. case OMPD_target_parallel:
  9970. case OMPD_cancel:
  9971. case OMPD_parallel:
  9972. case OMPD_parallel_sections:
  9973. case OMPD_threadprivate:
  9974. case OMPD_allocate:
  9975. case OMPD_taskyield:
  9976. case OMPD_barrier:
  9977. case OMPD_taskwait:
  9978. case OMPD_cancellation_point:
  9979. case OMPD_flush:
  9980. case OMPD_declare_reduction:
  9981. case OMPD_declare_mapper:
  9982. case OMPD_declare_simd:
  9983. case OMPD_declare_variant:
  9984. case OMPD_declare_target:
  9985. case OMPD_end_declare_target:
  9986. case OMPD_simd:
  9987. case OMPD_sections:
  9988. case OMPD_section:
  9989. case OMPD_single:
  9990. case OMPD_master:
  9991. case OMPD_critical:
  9992. case OMPD_taskgroup:
  9993. case OMPD_distribute:
  9994. case OMPD_ordered:
  9995. case OMPD_atomic:
  9996. case OMPD_distribute_simd:
  9997. case OMPD_target_teams:
  9998. case OMPD_requires:
  9999. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  10000. case OMPD_unknown:
  10001. llvm_unreachable("Unknown OpenMP directive");
  10002. }
  10003. break;
  10004. case OMPC_dist_schedule:
  10005. switch (DKind) {
  10006. case OMPD_teams_distribute_parallel_for:
  10007. case OMPD_teams_distribute_parallel_for_simd:
  10008. case OMPD_teams_distribute:
  10009. case OMPD_teams_distribute_simd:
  10010. case OMPD_target_teams_distribute_parallel_for:
  10011. case OMPD_target_teams_distribute_parallel_for_simd:
  10012. case OMPD_target_teams_distribute:
  10013. case OMPD_target_teams_distribute_simd:
  10014. CaptureRegion = OMPD_teams;
  10015. break;
  10016. case OMPD_distribute_parallel_for:
  10017. case OMPD_distribute_parallel_for_simd:
  10018. case OMPD_distribute:
  10019. case OMPD_distribute_simd:
  10020. // Do not capture thread_limit-clause expressions.
  10021. break;
  10022. case OMPD_parallel_for:
  10023. case OMPD_parallel_for_simd:
  10024. case OMPD_target_parallel_for_simd:
  10025. case OMPD_target_parallel_for:
  10026. case OMPD_task:
  10027. case OMPD_taskloop:
  10028. case OMPD_taskloop_simd:
  10029. case OMPD_master_taskloop:
  10030. case OMPD_master_taskloop_simd:
  10031. case OMPD_parallel_master_taskloop:
  10032. case OMPD_target_data:
  10033. case OMPD_target_enter_data:
  10034. case OMPD_target_exit_data:
  10035. case OMPD_target_update:
  10036. case OMPD_teams:
  10037. case OMPD_target:
  10038. case OMPD_target_simd:
  10039. case OMPD_target_parallel:
  10040. case OMPD_cancel:
  10041. case OMPD_parallel:
  10042. case OMPD_parallel_sections:
  10043. case OMPD_threadprivate:
  10044. case OMPD_allocate:
  10045. case OMPD_taskyield:
  10046. case OMPD_barrier:
  10047. case OMPD_taskwait:
  10048. case OMPD_cancellation_point:
  10049. case OMPD_flush:
  10050. case OMPD_declare_reduction:
  10051. case OMPD_declare_mapper:
  10052. case OMPD_declare_simd:
  10053. case OMPD_declare_variant:
  10054. case OMPD_declare_target:
  10055. case OMPD_end_declare_target:
  10056. case OMPD_simd:
  10057. case OMPD_for:
  10058. case OMPD_for_simd:
  10059. case OMPD_sections:
  10060. case OMPD_section:
  10061. case OMPD_single:
  10062. case OMPD_master:
  10063. case OMPD_critical:
  10064. case OMPD_taskgroup:
  10065. case OMPD_ordered:
  10066. case OMPD_atomic:
  10067. case OMPD_target_teams:
  10068. case OMPD_requires:
  10069. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  10070. case OMPD_unknown:
  10071. llvm_unreachable("Unknown OpenMP directive");
  10072. }
  10073. break;
  10074. case OMPC_device:
  10075. switch (DKind) {
  10076. case OMPD_target_update:
  10077. case OMPD_target_enter_data:
  10078. case OMPD_target_exit_data:
  10079. case OMPD_target:
  10080. case OMPD_target_simd:
  10081. case OMPD_target_teams:
  10082. case OMPD_target_parallel:
  10083. case OMPD_target_teams_distribute:
  10084. case OMPD_target_teams_distribute_simd:
  10085. case OMPD_target_parallel_for:
  10086. case OMPD_target_parallel_for_simd:
  10087. case OMPD_target_teams_distribute_parallel_for:
  10088. case OMPD_target_teams_distribute_parallel_for_simd:
  10089. CaptureRegion = OMPD_task;
  10090. break;
  10091. case OMPD_target_data:
  10092. // Do not capture device-clause expressions.
  10093. break;
  10094. case OMPD_teams_distribute_parallel_for:
  10095. case OMPD_teams_distribute_parallel_for_simd:
  10096. case OMPD_teams:
  10097. case OMPD_teams_distribute:
  10098. case OMPD_teams_distribute_simd:
  10099. case OMPD_distribute_parallel_for:
  10100. case OMPD_distribute_parallel_for_simd:
  10101. case OMPD_task:
  10102. case OMPD_taskloop:
  10103. case OMPD_taskloop_simd:
  10104. case OMPD_master_taskloop:
  10105. case OMPD_master_taskloop_simd:
  10106. case OMPD_parallel_master_taskloop:
  10107. case OMPD_cancel:
  10108. case OMPD_parallel:
  10109. case OMPD_parallel_sections:
  10110. case OMPD_parallel_for:
  10111. case OMPD_parallel_for_simd:
  10112. case OMPD_threadprivate:
  10113. case OMPD_allocate:
  10114. case OMPD_taskyield:
  10115. case OMPD_barrier:
  10116. case OMPD_taskwait:
  10117. case OMPD_cancellation_point:
  10118. case OMPD_flush:
  10119. case OMPD_declare_reduction:
  10120. case OMPD_declare_mapper:
  10121. case OMPD_declare_simd:
  10122. case OMPD_declare_variant:
  10123. case OMPD_declare_target:
  10124. case OMPD_end_declare_target:
  10125. case OMPD_simd:
  10126. case OMPD_for:
  10127. case OMPD_for_simd:
  10128. case OMPD_sections:
  10129. case OMPD_section:
  10130. case OMPD_single:
  10131. case OMPD_master:
  10132. case OMPD_critical:
  10133. case OMPD_taskgroup:
  10134. case OMPD_distribute:
  10135. case OMPD_ordered:
  10136. case OMPD_atomic:
  10137. case OMPD_distribute_simd:
  10138. case OMPD_requires:
  10139. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  10140. case OMPD_unknown:
  10141. llvm_unreachable("Unknown OpenMP directive");
  10142. }
  10143. break;
  10144. case OMPC_grainsize:
  10145. case OMPC_num_tasks:
  10146. case OMPC_final:
  10147. case OMPC_priority:
  10148. switch (DKind) {
  10149. case OMPD_task:
  10150. case OMPD_taskloop:
  10151. case OMPD_taskloop_simd:
  10152. case OMPD_master_taskloop:
  10153. case OMPD_master_taskloop_simd:
  10154. break;
  10155. case OMPD_parallel_master_taskloop:
  10156. CaptureRegion = OMPD_parallel;
  10157. break;
  10158. case OMPD_target_update:
  10159. case OMPD_target_enter_data:
  10160. case OMPD_target_exit_data:
  10161. case OMPD_target:
  10162. case OMPD_target_simd:
  10163. case OMPD_target_teams:
  10164. case OMPD_target_parallel:
  10165. case OMPD_target_teams_distribute:
  10166. case OMPD_target_teams_distribute_simd:
  10167. case OMPD_target_parallel_for:
  10168. case OMPD_target_parallel_for_simd:
  10169. case OMPD_target_teams_distribute_parallel_for:
  10170. case OMPD_target_teams_distribute_parallel_for_simd:
  10171. case OMPD_target_data:
  10172. case OMPD_teams_distribute_parallel_for:
  10173. case OMPD_teams_distribute_parallel_for_simd:
  10174. case OMPD_teams:
  10175. case OMPD_teams_distribute:
  10176. case OMPD_teams_distribute_simd:
  10177. case OMPD_distribute_parallel_for:
  10178. case OMPD_distribute_parallel_for_simd:
  10179. case OMPD_cancel:
  10180. case OMPD_parallel:
  10181. case OMPD_parallel_sections:
  10182. case OMPD_parallel_for:
  10183. case OMPD_parallel_for_simd:
  10184. case OMPD_threadprivate:
  10185. case OMPD_allocate:
  10186. case OMPD_taskyield:
  10187. case OMPD_barrier:
  10188. case OMPD_taskwait:
  10189. case OMPD_cancellation_point:
  10190. case OMPD_flush:
  10191. case OMPD_declare_reduction:
  10192. case OMPD_declare_mapper:
  10193. case OMPD_declare_simd:
  10194. case OMPD_declare_variant:
  10195. case OMPD_declare_target:
  10196. case OMPD_end_declare_target:
  10197. case OMPD_simd:
  10198. case OMPD_for:
  10199. case OMPD_for_simd:
  10200. case OMPD_sections:
  10201. case OMPD_section:
  10202. case OMPD_single:
  10203. case OMPD_master:
  10204. case OMPD_critical:
  10205. case OMPD_taskgroup:
  10206. case OMPD_distribute:
  10207. case OMPD_ordered:
  10208. case OMPD_atomic:
  10209. case OMPD_distribute_simd:
  10210. case OMPD_requires:
  10211. llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
  10212. case OMPD_unknown:
  10213. llvm_unreachable("Unknown OpenMP directive");
  10214. }
  10215. break;
  10216. case OMPC_firstprivate:
  10217. case OMPC_lastprivate:
  10218. case OMPC_reduction:
  10219. case OMPC_task_reduction:
  10220. case OMPC_in_reduction:
  10221. case OMPC_linear:
  10222. case OMPC_default:
  10223. case OMPC_proc_bind:
  10224. case OMPC_safelen:
  10225. case OMPC_simdlen:
  10226. case OMPC_allocator:
  10227. case OMPC_collapse:
  10228. case OMPC_private:
  10229. case OMPC_shared:
  10230. case OMPC_aligned:
  10231. case OMPC_copyin:
  10232. case OMPC_copyprivate:
  10233. case OMPC_ordered:
  10234. case OMPC_nowait:
  10235. case OMPC_untied:
  10236. case OMPC_mergeable:
  10237. case OMPC_threadprivate:
  10238. case OMPC_allocate:
  10239. case OMPC_flush:
  10240. case OMPC_read:
  10241. case OMPC_write:
  10242. case OMPC_update:
  10243. case OMPC_capture:
  10244. case OMPC_seq_cst:
  10245. case OMPC_depend:
  10246. case OMPC_threads:
  10247. case OMPC_simd:
  10248. case OMPC_map:
  10249. case OMPC_nogroup:
  10250. case OMPC_hint:
  10251. case OMPC_defaultmap:
  10252. case OMPC_unknown:
  10253. case OMPC_uniform:
  10254. case OMPC_to:
  10255. case OMPC_from:
  10256. case OMPC_use_device_ptr:
  10257. case OMPC_is_device_ptr:
  10258. case OMPC_unified_address:
  10259. case OMPC_unified_shared_memory:
  10260. case OMPC_reverse_offload:
  10261. case OMPC_dynamic_allocators:
  10262. case OMPC_atomic_default_mem_order:
  10263. case OMPC_device_type:
  10264. case OMPC_match:
  10265. llvm_unreachable("Unexpected OpenMP clause.");
  10266. }
  10267. return CaptureRegion;
  10268. }
  10269. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  10270. Expr *Condition, SourceLocation StartLoc,
  10271. SourceLocation LParenLoc,
  10272. SourceLocation NameModifierLoc,
  10273. SourceLocation ColonLoc,
  10274. SourceLocation EndLoc) {
  10275. Expr *ValExpr = Condition;
  10276. Stmt *HelperValStmt = nullptr;
  10277. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  10278. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  10279. !Condition->isInstantiationDependent() &&
  10280. !Condition->containsUnexpandedParameterPack()) {
  10281. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  10282. if (Val.isInvalid())
  10283. return nullptr;
  10284. ValExpr = Val.get();
  10285. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10286. CaptureRegion =
  10287. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  10288. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10289. ValExpr = MakeFullExpr(ValExpr).get();
  10290. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10291. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10292. HelperValStmt = buildPreInits(Context, Captures);
  10293. }
  10294. }
  10295. return new (Context)
  10296. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  10297. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  10298. }
  10299. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  10300. SourceLocation StartLoc,
  10301. SourceLocation LParenLoc,
  10302. SourceLocation EndLoc) {
  10303. Expr *ValExpr = Condition;
  10304. Stmt *HelperValStmt = nullptr;
  10305. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  10306. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  10307. !Condition->isInstantiationDependent() &&
  10308. !Condition->containsUnexpandedParameterPack()) {
  10309. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  10310. if (Val.isInvalid())
  10311. return nullptr;
  10312. ValExpr = MakeFullExpr(Val.get()).get();
  10313. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10314. CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_final);
  10315. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10316. ValExpr = MakeFullExpr(ValExpr).get();
  10317. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10318. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10319. HelperValStmt = buildPreInits(Context, Captures);
  10320. }
  10321. }
  10322. return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
  10323. StartLoc, LParenLoc, EndLoc);
  10324. }
  10325. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  10326. Expr *Op) {
  10327. if (!Op)
  10328. return ExprError();
  10329. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  10330. public:
  10331. IntConvertDiagnoser()
  10332. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  10333. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10334. QualType T) override {
  10335. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  10336. }
  10337. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  10338. QualType T) override {
  10339. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  10340. }
  10341. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  10342. QualType T,
  10343. QualType ConvTy) override {
  10344. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  10345. }
  10346. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  10347. QualType ConvTy) override {
  10348. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10349. << ConvTy->isEnumeralType() << ConvTy;
  10350. }
  10351. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  10352. QualType T) override {
  10353. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  10354. }
  10355. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  10356. QualType ConvTy) override {
  10357. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10358. << ConvTy->isEnumeralType() << ConvTy;
  10359. }
  10360. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  10361. QualType) override {
  10362. llvm_unreachable("conversion functions are permitted");
  10363. }
  10364. } ConvertDiagnoser;
  10365. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  10366. }
  10367. static bool
  10368. isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
  10369. bool StrictlyPositive, bool BuildCapture = false,
  10370. OpenMPDirectiveKind DKind = OMPD_unknown,
  10371. OpenMPDirectiveKind *CaptureRegion = nullptr,
  10372. Stmt **HelperValStmt = nullptr) {
  10373. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  10374. !ValExpr->isInstantiationDependent()) {
  10375. SourceLocation Loc = ValExpr->getExprLoc();
  10376. ExprResult Value =
  10377. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  10378. if (Value.isInvalid())
  10379. return false;
  10380. ValExpr = Value.get();
  10381. // The expression must evaluate to a non-negative integer value.
  10382. llvm::APSInt Result;
  10383. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  10384. Result.isSigned() &&
  10385. !((!StrictlyPositive && Result.isNonNegative()) ||
  10386. (StrictlyPositive && Result.isStrictlyPositive()))) {
  10387. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  10388. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10389. << ValExpr->getSourceRange();
  10390. return false;
  10391. }
  10392. if (!BuildCapture)
  10393. return true;
  10394. *CaptureRegion = getOpenMPCaptureRegionForClause(DKind, CKind);
  10395. if (*CaptureRegion != OMPD_unknown &&
  10396. !SemaRef.CurContext->isDependentContext()) {
  10397. ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
  10398. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10399. ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
  10400. *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
  10401. }
  10402. }
  10403. return true;
  10404. }
  10405. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  10406. SourceLocation StartLoc,
  10407. SourceLocation LParenLoc,
  10408. SourceLocation EndLoc) {
  10409. Expr *ValExpr = NumThreads;
  10410. Stmt *HelperValStmt = nullptr;
  10411. // OpenMP [2.5, Restrictions]
  10412. // The num_threads expression must evaluate to a positive integer value.
  10413. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  10414. /*StrictlyPositive=*/true))
  10415. return nullptr;
  10416. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10417. OpenMPDirectiveKind CaptureRegion =
  10418. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  10419. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10420. ValExpr = MakeFullExpr(ValExpr).get();
  10421. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10422. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10423. HelperValStmt = buildPreInits(Context, Captures);
  10424. }
  10425. return new (Context) OMPNumThreadsClause(
  10426. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  10427. }
  10428. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  10429. OpenMPClauseKind CKind,
  10430. bool StrictlyPositive) {
  10431. if (!E)
  10432. return ExprError();
  10433. if (E->isValueDependent() || E->isTypeDependent() ||
  10434. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  10435. return E;
  10436. llvm::APSInt Result;
  10437. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  10438. if (ICE.isInvalid())
  10439. return ExprError();
  10440. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  10441. (!StrictlyPositive && !Result.isNonNegative())) {
  10442. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  10443. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10444. << E->getSourceRange();
  10445. return ExprError();
  10446. }
  10447. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  10448. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  10449. << E->getSourceRange();
  10450. return ExprError();
  10451. }
  10452. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  10453. DSAStack->setAssociatedLoops(Result.getExtValue());
  10454. else if (CKind == OMPC_ordered)
  10455. DSAStack->setAssociatedLoops(Result.getExtValue());
  10456. return ICE;
  10457. }
  10458. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  10459. SourceLocation LParenLoc,
  10460. SourceLocation EndLoc) {
  10461. // OpenMP [2.8.1, simd construct, Description]
  10462. // The parameter of the safelen clause must be a constant
  10463. // positive integer expression.
  10464. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  10465. if (Safelen.isInvalid())
  10466. return nullptr;
  10467. return new (Context)
  10468. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  10469. }
  10470. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  10471. SourceLocation LParenLoc,
  10472. SourceLocation EndLoc) {
  10473. // OpenMP [2.8.1, simd construct, Description]
  10474. // The parameter of the simdlen clause must be a constant
  10475. // positive integer expression.
  10476. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  10477. if (Simdlen.isInvalid())
  10478. return nullptr;
  10479. return new (Context)
  10480. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  10481. }
  10482. /// Tries to find omp_allocator_handle_t type.
  10483. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  10484. DSAStackTy *Stack) {
  10485. QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
  10486. if (!OMPAllocatorHandleT.isNull())
  10487. return true;
  10488. // Build the predefined allocator expressions.
  10489. bool ErrorFound = false;
  10490. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  10491. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  10492. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  10493. StringRef Allocator =
  10494. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  10495. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  10496. auto *VD = dyn_cast_or_null<ValueDecl>(
  10497. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  10498. if (!VD) {
  10499. ErrorFound = true;
  10500. break;
  10501. }
  10502. QualType AllocatorType =
  10503. VD->getType().getNonLValueExprType(S.getASTContext());
  10504. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  10505. if (!Res.isUsable()) {
  10506. ErrorFound = true;
  10507. break;
  10508. }
  10509. if (OMPAllocatorHandleT.isNull())
  10510. OMPAllocatorHandleT = AllocatorType;
  10511. if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
  10512. ErrorFound = true;
  10513. break;
  10514. }
  10515. Stack->setAllocator(AllocatorKind, Res.get());
  10516. }
  10517. if (ErrorFound) {
  10518. S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
  10519. return false;
  10520. }
  10521. OMPAllocatorHandleT.addConst();
  10522. Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
  10523. return true;
  10524. }
  10525. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  10526. SourceLocation LParenLoc,
  10527. SourceLocation EndLoc) {
  10528. // OpenMP [2.11.3, allocate Directive, Description]
  10529. // allocator is an expression of omp_allocator_handle_t type.
  10530. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  10531. return nullptr;
  10532. ExprResult Allocator = DefaultLvalueConversion(A);
  10533. if (Allocator.isInvalid())
  10534. return nullptr;
  10535. Allocator = PerformImplicitConversion(Allocator.get(),
  10536. DSAStack->getOMPAllocatorHandleT(),
  10537. Sema::AA_Initializing,
  10538. /*AllowExplicit=*/true);
  10539. if (Allocator.isInvalid())
  10540. return nullptr;
  10541. return new (Context)
  10542. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  10543. }
  10544. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  10545. SourceLocation StartLoc,
  10546. SourceLocation LParenLoc,
  10547. SourceLocation EndLoc) {
  10548. // OpenMP [2.7.1, loop construct, Description]
  10549. // OpenMP [2.8.1, simd construct, Description]
  10550. // OpenMP [2.9.6, distribute construct, Description]
  10551. // The parameter of the collapse clause must be a constant
  10552. // positive integer expression.
  10553. ExprResult NumForLoopsResult =
  10554. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  10555. if (NumForLoopsResult.isInvalid())
  10556. return nullptr;
  10557. return new (Context)
  10558. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  10559. }
  10560. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  10561. SourceLocation EndLoc,
  10562. SourceLocation LParenLoc,
  10563. Expr *NumForLoops) {
  10564. // OpenMP [2.7.1, loop construct, Description]
  10565. // OpenMP [2.8.1, simd construct, Description]
  10566. // OpenMP [2.9.6, distribute construct, Description]
  10567. // The parameter of the ordered clause must be a constant
  10568. // positive integer expression if any.
  10569. if (NumForLoops && LParenLoc.isValid()) {
  10570. ExprResult NumForLoopsResult =
  10571. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  10572. if (NumForLoopsResult.isInvalid())
  10573. return nullptr;
  10574. NumForLoops = NumForLoopsResult.get();
  10575. } else {
  10576. NumForLoops = nullptr;
  10577. }
  10578. auto *Clause = OMPOrderedClause::Create(
  10579. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  10580. StartLoc, LParenLoc, EndLoc);
  10581. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  10582. return Clause;
  10583. }
  10584. OMPClause *Sema::ActOnOpenMPSimpleClause(
  10585. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  10586. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10587. OMPClause *Res = nullptr;
  10588. switch (Kind) {
  10589. case OMPC_default:
  10590. Res =
  10591. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  10592. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10593. break;
  10594. case OMPC_proc_bind:
  10595. Res = ActOnOpenMPProcBindClause(
  10596. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  10597. LParenLoc, EndLoc);
  10598. break;
  10599. case OMPC_atomic_default_mem_order:
  10600. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  10601. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  10602. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10603. break;
  10604. case OMPC_if:
  10605. case OMPC_final:
  10606. case OMPC_num_threads:
  10607. case OMPC_safelen:
  10608. case OMPC_simdlen:
  10609. case OMPC_allocator:
  10610. case OMPC_collapse:
  10611. case OMPC_schedule:
  10612. case OMPC_private:
  10613. case OMPC_firstprivate:
  10614. case OMPC_lastprivate:
  10615. case OMPC_shared:
  10616. case OMPC_reduction:
  10617. case OMPC_task_reduction:
  10618. case OMPC_in_reduction:
  10619. case OMPC_linear:
  10620. case OMPC_aligned:
  10621. case OMPC_copyin:
  10622. case OMPC_copyprivate:
  10623. case OMPC_ordered:
  10624. case OMPC_nowait:
  10625. case OMPC_untied:
  10626. case OMPC_mergeable:
  10627. case OMPC_threadprivate:
  10628. case OMPC_allocate:
  10629. case OMPC_flush:
  10630. case OMPC_read:
  10631. case OMPC_write:
  10632. case OMPC_update:
  10633. case OMPC_capture:
  10634. case OMPC_seq_cst:
  10635. case OMPC_depend:
  10636. case OMPC_device:
  10637. case OMPC_threads:
  10638. case OMPC_simd:
  10639. case OMPC_map:
  10640. case OMPC_num_teams:
  10641. case OMPC_thread_limit:
  10642. case OMPC_priority:
  10643. case OMPC_grainsize:
  10644. case OMPC_nogroup:
  10645. case OMPC_num_tasks:
  10646. case OMPC_hint:
  10647. case OMPC_dist_schedule:
  10648. case OMPC_defaultmap:
  10649. case OMPC_unknown:
  10650. case OMPC_uniform:
  10651. case OMPC_to:
  10652. case OMPC_from:
  10653. case OMPC_use_device_ptr:
  10654. case OMPC_is_device_ptr:
  10655. case OMPC_unified_address:
  10656. case OMPC_unified_shared_memory:
  10657. case OMPC_reverse_offload:
  10658. case OMPC_dynamic_allocators:
  10659. case OMPC_device_type:
  10660. case OMPC_match:
  10661. llvm_unreachable("Clause is not allowed.");
  10662. }
  10663. return Res;
  10664. }
  10665. static std::string
  10666. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  10667. ArrayRef<unsigned> Exclude = llvm::None) {
  10668. SmallString<256> Buffer;
  10669. llvm::raw_svector_ostream Out(Buffer);
  10670. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  10671. unsigned Skipped = Exclude.size();
  10672. auto S = Exclude.begin(), E = Exclude.end();
  10673. for (unsigned I = First; I < Last; ++I) {
  10674. if (std::find(S, E, I) != E) {
  10675. --Skipped;
  10676. continue;
  10677. }
  10678. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  10679. if (I == Bound - Skipped)
  10680. Out << " or ";
  10681. else if (I != Bound + 1 - Skipped)
  10682. Out << ", ";
  10683. }
  10684. return Out.str();
  10685. }
  10686. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  10687. SourceLocation KindKwLoc,
  10688. SourceLocation StartLoc,
  10689. SourceLocation LParenLoc,
  10690. SourceLocation EndLoc) {
  10691. if (Kind == OMPC_DEFAULT_unknown) {
  10692. static_assert(OMPC_DEFAULT_unknown > 0,
  10693. "OMPC_DEFAULT_unknown not greater than 0");
  10694. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10695. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  10696. /*Last=*/OMPC_DEFAULT_unknown)
  10697. << getOpenMPClauseName(OMPC_default);
  10698. return nullptr;
  10699. }
  10700. switch (Kind) {
  10701. case OMPC_DEFAULT_none:
  10702. DSAStack->setDefaultDSANone(KindKwLoc);
  10703. break;
  10704. case OMPC_DEFAULT_shared:
  10705. DSAStack->setDefaultDSAShared(KindKwLoc);
  10706. break;
  10707. case OMPC_DEFAULT_unknown:
  10708. llvm_unreachable("Clause kind is not allowed.");
  10709. break;
  10710. }
  10711. return new (Context)
  10712. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10713. }
  10714. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  10715. SourceLocation KindKwLoc,
  10716. SourceLocation StartLoc,
  10717. SourceLocation LParenLoc,
  10718. SourceLocation EndLoc) {
  10719. if (Kind == OMPC_PROC_BIND_unknown) {
  10720. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10721. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  10722. /*Last=*/OMPC_PROC_BIND_unknown)
  10723. << getOpenMPClauseName(OMPC_proc_bind);
  10724. return nullptr;
  10725. }
  10726. return new (Context)
  10727. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10728. }
  10729. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  10730. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  10731. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10732. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  10733. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10734. << getListOfPossibleValues(
  10735. OMPC_atomic_default_mem_order, /*First=*/0,
  10736. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  10737. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  10738. return nullptr;
  10739. }
  10740. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  10741. LParenLoc, EndLoc);
  10742. }
  10743. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  10744. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  10745. SourceLocation StartLoc, SourceLocation LParenLoc,
  10746. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  10747. SourceLocation EndLoc) {
  10748. OMPClause *Res = nullptr;
  10749. switch (Kind) {
  10750. case OMPC_schedule:
  10751. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  10752. assert(Argument.size() == NumberOfElements &&
  10753. ArgumentLoc.size() == NumberOfElements);
  10754. Res = ActOnOpenMPScheduleClause(
  10755. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  10756. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  10757. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  10758. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  10759. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  10760. break;
  10761. case OMPC_if:
  10762. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  10763. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  10764. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  10765. DelimLoc, EndLoc);
  10766. break;
  10767. case OMPC_dist_schedule:
  10768. Res = ActOnOpenMPDistScheduleClause(
  10769. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  10770. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  10771. break;
  10772. case OMPC_defaultmap:
  10773. enum { Modifier, DefaultmapKind };
  10774. Res = ActOnOpenMPDefaultmapClause(
  10775. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  10776. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  10777. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  10778. EndLoc);
  10779. break;
  10780. case OMPC_final:
  10781. case OMPC_num_threads:
  10782. case OMPC_safelen:
  10783. case OMPC_simdlen:
  10784. case OMPC_allocator:
  10785. case OMPC_collapse:
  10786. case OMPC_default:
  10787. case OMPC_proc_bind:
  10788. case OMPC_private:
  10789. case OMPC_firstprivate:
  10790. case OMPC_lastprivate:
  10791. case OMPC_shared:
  10792. case OMPC_reduction:
  10793. case OMPC_task_reduction:
  10794. case OMPC_in_reduction:
  10795. case OMPC_linear:
  10796. case OMPC_aligned:
  10797. case OMPC_copyin:
  10798. case OMPC_copyprivate:
  10799. case OMPC_ordered:
  10800. case OMPC_nowait:
  10801. case OMPC_untied:
  10802. case OMPC_mergeable:
  10803. case OMPC_threadprivate:
  10804. case OMPC_allocate:
  10805. case OMPC_flush:
  10806. case OMPC_read:
  10807. case OMPC_write:
  10808. case OMPC_update:
  10809. case OMPC_capture:
  10810. case OMPC_seq_cst:
  10811. case OMPC_depend:
  10812. case OMPC_device:
  10813. case OMPC_threads:
  10814. case OMPC_simd:
  10815. case OMPC_map:
  10816. case OMPC_num_teams:
  10817. case OMPC_thread_limit:
  10818. case OMPC_priority:
  10819. case OMPC_grainsize:
  10820. case OMPC_nogroup:
  10821. case OMPC_num_tasks:
  10822. case OMPC_hint:
  10823. case OMPC_unknown:
  10824. case OMPC_uniform:
  10825. case OMPC_to:
  10826. case OMPC_from:
  10827. case OMPC_use_device_ptr:
  10828. case OMPC_is_device_ptr:
  10829. case OMPC_unified_address:
  10830. case OMPC_unified_shared_memory:
  10831. case OMPC_reverse_offload:
  10832. case OMPC_dynamic_allocators:
  10833. case OMPC_atomic_default_mem_order:
  10834. case OMPC_device_type:
  10835. case OMPC_match:
  10836. llvm_unreachable("Clause is not allowed.");
  10837. }
  10838. return Res;
  10839. }
  10840. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  10841. OpenMPScheduleClauseModifier M2,
  10842. SourceLocation M1Loc, SourceLocation M2Loc) {
  10843. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  10844. SmallVector<unsigned, 2> Excluded;
  10845. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  10846. Excluded.push_back(M2);
  10847. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  10848. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  10849. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  10850. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  10851. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  10852. << getListOfPossibleValues(OMPC_schedule,
  10853. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  10854. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10855. Excluded)
  10856. << getOpenMPClauseName(OMPC_schedule);
  10857. return true;
  10858. }
  10859. return false;
  10860. }
  10861. OMPClause *Sema::ActOnOpenMPScheduleClause(
  10862. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  10863. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  10864. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  10865. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  10866. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  10867. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  10868. return nullptr;
  10869. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10870. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  10871. // but not both.
  10872. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  10873. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  10874. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  10875. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  10876. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  10877. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  10878. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  10879. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  10880. return nullptr;
  10881. }
  10882. if (Kind == OMPC_SCHEDULE_unknown) {
  10883. std::string Values;
  10884. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  10885. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  10886. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10887. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10888. Exclude);
  10889. } else {
  10890. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10891. /*Last=*/OMPC_SCHEDULE_unknown);
  10892. }
  10893. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  10894. << Values << getOpenMPClauseName(OMPC_schedule);
  10895. return nullptr;
  10896. }
  10897. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10898. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  10899. // schedule(guided).
  10900. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  10901. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  10902. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  10903. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  10904. diag::err_omp_schedule_nonmonotonic_static);
  10905. return nullptr;
  10906. }
  10907. Expr *ValExpr = ChunkSize;
  10908. Stmt *HelperValStmt = nullptr;
  10909. if (ChunkSize) {
  10910. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  10911. !ChunkSize->isInstantiationDependent() &&
  10912. !ChunkSize->containsUnexpandedParameterPack()) {
  10913. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  10914. ExprResult Val =
  10915. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  10916. if (Val.isInvalid())
  10917. return nullptr;
  10918. ValExpr = Val.get();
  10919. // OpenMP [2.7.1, Restrictions]
  10920. // chunk_size must be a loop invariant integer expression with a positive
  10921. // value.
  10922. llvm::APSInt Result;
  10923. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  10924. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  10925. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  10926. << "schedule" << 1 << ChunkSize->getSourceRange();
  10927. return nullptr;
  10928. }
  10929. } else if (getOpenMPCaptureRegionForClause(
  10930. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  10931. OMPD_unknown &&
  10932. !CurContext->isDependentContext()) {
  10933. ValExpr = MakeFullExpr(ValExpr).get();
  10934. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10935. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10936. HelperValStmt = buildPreInits(Context, Captures);
  10937. }
  10938. }
  10939. }
  10940. return new (Context)
  10941. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  10942. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  10943. }
  10944. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  10945. SourceLocation StartLoc,
  10946. SourceLocation EndLoc) {
  10947. OMPClause *Res = nullptr;
  10948. switch (Kind) {
  10949. case OMPC_ordered:
  10950. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  10951. break;
  10952. case OMPC_nowait:
  10953. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  10954. break;
  10955. case OMPC_untied:
  10956. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  10957. break;
  10958. case OMPC_mergeable:
  10959. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  10960. break;
  10961. case OMPC_read:
  10962. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  10963. break;
  10964. case OMPC_write:
  10965. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  10966. break;
  10967. case OMPC_update:
  10968. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  10969. break;
  10970. case OMPC_capture:
  10971. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  10972. break;
  10973. case OMPC_seq_cst:
  10974. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  10975. break;
  10976. case OMPC_threads:
  10977. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  10978. break;
  10979. case OMPC_simd:
  10980. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  10981. break;
  10982. case OMPC_nogroup:
  10983. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  10984. break;
  10985. case OMPC_unified_address:
  10986. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  10987. break;
  10988. case OMPC_unified_shared_memory:
  10989. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10990. break;
  10991. case OMPC_reverse_offload:
  10992. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  10993. break;
  10994. case OMPC_dynamic_allocators:
  10995. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10996. break;
  10997. case OMPC_if:
  10998. case OMPC_final:
  10999. case OMPC_num_threads:
  11000. case OMPC_safelen:
  11001. case OMPC_simdlen:
  11002. case OMPC_allocator:
  11003. case OMPC_collapse:
  11004. case OMPC_schedule:
  11005. case OMPC_private:
  11006. case OMPC_firstprivate:
  11007. case OMPC_lastprivate:
  11008. case OMPC_shared:
  11009. case OMPC_reduction:
  11010. case OMPC_task_reduction:
  11011. case OMPC_in_reduction:
  11012. case OMPC_linear:
  11013. case OMPC_aligned:
  11014. case OMPC_copyin:
  11015. case OMPC_copyprivate:
  11016. case OMPC_default:
  11017. case OMPC_proc_bind:
  11018. case OMPC_threadprivate:
  11019. case OMPC_allocate:
  11020. case OMPC_flush:
  11021. case OMPC_depend:
  11022. case OMPC_device:
  11023. case OMPC_map:
  11024. case OMPC_num_teams:
  11025. case OMPC_thread_limit:
  11026. case OMPC_priority:
  11027. case OMPC_grainsize:
  11028. case OMPC_num_tasks:
  11029. case OMPC_hint:
  11030. case OMPC_dist_schedule:
  11031. case OMPC_defaultmap:
  11032. case OMPC_unknown:
  11033. case OMPC_uniform:
  11034. case OMPC_to:
  11035. case OMPC_from:
  11036. case OMPC_use_device_ptr:
  11037. case OMPC_is_device_ptr:
  11038. case OMPC_atomic_default_mem_order:
  11039. case OMPC_device_type:
  11040. case OMPC_match:
  11041. llvm_unreachable("Clause is not allowed.");
  11042. }
  11043. return Res;
  11044. }
  11045. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  11046. SourceLocation EndLoc) {
  11047. DSAStack->setNowaitRegion();
  11048. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  11049. }
  11050. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  11051. SourceLocation EndLoc) {
  11052. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  11053. }
  11054. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  11055. SourceLocation EndLoc) {
  11056. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  11057. }
  11058. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  11059. SourceLocation EndLoc) {
  11060. return new (Context) OMPReadClause(StartLoc, EndLoc);
  11061. }
  11062. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  11063. SourceLocation EndLoc) {
  11064. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  11065. }
  11066. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  11067. SourceLocation EndLoc) {
  11068. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  11069. }
  11070. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  11071. SourceLocation EndLoc) {
  11072. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  11073. }
  11074. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  11075. SourceLocation EndLoc) {
  11076. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  11077. }
  11078. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  11079. SourceLocation EndLoc) {
  11080. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  11081. }
  11082. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  11083. SourceLocation EndLoc) {
  11084. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  11085. }
  11086. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  11087. SourceLocation EndLoc) {
  11088. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  11089. }
  11090. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  11091. SourceLocation EndLoc) {
  11092. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  11093. }
  11094. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  11095. SourceLocation EndLoc) {
  11096. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  11097. }
  11098. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  11099. SourceLocation EndLoc) {
  11100. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  11101. }
  11102. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  11103. SourceLocation EndLoc) {
  11104. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  11105. }
  11106. OMPClause *Sema::ActOnOpenMPVarListClause(
  11107. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  11108. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  11109. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  11110. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  11111. OpenMPLinearClauseKind LinKind,
  11112. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  11113. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  11114. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  11115. SourceLocation StartLoc = Locs.StartLoc;
  11116. SourceLocation LParenLoc = Locs.LParenLoc;
  11117. SourceLocation EndLoc = Locs.EndLoc;
  11118. OMPClause *Res = nullptr;
  11119. switch (Kind) {
  11120. case OMPC_private:
  11121. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  11122. break;
  11123. case OMPC_firstprivate:
  11124. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  11125. break;
  11126. case OMPC_lastprivate:
  11127. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  11128. break;
  11129. case OMPC_shared:
  11130. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  11131. break;
  11132. case OMPC_reduction:
  11133. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  11134. EndLoc, ReductionOrMapperIdScopeSpec,
  11135. ReductionOrMapperId);
  11136. break;
  11137. case OMPC_task_reduction:
  11138. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  11139. EndLoc, ReductionOrMapperIdScopeSpec,
  11140. ReductionOrMapperId);
  11141. break;
  11142. case OMPC_in_reduction:
  11143. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  11144. EndLoc, ReductionOrMapperIdScopeSpec,
  11145. ReductionOrMapperId);
  11146. break;
  11147. case OMPC_linear:
  11148. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  11149. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  11150. break;
  11151. case OMPC_aligned:
  11152. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  11153. ColonLoc, EndLoc);
  11154. break;
  11155. case OMPC_copyin:
  11156. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  11157. break;
  11158. case OMPC_copyprivate:
  11159. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  11160. break;
  11161. case OMPC_flush:
  11162. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  11163. break;
  11164. case OMPC_depend:
  11165. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  11166. StartLoc, LParenLoc, EndLoc);
  11167. break;
  11168. case OMPC_map:
  11169. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  11170. ReductionOrMapperIdScopeSpec,
  11171. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  11172. DepLinMapLoc, ColonLoc, VarList, Locs);
  11173. break;
  11174. case OMPC_to:
  11175. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  11176. ReductionOrMapperId, Locs);
  11177. break;
  11178. case OMPC_from:
  11179. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  11180. ReductionOrMapperId, Locs);
  11181. break;
  11182. case OMPC_use_device_ptr:
  11183. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  11184. break;
  11185. case OMPC_is_device_ptr:
  11186. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  11187. break;
  11188. case OMPC_allocate:
  11189. Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
  11190. ColonLoc, EndLoc);
  11191. break;
  11192. case OMPC_if:
  11193. case OMPC_final:
  11194. case OMPC_num_threads:
  11195. case OMPC_safelen:
  11196. case OMPC_simdlen:
  11197. case OMPC_allocator:
  11198. case OMPC_collapse:
  11199. case OMPC_default:
  11200. case OMPC_proc_bind:
  11201. case OMPC_schedule:
  11202. case OMPC_ordered:
  11203. case OMPC_nowait:
  11204. case OMPC_untied:
  11205. case OMPC_mergeable:
  11206. case OMPC_threadprivate:
  11207. case OMPC_read:
  11208. case OMPC_write:
  11209. case OMPC_update:
  11210. case OMPC_capture:
  11211. case OMPC_seq_cst:
  11212. case OMPC_device:
  11213. case OMPC_threads:
  11214. case OMPC_simd:
  11215. case OMPC_num_teams:
  11216. case OMPC_thread_limit:
  11217. case OMPC_priority:
  11218. case OMPC_grainsize:
  11219. case OMPC_nogroup:
  11220. case OMPC_num_tasks:
  11221. case OMPC_hint:
  11222. case OMPC_dist_schedule:
  11223. case OMPC_defaultmap:
  11224. case OMPC_unknown:
  11225. case OMPC_uniform:
  11226. case OMPC_unified_address:
  11227. case OMPC_unified_shared_memory:
  11228. case OMPC_reverse_offload:
  11229. case OMPC_dynamic_allocators:
  11230. case OMPC_atomic_default_mem_order:
  11231. case OMPC_device_type:
  11232. case OMPC_match:
  11233. llvm_unreachable("Clause is not allowed.");
  11234. }
  11235. return Res;
  11236. }
  11237. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  11238. ExprObjectKind OK, SourceLocation Loc) {
  11239. ExprResult Res = BuildDeclRefExpr(
  11240. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  11241. if (!Res.isUsable())
  11242. return ExprError();
  11243. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  11244. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  11245. if (!Res.isUsable())
  11246. return ExprError();
  11247. }
  11248. if (VK != VK_LValue && Res.get()->isGLValue()) {
  11249. Res = DefaultLvalueConversion(Res.get());
  11250. if (!Res.isUsable())
  11251. return ExprError();
  11252. }
  11253. return Res;
  11254. }
  11255. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  11256. SourceLocation StartLoc,
  11257. SourceLocation LParenLoc,
  11258. SourceLocation EndLoc) {
  11259. SmallVector<Expr *, 8> Vars;
  11260. SmallVector<Expr *, 8> PrivateCopies;
  11261. for (Expr *RefExpr : VarList) {
  11262. assert(RefExpr && "NULL expr in OpenMP private clause.");
  11263. SourceLocation ELoc;
  11264. SourceRange ERange;
  11265. Expr *SimpleRefExpr = RefExpr;
  11266. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11267. if (Res.second) {
  11268. // It will be analyzed later.
  11269. Vars.push_back(RefExpr);
  11270. PrivateCopies.push_back(nullptr);
  11271. }
  11272. ValueDecl *D = Res.first;
  11273. if (!D)
  11274. continue;
  11275. QualType Type = D->getType();
  11276. auto *VD = dyn_cast<VarDecl>(D);
  11277. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  11278. // A variable that appears in a private clause must not have an incomplete
  11279. // type or a reference type.
  11280. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  11281. continue;
  11282. Type = Type.getNonReferenceType();
  11283. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11284. // A variable that is privatized must not have a const-qualified type
  11285. // unless it is of class type with a mutable member. This restriction does
  11286. // not apply to the firstprivate clause.
  11287. //
  11288. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  11289. // A variable that appears in a private clause must not have a
  11290. // const-qualified type unless it is of class type with a mutable member.
  11291. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  11292. continue;
  11293. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11294. // in a Construct]
  11295. // Variables with the predetermined data-sharing attributes may not be
  11296. // listed in data-sharing attributes clauses, except for the cases
  11297. // listed below. For these exceptions only, listing a predetermined
  11298. // variable in a data-sharing attribute clause is allowed and overrides
  11299. // the variable's predetermined data-sharing attributes.
  11300. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11301. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  11302. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11303. << getOpenMPClauseName(OMPC_private);
  11304. reportOriginalDsa(*this, DSAStack, D, DVar);
  11305. continue;
  11306. }
  11307. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11308. // Variably modified types are not supported for tasks.
  11309. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  11310. isOpenMPTaskingDirective(CurrDir)) {
  11311. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11312. << getOpenMPClauseName(OMPC_private) << Type
  11313. << getOpenMPDirectiveName(CurrDir);
  11314. bool IsDecl =
  11315. !VD ||
  11316. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11317. Diag(D->getLocation(),
  11318. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11319. << D;
  11320. continue;
  11321. }
  11322. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11323. // A list item cannot appear in both a map clause and a data-sharing
  11324. // attribute clause on the same construct
  11325. //
  11326. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11327. // A list item cannot appear in both a map clause and a data-sharing
  11328. // attribute clause on the same construct unless the construct is a
  11329. // combined construct.
  11330. if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
  11331. CurrDir == OMPD_target) {
  11332. OpenMPClauseKind ConflictKind;
  11333. if (DSAStack->checkMappableExprComponentListsForDecl(
  11334. VD, /*CurrentRegionOnly=*/true,
  11335. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11336. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  11337. ConflictKind = WhereFoundClauseKind;
  11338. return true;
  11339. })) {
  11340. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11341. << getOpenMPClauseName(OMPC_private)
  11342. << getOpenMPClauseName(ConflictKind)
  11343. << getOpenMPDirectiveName(CurrDir);
  11344. reportOriginalDsa(*this, DSAStack, D, DVar);
  11345. continue;
  11346. }
  11347. }
  11348. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  11349. // A variable of class type (or array thereof) that appears in a private
  11350. // clause requires an accessible, unambiguous default constructor for the
  11351. // class type.
  11352. // Generate helper private variable and initialize it with the default
  11353. // value. The address of the original variable is replaced by the address of
  11354. // the new private variable in CodeGen. This new variable is not added to
  11355. // IdResolver, so the code in the OpenMP region uses original variable for
  11356. // proper diagnostics.
  11357. Type = Type.getUnqualifiedType();
  11358. VarDecl *VDPrivate =
  11359. buildVarDecl(*this, ELoc, Type, D->getName(),
  11360. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11361. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11362. ActOnUninitializedDecl(VDPrivate);
  11363. if (VDPrivate->isInvalidDecl())
  11364. continue;
  11365. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11366. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11367. DeclRefExpr *Ref = nullptr;
  11368. if (!VD && !CurContext->isDependentContext())
  11369. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11370. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  11371. Vars.push_back((VD || CurContext->isDependentContext())
  11372. ? RefExpr->IgnoreParens()
  11373. : Ref);
  11374. PrivateCopies.push_back(VDPrivateRefExpr);
  11375. }
  11376. if (Vars.empty())
  11377. return nullptr;
  11378. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11379. PrivateCopies);
  11380. }
  11381. namespace {
  11382. class DiagsUninitializedSeveretyRAII {
  11383. private:
  11384. DiagnosticsEngine &Diags;
  11385. SourceLocation SavedLoc;
  11386. bool IsIgnored = false;
  11387. public:
  11388. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  11389. bool IsIgnored)
  11390. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  11391. if (!IsIgnored) {
  11392. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  11393. /*Map*/ diag::Severity::Ignored, Loc);
  11394. }
  11395. }
  11396. ~DiagsUninitializedSeveretyRAII() {
  11397. if (!IsIgnored)
  11398. Diags.popMappings(SavedLoc);
  11399. }
  11400. };
  11401. }
  11402. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  11403. SourceLocation StartLoc,
  11404. SourceLocation LParenLoc,
  11405. SourceLocation EndLoc) {
  11406. SmallVector<Expr *, 8> Vars;
  11407. SmallVector<Expr *, 8> PrivateCopies;
  11408. SmallVector<Expr *, 8> Inits;
  11409. SmallVector<Decl *, 4> ExprCaptures;
  11410. bool IsImplicitClause =
  11411. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  11412. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  11413. for (Expr *RefExpr : VarList) {
  11414. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  11415. SourceLocation ELoc;
  11416. SourceRange ERange;
  11417. Expr *SimpleRefExpr = RefExpr;
  11418. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11419. if (Res.second) {
  11420. // It will be analyzed later.
  11421. Vars.push_back(RefExpr);
  11422. PrivateCopies.push_back(nullptr);
  11423. Inits.push_back(nullptr);
  11424. }
  11425. ValueDecl *D = Res.first;
  11426. if (!D)
  11427. continue;
  11428. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  11429. QualType Type = D->getType();
  11430. auto *VD = dyn_cast<VarDecl>(D);
  11431. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  11432. // A variable that appears in a private clause must not have an incomplete
  11433. // type or a reference type.
  11434. if (RequireCompleteType(ELoc, Type,
  11435. diag::err_omp_firstprivate_incomplete_type))
  11436. continue;
  11437. Type = Type.getNonReferenceType();
  11438. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  11439. // A variable of class type (or array thereof) that appears in a private
  11440. // clause requires an accessible, unambiguous copy constructor for the
  11441. // class type.
  11442. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11443. // If an implicit firstprivate variable found it was checked already.
  11444. DSAStackTy::DSAVarData TopDVar;
  11445. if (!IsImplicitClause) {
  11446. DSAStackTy::DSAVarData DVar =
  11447. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11448. TopDVar = DVar;
  11449. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11450. bool IsConstant = ElemType.isConstant(Context);
  11451. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  11452. // A list item that specifies a given variable may not appear in more
  11453. // than one clause on the same directive, except that a variable may be
  11454. // specified in both firstprivate and lastprivate clauses.
  11455. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11456. // A list item may appear in a firstprivate or lastprivate clause but not
  11457. // both.
  11458. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  11459. (isOpenMPDistributeDirective(CurrDir) ||
  11460. DVar.CKind != OMPC_lastprivate) &&
  11461. DVar.RefExpr) {
  11462. Diag(ELoc, diag::err_omp_wrong_dsa)
  11463. << getOpenMPClauseName(DVar.CKind)
  11464. << getOpenMPClauseName(OMPC_firstprivate);
  11465. reportOriginalDsa(*this, DSAStack, D, DVar);
  11466. continue;
  11467. }
  11468. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11469. // in a Construct]
  11470. // Variables with the predetermined data-sharing attributes may not be
  11471. // listed in data-sharing attributes clauses, except for the cases
  11472. // listed below. For these exceptions only, listing a predetermined
  11473. // variable in a data-sharing attribute clause is allowed and overrides
  11474. // the variable's predetermined data-sharing attributes.
  11475. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11476. // in a Construct, C/C++, p.2]
  11477. // Variables with const-qualified type having no mutable member may be
  11478. // listed in a firstprivate clause, even if they are static data members.
  11479. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  11480. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  11481. Diag(ELoc, diag::err_omp_wrong_dsa)
  11482. << getOpenMPClauseName(DVar.CKind)
  11483. << getOpenMPClauseName(OMPC_firstprivate);
  11484. reportOriginalDsa(*this, DSAStack, D, DVar);
  11485. continue;
  11486. }
  11487. // OpenMP [2.9.3.4, Restrictions, p.2]
  11488. // A list item that is private within a parallel region must not appear
  11489. // in a firstprivate clause on a worksharing construct if any of the
  11490. // worksharing regions arising from the worksharing construct ever bind
  11491. // to any of the parallel regions arising from the parallel construct.
  11492. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11493. // A list item that is private within a teams region must not appear in a
  11494. // firstprivate clause on a distribute construct if any of the distribute
  11495. // regions arising from the distribute construct ever bind to any of the
  11496. // teams regions arising from the teams construct.
  11497. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11498. // A list item that appears in a reduction clause of a teams construct
  11499. // must not appear in a firstprivate clause on a distribute construct if
  11500. // any of the distribute regions arising from the distribute construct
  11501. // ever bind to any of the teams regions arising from the teams construct.
  11502. if ((isOpenMPWorksharingDirective(CurrDir) ||
  11503. isOpenMPDistributeDirective(CurrDir)) &&
  11504. !isOpenMPParallelDirective(CurrDir) &&
  11505. !isOpenMPTeamsDirective(CurrDir)) {
  11506. DVar = DSAStack->getImplicitDSA(D, true);
  11507. if (DVar.CKind != OMPC_shared &&
  11508. (isOpenMPParallelDirective(DVar.DKind) ||
  11509. isOpenMPTeamsDirective(DVar.DKind) ||
  11510. DVar.DKind == OMPD_unknown)) {
  11511. Diag(ELoc, diag::err_omp_required_access)
  11512. << getOpenMPClauseName(OMPC_firstprivate)
  11513. << getOpenMPClauseName(OMPC_shared);
  11514. reportOriginalDsa(*this, DSAStack, D, DVar);
  11515. continue;
  11516. }
  11517. }
  11518. // OpenMP [2.9.3.4, Restrictions, p.3]
  11519. // A list item that appears in a reduction clause of a parallel construct
  11520. // must not appear in a firstprivate clause on a worksharing or task
  11521. // construct if any of the worksharing or task regions arising from the
  11522. // worksharing or task construct ever bind to any of the parallel regions
  11523. // arising from the parallel construct.
  11524. // OpenMP [2.9.3.4, Restrictions, p.4]
  11525. // A list item that appears in a reduction clause in worksharing
  11526. // construct must not appear in a firstprivate clause in a task construct
  11527. // encountered during execution of any of the worksharing regions arising
  11528. // from the worksharing construct.
  11529. if (isOpenMPTaskingDirective(CurrDir)) {
  11530. DVar = DSAStack->hasInnermostDSA(
  11531. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  11532. [](OpenMPDirectiveKind K) {
  11533. return isOpenMPParallelDirective(K) ||
  11534. isOpenMPWorksharingDirective(K) ||
  11535. isOpenMPTeamsDirective(K);
  11536. },
  11537. /*FromParent=*/true);
  11538. if (DVar.CKind == OMPC_reduction &&
  11539. (isOpenMPParallelDirective(DVar.DKind) ||
  11540. isOpenMPWorksharingDirective(DVar.DKind) ||
  11541. isOpenMPTeamsDirective(DVar.DKind))) {
  11542. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  11543. << getOpenMPDirectiveName(DVar.DKind);
  11544. reportOriginalDsa(*this, DSAStack, D, DVar);
  11545. continue;
  11546. }
  11547. }
  11548. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11549. // A list item cannot appear in both a map clause and a data-sharing
  11550. // attribute clause on the same construct
  11551. //
  11552. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11553. // A list item cannot appear in both a map clause and a data-sharing
  11554. // attribute clause on the same construct unless the construct is a
  11555. // combined construct.
  11556. if ((LangOpts.OpenMP <= 45 &&
  11557. isOpenMPTargetExecutionDirective(CurrDir)) ||
  11558. CurrDir == OMPD_target) {
  11559. OpenMPClauseKind ConflictKind;
  11560. if (DSAStack->checkMappableExprComponentListsForDecl(
  11561. VD, /*CurrentRegionOnly=*/true,
  11562. [&ConflictKind](
  11563. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11564. OpenMPClauseKind WhereFoundClauseKind) {
  11565. ConflictKind = WhereFoundClauseKind;
  11566. return true;
  11567. })) {
  11568. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11569. << getOpenMPClauseName(OMPC_firstprivate)
  11570. << getOpenMPClauseName(ConflictKind)
  11571. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11572. reportOriginalDsa(*this, DSAStack, D, DVar);
  11573. continue;
  11574. }
  11575. }
  11576. }
  11577. // Variably modified types are not supported for tasks.
  11578. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  11579. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  11580. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11581. << getOpenMPClauseName(OMPC_firstprivate) << Type
  11582. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11583. bool IsDecl =
  11584. !VD ||
  11585. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11586. Diag(D->getLocation(),
  11587. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11588. << D;
  11589. continue;
  11590. }
  11591. Type = Type.getUnqualifiedType();
  11592. VarDecl *VDPrivate =
  11593. buildVarDecl(*this, ELoc, Type, D->getName(),
  11594. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11595. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11596. // Generate helper private variable and initialize it with the value of the
  11597. // original variable. The address of the original variable is replaced by
  11598. // the address of the new private variable in the CodeGen. This new variable
  11599. // is not added to IdResolver, so the code in the OpenMP region uses
  11600. // original variable for proper diagnostics and variable capturing.
  11601. Expr *VDInitRefExpr = nullptr;
  11602. // For arrays generate initializer for single element and replace it by the
  11603. // original array element in CodeGen.
  11604. if (Type->isArrayType()) {
  11605. VarDecl *VDInit =
  11606. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  11607. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  11608. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  11609. ElemType = ElemType.getUnqualifiedType();
  11610. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  11611. ".firstprivate.temp");
  11612. InitializedEntity Entity =
  11613. InitializedEntity::InitializeVariable(VDInitTemp);
  11614. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  11615. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  11616. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  11617. if (Result.isInvalid())
  11618. VDPrivate->setInvalidDecl();
  11619. else
  11620. VDPrivate->setInit(Result.getAs<Expr>());
  11621. // Remove temp variable declaration.
  11622. Context.Deallocate(VDInitTemp);
  11623. } else {
  11624. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  11625. ".firstprivate.temp");
  11626. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11627. RefExpr->getExprLoc());
  11628. AddInitializerToDecl(VDPrivate,
  11629. DefaultLvalueConversion(VDInitRefExpr).get(),
  11630. /*DirectInit=*/false);
  11631. }
  11632. if (VDPrivate->isInvalidDecl()) {
  11633. if (IsImplicitClause) {
  11634. Diag(RefExpr->getExprLoc(),
  11635. diag::note_omp_task_predetermined_firstprivate_here);
  11636. }
  11637. continue;
  11638. }
  11639. CurContext->addDecl(VDPrivate);
  11640. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11641. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  11642. RefExpr->getExprLoc());
  11643. DeclRefExpr *Ref = nullptr;
  11644. if (!VD && !CurContext->isDependentContext()) {
  11645. if (TopDVar.CKind == OMPC_lastprivate) {
  11646. Ref = TopDVar.PrivateCopy;
  11647. } else {
  11648. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11649. if (!isOpenMPCapturedDecl(D))
  11650. ExprCaptures.push_back(Ref->getDecl());
  11651. }
  11652. }
  11653. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11654. Vars.push_back((VD || CurContext->isDependentContext())
  11655. ? RefExpr->IgnoreParens()
  11656. : Ref);
  11657. PrivateCopies.push_back(VDPrivateRefExpr);
  11658. Inits.push_back(VDInitRefExpr);
  11659. }
  11660. if (Vars.empty())
  11661. return nullptr;
  11662. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11663. Vars, PrivateCopies, Inits,
  11664. buildPreInits(Context, ExprCaptures));
  11665. }
  11666. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  11667. SourceLocation StartLoc,
  11668. SourceLocation LParenLoc,
  11669. SourceLocation EndLoc) {
  11670. SmallVector<Expr *, 8> Vars;
  11671. SmallVector<Expr *, 8> SrcExprs;
  11672. SmallVector<Expr *, 8> DstExprs;
  11673. SmallVector<Expr *, 8> AssignmentOps;
  11674. SmallVector<Decl *, 4> ExprCaptures;
  11675. SmallVector<Expr *, 4> ExprPostUpdates;
  11676. for (Expr *RefExpr : VarList) {
  11677. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11678. SourceLocation ELoc;
  11679. SourceRange ERange;
  11680. Expr *SimpleRefExpr = RefExpr;
  11681. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11682. if (Res.second) {
  11683. // It will be analyzed later.
  11684. Vars.push_back(RefExpr);
  11685. SrcExprs.push_back(nullptr);
  11686. DstExprs.push_back(nullptr);
  11687. AssignmentOps.push_back(nullptr);
  11688. }
  11689. ValueDecl *D = Res.first;
  11690. if (!D)
  11691. continue;
  11692. QualType Type = D->getType();
  11693. auto *VD = dyn_cast<VarDecl>(D);
  11694. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  11695. // A variable that appears in a lastprivate clause must not have an
  11696. // incomplete type or a reference type.
  11697. if (RequireCompleteType(ELoc, Type,
  11698. diag::err_omp_lastprivate_incomplete_type))
  11699. continue;
  11700. Type = Type.getNonReferenceType();
  11701. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11702. // A variable that is privatized must not have a const-qualified type
  11703. // unless it is of class type with a mutable member. This restriction does
  11704. // not apply to the firstprivate clause.
  11705. //
  11706. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  11707. // A variable that appears in a lastprivate clause must not have a
  11708. // const-qualified type unless it is of class type with a mutable member.
  11709. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  11710. continue;
  11711. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11712. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  11713. // in a Construct]
  11714. // Variables with the predetermined data-sharing attributes may not be
  11715. // listed in data-sharing attributes clauses, except for the cases
  11716. // listed below.
  11717. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11718. // A list item may appear in a firstprivate or lastprivate clause but not
  11719. // both.
  11720. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11721. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  11722. (isOpenMPDistributeDirective(CurrDir) ||
  11723. DVar.CKind != OMPC_firstprivate) &&
  11724. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  11725. Diag(ELoc, diag::err_omp_wrong_dsa)
  11726. << getOpenMPClauseName(DVar.CKind)
  11727. << getOpenMPClauseName(OMPC_lastprivate);
  11728. reportOriginalDsa(*this, DSAStack, D, DVar);
  11729. continue;
  11730. }
  11731. // OpenMP [2.14.3.5, Restrictions, p.2]
  11732. // A list item that is private within a parallel region, or that appears in
  11733. // the reduction clause of a parallel construct, must not appear in a
  11734. // lastprivate clause on a worksharing construct if any of the corresponding
  11735. // worksharing regions ever binds to any of the corresponding parallel
  11736. // regions.
  11737. DSAStackTy::DSAVarData TopDVar = DVar;
  11738. if (isOpenMPWorksharingDirective(CurrDir) &&
  11739. !isOpenMPParallelDirective(CurrDir) &&
  11740. !isOpenMPTeamsDirective(CurrDir)) {
  11741. DVar = DSAStack->getImplicitDSA(D, true);
  11742. if (DVar.CKind != OMPC_shared) {
  11743. Diag(ELoc, diag::err_omp_required_access)
  11744. << getOpenMPClauseName(OMPC_lastprivate)
  11745. << getOpenMPClauseName(OMPC_shared);
  11746. reportOriginalDsa(*this, DSAStack, D, DVar);
  11747. continue;
  11748. }
  11749. }
  11750. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  11751. // A variable of class type (or array thereof) that appears in a
  11752. // lastprivate clause requires an accessible, unambiguous default
  11753. // constructor for the class type, unless the list item is also specified
  11754. // in a firstprivate clause.
  11755. // A variable of class type (or array thereof) that appears in a
  11756. // lastprivate clause requires an accessible, unambiguous copy assignment
  11757. // operator for the class type.
  11758. Type = Context.getBaseElementType(Type).getNonReferenceType();
  11759. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  11760. Type.getUnqualifiedType(), ".lastprivate.src",
  11761. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11762. DeclRefExpr *PseudoSrcExpr =
  11763. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  11764. VarDecl *DstVD =
  11765. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  11766. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11767. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11768. // For arrays generate assignment operation for single element and replace
  11769. // it by the original array element in CodeGen.
  11770. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  11771. PseudoDstExpr, PseudoSrcExpr);
  11772. if (AssignmentOp.isInvalid())
  11773. continue;
  11774. AssignmentOp =
  11775. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  11776. if (AssignmentOp.isInvalid())
  11777. continue;
  11778. DeclRefExpr *Ref = nullptr;
  11779. if (!VD && !CurContext->isDependentContext()) {
  11780. if (TopDVar.CKind == OMPC_firstprivate) {
  11781. Ref = TopDVar.PrivateCopy;
  11782. } else {
  11783. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11784. if (!isOpenMPCapturedDecl(D))
  11785. ExprCaptures.push_back(Ref->getDecl());
  11786. }
  11787. if (TopDVar.CKind == OMPC_firstprivate ||
  11788. (!isOpenMPCapturedDecl(D) &&
  11789. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  11790. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11791. if (!RefRes.isUsable())
  11792. continue;
  11793. ExprResult PostUpdateRes =
  11794. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  11795. RefRes.get());
  11796. if (!PostUpdateRes.isUsable())
  11797. continue;
  11798. ExprPostUpdates.push_back(
  11799. IgnoredValueConversions(PostUpdateRes.get()).get());
  11800. }
  11801. }
  11802. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  11803. Vars.push_back((VD || CurContext->isDependentContext())
  11804. ? RefExpr->IgnoreParens()
  11805. : Ref);
  11806. SrcExprs.push_back(PseudoSrcExpr);
  11807. DstExprs.push_back(PseudoDstExpr);
  11808. AssignmentOps.push_back(AssignmentOp.get());
  11809. }
  11810. if (Vars.empty())
  11811. return nullptr;
  11812. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11813. Vars, SrcExprs, DstExprs, AssignmentOps,
  11814. buildPreInits(Context, ExprCaptures),
  11815. buildPostUpdate(*this, ExprPostUpdates));
  11816. }
  11817. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  11818. SourceLocation StartLoc,
  11819. SourceLocation LParenLoc,
  11820. SourceLocation EndLoc) {
  11821. SmallVector<Expr *, 8> Vars;
  11822. for (Expr *RefExpr : VarList) {
  11823. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11824. SourceLocation ELoc;
  11825. SourceRange ERange;
  11826. Expr *SimpleRefExpr = RefExpr;
  11827. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11828. if (Res.second) {
  11829. // It will be analyzed later.
  11830. Vars.push_back(RefExpr);
  11831. }
  11832. ValueDecl *D = Res.first;
  11833. if (!D)
  11834. continue;
  11835. auto *VD = dyn_cast<VarDecl>(D);
  11836. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11837. // in a Construct]
  11838. // Variables with the predetermined data-sharing attributes may not be
  11839. // listed in data-sharing attributes clauses, except for the cases
  11840. // listed below. For these exceptions only, listing a predetermined
  11841. // variable in a data-sharing attribute clause is allowed and overrides
  11842. // the variable's predetermined data-sharing attributes.
  11843. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11844. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  11845. DVar.RefExpr) {
  11846. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11847. << getOpenMPClauseName(OMPC_shared);
  11848. reportOriginalDsa(*this, DSAStack, D, DVar);
  11849. continue;
  11850. }
  11851. DeclRefExpr *Ref = nullptr;
  11852. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  11853. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11854. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  11855. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  11856. ? RefExpr->IgnoreParens()
  11857. : Ref);
  11858. }
  11859. if (Vars.empty())
  11860. return nullptr;
  11861. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  11862. }
  11863. namespace {
  11864. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  11865. DSAStackTy *Stack;
  11866. public:
  11867. bool VisitDeclRefExpr(DeclRefExpr *E) {
  11868. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  11869. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  11870. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  11871. return false;
  11872. if (DVar.CKind != OMPC_unknown)
  11873. return true;
  11874. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  11875. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  11876. /*FromParent=*/true);
  11877. return DVarPrivate.CKind != OMPC_unknown;
  11878. }
  11879. return false;
  11880. }
  11881. bool VisitStmt(Stmt *S) {
  11882. for (Stmt *Child : S->children()) {
  11883. if (Child && Visit(Child))
  11884. return true;
  11885. }
  11886. return false;
  11887. }
  11888. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  11889. };
  11890. } // namespace
  11891. namespace {
  11892. // Transform MemberExpression for specified FieldDecl of current class to
  11893. // DeclRefExpr to specified OMPCapturedExprDecl.
  11894. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  11895. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  11896. ValueDecl *Field = nullptr;
  11897. DeclRefExpr *CapturedExpr = nullptr;
  11898. public:
  11899. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  11900. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  11901. ExprResult TransformMemberExpr(MemberExpr *E) {
  11902. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  11903. E->getMemberDecl() == Field) {
  11904. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  11905. return CapturedExpr;
  11906. }
  11907. return BaseTransform::TransformMemberExpr(E);
  11908. }
  11909. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  11910. };
  11911. } // namespace
  11912. template <typename T, typename U>
  11913. static T filterLookupForUDReductionAndMapper(
  11914. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  11915. for (U &Set : Lookups) {
  11916. for (auto *D : Set) {
  11917. if (T Res = Gen(cast<ValueDecl>(D)))
  11918. return Res;
  11919. }
  11920. }
  11921. return T();
  11922. }
  11923. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  11924. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  11925. for (auto RD : D->redecls()) {
  11926. // Don't bother with extra checks if we already know this one isn't visible.
  11927. if (RD == D)
  11928. continue;
  11929. auto ND = cast<NamedDecl>(RD);
  11930. if (LookupResult::isVisible(SemaRef, ND))
  11931. return ND;
  11932. }
  11933. return nullptr;
  11934. }
  11935. static void
  11936. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  11937. SourceLocation Loc, QualType Ty,
  11938. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  11939. // Find all of the associated namespaces and classes based on the
  11940. // arguments we have.
  11941. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  11942. Sema::AssociatedClassSet AssociatedClasses;
  11943. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  11944. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  11945. AssociatedClasses);
  11946. // C++ [basic.lookup.argdep]p3:
  11947. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  11948. // and let Y be the lookup set produced by argument dependent
  11949. // lookup (defined as follows). If X contains [...] then Y is
  11950. // empty. Otherwise Y is the set of declarations found in the
  11951. // namespaces associated with the argument types as described
  11952. // below. The set of declarations found by the lookup of the name
  11953. // is the union of X and Y.
  11954. //
  11955. // Here, we compute Y and add its members to the overloaded
  11956. // candidate set.
  11957. for (auto *NS : AssociatedNamespaces) {
  11958. // When considering an associated namespace, the lookup is the
  11959. // same as the lookup performed when the associated namespace is
  11960. // used as a qualifier (3.4.3.2) except that:
  11961. //
  11962. // -- Any using-directives in the associated namespace are
  11963. // ignored.
  11964. //
  11965. // -- Any namespace-scope friend functions declared in
  11966. // associated classes are visible within their respective
  11967. // namespaces even if they are not visible during an ordinary
  11968. // lookup (11.4).
  11969. DeclContext::lookup_result R = NS->lookup(Id.getName());
  11970. for (auto *D : R) {
  11971. auto *Underlying = D;
  11972. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11973. Underlying = USD->getTargetDecl();
  11974. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  11975. !isa<OMPDeclareMapperDecl>(Underlying))
  11976. continue;
  11977. if (!SemaRef.isVisible(D)) {
  11978. D = findAcceptableDecl(SemaRef, D);
  11979. if (!D)
  11980. continue;
  11981. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11982. Underlying = USD->getTargetDecl();
  11983. }
  11984. Lookups.emplace_back();
  11985. Lookups.back().addDecl(Underlying);
  11986. }
  11987. }
  11988. }
  11989. static ExprResult
  11990. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  11991. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  11992. const DeclarationNameInfo &ReductionId, QualType Ty,
  11993. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  11994. if (ReductionIdScopeSpec.isInvalid())
  11995. return ExprError();
  11996. SmallVector<UnresolvedSet<8>, 4> Lookups;
  11997. if (S) {
  11998. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11999. Lookup.suppressDiagnostics();
  12000. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  12001. NamedDecl *D = Lookup.getRepresentativeDecl();
  12002. do {
  12003. S = S->getParent();
  12004. } while (S && !S->isDeclScope(D));
  12005. if (S)
  12006. S = S->getParent();
  12007. Lookups.emplace_back();
  12008. Lookups.back().append(Lookup.begin(), Lookup.end());
  12009. Lookup.clear();
  12010. }
  12011. } else if (auto *ULE =
  12012. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  12013. Lookups.push_back(UnresolvedSet<8>());
  12014. Decl *PrevD = nullptr;
  12015. for (NamedDecl *D : ULE->decls()) {
  12016. if (D == PrevD)
  12017. Lookups.push_back(UnresolvedSet<8>());
  12018. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  12019. Lookups.back().addDecl(DRD);
  12020. PrevD = D;
  12021. }
  12022. }
  12023. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  12024. Ty->isInstantiationDependentType() ||
  12025. Ty->containsUnexpandedParameterPack() ||
  12026. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  12027. return !D->isInvalidDecl() &&
  12028. (D->getType()->isDependentType() ||
  12029. D->getType()->isInstantiationDependentType() ||
  12030. D->getType()->containsUnexpandedParameterPack());
  12031. })) {
  12032. UnresolvedSet<8> ResSet;
  12033. for (const UnresolvedSet<8> &Set : Lookups) {
  12034. if (Set.empty())
  12035. continue;
  12036. ResSet.append(Set.begin(), Set.end());
  12037. // The last item marks the end of all declarations at the specified scope.
  12038. ResSet.addDecl(Set[Set.size() - 1]);
  12039. }
  12040. return UnresolvedLookupExpr::Create(
  12041. SemaRef.Context, /*NamingClass=*/nullptr,
  12042. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  12043. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  12044. }
  12045. // Lookup inside the classes.
  12046. // C++ [over.match.oper]p3:
  12047. // For a unary operator @ with an operand of a type whose
  12048. // cv-unqualified version is T1, and for a binary operator @ with
  12049. // a left operand of a type whose cv-unqualified version is T1 and
  12050. // a right operand of a type whose cv-unqualified version is T2,
  12051. // three sets of candidate functions, designated member
  12052. // candidates, non-member candidates and built-in candidates, are
  12053. // constructed as follows:
  12054. // -- If T1 is a complete class type or a class currently being
  12055. // defined, the set of member candidates is the result of the
  12056. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  12057. // the set of member candidates is empty.
  12058. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  12059. Lookup.suppressDiagnostics();
  12060. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  12061. // Complete the type if it can be completed.
  12062. // If the type is neither complete nor being defined, bail out now.
  12063. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  12064. TyRec->getDecl()->getDefinition()) {
  12065. Lookup.clear();
  12066. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  12067. if (Lookup.empty()) {
  12068. Lookups.emplace_back();
  12069. Lookups.back().append(Lookup.begin(), Lookup.end());
  12070. }
  12071. }
  12072. }
  12073. // Perform ADL.
  12074. if (SemaRef.getLangOpts().CPlusPlus)
  12075. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  12076. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  12077. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  12078. if (!D->isInvalidDecl() &&
  12079. SemaRef.Context.hasSameType(D->getType(), Ty))
  12080. return D;
  12081. return nullptr;
  12082. }))
  12083. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  12084. VK_LValue, Loc);
  12085. if (SemaRef.getLangOpts().CPlusPlus) {
  12086. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  12087. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  12088. if (!D->isInvalidDecl() &&
  12089. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  12090. !Ty.isMoreQualifiedThan(D->getType()))
  12091. return D;
  12092. return nullptr;
  12093. })) {
  12094. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  12095. /*DetectVirtual=*/false);
  12096. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  12097. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  12098. VD->getType().getUnqualifiedType()))) {
  12099. if (SemaRef.CheckBaseClassAccess(
  12100. Loc, VD->getType(), Ty, Paths.front(),
  12101. /*DiagID=*/0) != Sema::AR_inaccessible) {
  12102. SemaRef.BuildBasePathArray(Paths, BasePath);
  12103. return SemaRef.BuildDeclRefExpr(
  12104. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  12105. }
  12106. }
  12107. }
  12108. }
  12109. }
  12110. if (ReductionIdScopeSpec.isSet()) {
  12111. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  12112. return ExprError();
  12113. }
  12114. return ExprEmpty();
  12115. }
  12116. namespace {
  12117. /// Data for the reduction-based clauses.
  12118. struct ReductionData {
  12119. /// List of original reduction items.
  12120. SmallVector<Expr *, 8> Vars;
  12121. /// List of private copies of the reduction items.
  12122. SmallVector<Expr *, 8> Privates;
  12123. /// LHS expressions for the reduction_op expressions.
  12124. SmallVector<Expr *, 8> LHSs;
  12125. /// RHS expressions for the reduction_op expressions.
  12126. SmallVector<Expr *, 8> RHSs;
  12127. /// Reduction operation expression.
  12128. SmallVector<Expr *, 8> ReductionOps;
  12129. /// Taskgroup descriptors for the corresponding reduction items in
  12130. /// in_reduction clauses.
  12131. SmallVector<Expr *, 8> TaskgroupDescriptors;
  12132. /// List of captures for clause.
  12133. SmallVector<Decl *, 4> ExprCaptures;
  12134. /// List of postupdate expressions.
  12135. SmallVector<Expr *, 4> ExprPostUpdates;
  12136. ReductionData() = delete;
  12137. /// Reserves required memory for the reduction data.
  12138. ReductionData(unsigned Size) {
  12139. Vars.reserve(Size);
  12140. Privates.reserve(Size);
  12141. LHSs.reserve(Size);
  12142. RHSs.reserve(Size);
  12143. ReductionOps.reserve(Size);
  12144. TaskgroupDescriptors.reserve(Size);
  12145. ExprCaptures.reserve(Size);
  12146. ExprPostUpdates.reserve(Size);
  12147. }
  12148. /// Stores reduction item and reduction operation only (required for dependent
  12149. /// reduction item).
  12150. void push(Expr *Item, Expr *ReductionOp) {
  12151. Vars.emplace_back(Item);
  12152. Privates.emplace_back(nullptr);
  12153. LHSs.emplace_back(nullptr);
  12154. RHSs.emplace_back(nullptr);
  12155. ReductionOps.emplace_back(ReductionOp);
  12156. TaskgroupDescriptors.emplace_back(nullptr);
  12157. }
  12158. /// Stores reduction data.
  12159. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  12160. Expr *TaskgroupDescriptor) {
  12161. Vars.emplace_back(Item);
  12162. Privates.emplace_back(Private);
  12163. LHSs.emplace_back(LHS);
  12164. RHSs.emplace_back(RHS);
  12165. ReductionOps.emplace_back(ReductionOp);
  12166. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  12167. }
  12168. };
  12169. } // namespace
  12170. static bool checkOMPArraySectionConstantForReduction(
  12171. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  12172. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  12173. const Expr *Length = OASE->getLength();
  12174. if (Length == nullptr) {
  12175. // For array sections of the form [1:] or [:], we would need to analyze
  12176. // the lower bound...
  12177. if (OASE->getColonLoc().isValid())
  12178. return false;
  12179. // This is an array subscript which has implicit length 1!
  12180. SingleElement = true;
  12181. ArraySizes.push_back(llvm::APSInt::get(1));
  12182. } else {
  12183. Expr::EvalResult Result;
  12184. if (!Length->EvaluateAsInt(Result, Context))
  12185. return false;
  12186. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  12187. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  12188. ArraySizes.push_back(ConstantLengthValue);
  12189. }
  12190. // Get the base of this array section and walk up from there.
  12191. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  12192. // We require length = 1 for all array sections except the right-most to
  12193. // guarantee that the memory region is contiguous and has no holes in it.
  12194. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  12195. Length = TempOASE->getLength();
  12196. if (Length == nullptr) {
  12197. // For array sections of the form [1:] or [:], we would need to analyze
  12198. // the lower bound...
  12199. if (OASE->getColonLoc().isValid())
  12200. return false;
  12201. // This is an array subscript which has implicit length 1!
  12202. ArraySizes.push_back(llvm::APSInt::get(1));
  12203. } else {
  12204. Expr::EvalResult Result;
  12205. if (!Length->EvaluateAsInt(Result, Context))
  12206. return false;
  12207. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  12208. if (ConstantLengthValue.getSExtValue() != 1)
  12209. return false;
  12210. ArraySizes.push_back(ConstantLengthValue);
  12211. }
  12212. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  12213. }
  12214. // If we have a single element, we don't need to add the implicit lengths.
  12215. if (!SingleElement) {
  12216. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  12217. // Has implicit length 1!
  12218. ArraySizes.push_back(llvm::APSInt::get(1));
  12219. Base = TempASE->getBase()->IgnoreParenImpCasts();
  12220. }
  12221. }
  12222. // This array section can be privatized as a single value or as a constant
  12223. // sized array.
  12224. return true;
  12225. }
  12226. static bool actOnOMPReductionKindClause(
  12227. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  12228. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12229. SourceLocation ColonLoc, SourceLocation EndLoc,
  12230. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12231. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  12232. DeclarationName DN = ReductionId.getName();
  12233. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  12234. BinaryOperatorKind BOK = BO_Comma;
  12235. ASTContext &Context = S.Context;
  12236. // OpenMP [2.14.3.6, reduction clause]
  12237. // C
  12238. // reduction-identifier is either an identifier or one of the following
  12239. // operators: +, -, *, &, |, ^, && and ||
  12240. // C++
  12241. // reduction-identifier is either an id-expression or one of the following
  12242. // operators: +, -, *, &, |, ^, && and ||
  12243. switch (OOK) {
  12244. case OO_Plus:
  12245. case OO_Minus:
  12246. BOK = BO_Add;
  12247. break;
  12248. case OO_Star:
  12249. BOK = BO_Mul;
  12250. break;
  12251. case OO_Amp:
  12252. BOK = BO_And;
  12253. break;
  12254. case OO_Pipe:
  12255. BOK = BO_Or;
  12256. break;
  12257. case OO_Caret:
  12258. BOK = BO_Xor;
  12259. break;
  12260. case OO_AmpAmp:
  12261. BOK = BO_LAnd;
  12262. break;
  12263. case OO_PipePipe:
  12264. BOK = BO_LOr;
  12265. break;
  12266. case OO_New:
  12267. case OO_Delete:
  12268. case OO_Array_New:
  12269. case OO_Array_Delete:
  12270. case OO_Slash:
  12271. case OO_Percent:
  12272. case OO_Tilde:
  12273. case OO_Exclaim:
  12274. case OO_Equal:
  12275. case OO_Less:
  12276. case OO_Greater:
  12277. case OO_LessEqual:
  12278. case OO_GreaterEqual:
  12279. case OO_PlusEqual:
  12280. case OO_MinusEqual:
  12281. case OO_StarEqual:
  12282. case OO_SlashEqual:
  12283. case OO_PercentEqual:
  12284. case OO_CaretEqual:
  12285. case OO_AmpEqual:
  12286. case OO_PipeEqual:
  12287. case OO_LessLess:
  12288. case OO_GreaterGreater:
  12289. case OO_LessLessEqual:
  12290. case OO_GreaterGreaterEqual:
  12291. case OO_EqualEqual:
  12292. case OO_ExclaimEqual:
  12293. case OO_Spaceship:
  12294. case OO_PlusPlus:
  12295. case OO_MinusMinus:
  12296. case OO_Comma:
  12297. case OO_ArrowStar:
  12298. case OO_Arrow:
  12299. case OO_Call:
  12300. case OO_Subscript:
  12301. case OO_Conditional:
  12302. case OO_Coawait:
  12303. case NUM_OVERLOADED_OPERATORS:
  12304. llvm_unreachable("Unexpected reduction identifier");
  12305. case OO_None:
  12306. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  12307. if (II->isStr("max"))
  12308. BOK = BO_GT;
  12309. else if (II->isStr("min"))
  12310. BOK = BO_LT;
  12311. }
  12312. break;
  12313. }
  12314. SourceRange ReductionIdRange;
  12315. if (ReductionIdScopeSpec.isValid())
  12316. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  12317. else
  12318. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  12319. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  12320. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  12321. bool FirstIter = true;
  12322. for (Expr *RefExpr : VarList) {
  12323. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  12324. // OpenMP [2.1, C/C++]
  12325. // A list item is a variable or array section, subject to the restrictions
  12326. // specified in Section 2.4 on page 42 and in each of the sections
  12327. // describing clauses and directives for which a list appears.
  12328. // OpenMP [2.14.3.3, Restrictions, p.1]
  12329. // A variable that is part of another variable (as an array or
  12330. // structure element) cannot appear in a private clause.
  12331. if (!FirstIter && IR != ER)
  12332. ++IR;
  12333. FirstIter = false;
  12334. SourceLocation ELoc;
  12335. SourceRange ERange;
  12336. Expr *SimpleRefExpr = RefExpr;
  12337. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  12338. /*AllowArraySection=*/true);
  12339. if (Res.second) {
  12340. // Try to find 'declare reduction' corresponding construct before using
  12341. // builtin/overloaded operators.
  12342. QualType Type = Context.DependentTy;
  12343. CXXCastPath BasePath;
  12344. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12345. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12346. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12347. Expr *ReductionOp = nullptr;
  12348. if (S.CurContext->isDependentContext() &&
  12349. (DeclareReductionRef.isUnset() ||
  12350. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  12351. ReductionOp = DeclareReductionRef.get();
  12352. // It will be analyzed later.
  12353. RD.push(RefExpr, ReductionOp);
  12354. }
  12355. ValueDecl *D = Res.first;
  12356. if (!D)
  12357. continue;
  12358. Expr *TaskgroupDescriptor = nullptr;
  12359. QualType Type;
  12360. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  12361. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  12362. if (ASE) {
  12363. Type = ASE->getType().getNonReferenceType();
  12364. } else if (OASE) {
  12365. QualType BaseType =
  12366. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  12367. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  12368. Type = ATy->getElementType();
  12369. else
  12370. Type = BaseType->getPointeeType();
  12371. Type = Type.getNonReferenceType();
  12372. } else {
  12373. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  12374. }
  12375. auto *VD = dyn_cast<VarDecl>(D);
  12376. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  12377. // A variable that appears in a private clause must not have an incomplete
  12378. // type or a reference type.
  12379. if (S.RequireCompleteType(ELoc, D->getType(),
  12380. diag::err_omp_reduction_incomplete_type))
  12381. continue;
  12382. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12383. // A list item that appears in a reduction clause must not be
  12384. // const-qualified.
  12385. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  12386. /*AcceptIfMutable*/ false, ASE || OASE))
  12387. continue;
  12388. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  12389. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  12390. // If a list-item is a reference type then it must bind to the same object
  12391. // for all threads of the team.
  12392. if (!ASE && !OASE) {
  12393. if (VD) {
  12394. VarDecl *VDDef = VD->getDefinition();
  12395. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  12396. DSARefChecker Check(Stack);
  12397. if (Check.Visit(VDDef->getInit())) {
  12398. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  12399. << getOpenMPClauseName(ClauseKind) << ERange;
  12400. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  12401. continue;
  12402. }
  12403. }
  12404. }
  12405. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  12406. // in a Construct]
  12407. // Variables with the predetermined data-sharing attributes may not be
  12408. // listed in data-sharing attributes clauses, except for the cases
  12409. // listed below. For these exceptions only, listing a predetermined
  12410. // variable in a data-sharing attribute clause is allowed and overrides
  12411. // the variable's predetermined data-sharing attributes.
  12412. // OpenMP [2.14.3.6, Restrictions, p.3]
  12413. // Any number of reduction clauses can be specified on the directive,
  12414. // but a list item can appear only once in the reduction clauses for that
  12415. // directive.
  12416. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  12417. if (DVar.CKind == OMPC_reduction) {
  12418. S.Diag(ELoc, diag::err_omp_once_referenced)
  12419. << getOpenMPClauseName(ClauseKind);
  12420. if (DVar.RefExpr)
  12421. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  12422. continue;
  12423. }
  12424. if (DVar.CKind != OMPC_unknown) {
  12425. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  12426. << getOpenMPClauseName(DVar.CKind)
  12427. << getOpenMPClauseName(OMPC_reduction);
  12428. reportOriginalDsa(S, Stack, D, DVar);
  12429. continue;
  12430. }
  12431. // OpenMP [2.14.3.6, Restrictions, p.1]
  12432. // A list item that appears in a reduction clause of a worksharing
  12433. // construct must be shared in the parallel regions to which any of the
  12434. // worksharing regions arising from the worksharing construct bind.
  12435. if (isOpenMPWorksharingDirective(CurrDir) &&
  12436. !isOpenMPParallelDirective(CurrDir) &&
  12437. !isOpenMPTeamsDirective(CurrDir)) {
  12438. DVar = Stack->getImplicitDSA(D, true);
  12439. if (DVar.CKind != OMPC_shared) {
  12440. S.Diag(ELoc, diag::err_omp_required_access)
  12441. << getOpenMPClauseName(OMPC_reduction)
  12442. << getOpenMPClauseName(OMPC_shared);
  12443. reportOriginalDsa(S, Stack, D, DVar);
  12444. continue;
  12445. }
  12446. }
  12447. }
  12448. // Try to find 'declare reduction' corresponding construct before using
  12449. // builtin/overloaded operators.
  12450. CXXCastPath BasePath;
  12451. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12452. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12453. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12454. if (DeclareReductionRef.isInvalid())
  12455. continue;
  12456. if (S.CurContext->isDependentContext() &&
  12457. (DeclareReductionRef.isUnset() ||
  12458. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  12459. RD.push(RefExpr, DeclareReductionRef.get());
  12460. continue;
  12461. }
  12462. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  12463. // Not allowed reduction identifier is found.
  12464. S.Diag(ReductionId.getBeginLoc(),
  12465. diag::err_omp_unknown_reduction_identifier)
  12466. << Type << ReductionIdRange;
  12467. continue;
  12468. }
  12469. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12470. // The type of a list item that appears in a reduction clause must be valid
  12471. // for the reduction-identifier. For a max or min reduction in C, the type
  12472. // of the list item must be an allowed arithmetic data type: char, int,
  12473. // float, double, or _Bool, possibly modified with long, short, signed, or
  12474. // unsigned. For a max or min reduction in C++, the type of the list item
  12475. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  12476. // double, or bool, possibly modified with long, short, signed, or unsigned.
  12477. if (DeclareReductionRef.isUnset()) {
  12478. if ((BOK == BO_GT || BOK == BO_LT) &&
  12479. !(Type->isScalarType() ||
  12480. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  12481. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  12482. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  12483. if (!ASE && !OASE) {
  12484. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12485. VarDecl::DeclarationOnly;
  12486. S.Diag(D->getLocation(),
  12487. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12488. << D;
  12489. }
  12490. continue;
  12491. }
  12492. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  12493. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  12494. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  12495. << getOpenMPClauseName(ClauseKind);
  12496. if (!ASE && !OASE) {
  12497. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12498. VarDecl::DeclarationOnly;
  12499. S.Diag(D->getLocation(),
  12500. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12501. << D;
  12502. }
  12503. continue;
  12504. }
  12505. }
  12506. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  12507. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  12508. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12509. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  12510. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12511. QualType PrivateTy = Type;
  12512. // Try if we can determine constant lengths for all array sections and avoid
  12513. // the VLA.
  12514. bool ConstantLengthOASE = false;
  12515. if (OASE) {
  12516. bool SingleElement;
  12517. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  12518. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  12519. Context, OASE, SingleElement, ArraySizes);
  12520. // If we don't have a single element, we must emit a constant array type.
  12521. if (ConstantLengthOASE && !SingleElement) {
  12522. for (llvm::APSInt &Size : ArraySizes)
  12523. PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
  12524. ArrayType::Normal,
  12525. /*IndexTypeQuals=*/0);
  12526. }
  12527. }
  12528. if ((OASE && !ConstantLengthOASE) ||
  12529. (!OASE && !ASE &&
  12530. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  12531. if (!Context.getTargetInfo().isVLASupported()) {
  12532. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
  12533. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12534. S.Diag(ELoc, diag::note_vla_unsupported);
  12535. } else {
  12536. S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12537. S.targetDiag(ELoc, diag::note_vla_unsupported);
  12538. }
  12539. continue;
  12540. }
  12541. // For arrays/array sections only:
  12542. // Create pseudo array type for private copy. The size for this array will
  12543. // be generated during codegen.
  12544. // For array subscripts or single variables Private Ty is the same as Type
  12545. // (type of the variable or single array element).
  12546. PrivateTy = Context.getVariableArrayType(
  12547. Type,
  12548. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  12549. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  12550. } else if (!ASE && !OASE &&
  12551. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  12552. PrivateTy = D->getType().getNonReferenceType();
  12553. }
  12554. // Private copy.
  12555. VarDecl *PrivateVD =
  12556. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  12557. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12558. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12559. // Add initializer for private variable.
  12560. Expr *Init = nullptr;
  12561. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  12562. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  12563. if (DeclareReductionRef.isUsable()) {
  12564. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  12565. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  12566. if (DRD->getInitializer()) {
  12567. Init = DRDRef;
  12568. RHSVD->setInit(DRDRef);
  12569. RHSVD->setInitStyle(VarDecl::CallInit);
  12570. }
  12571. } else {
  12572. switch (BOK) {
  12573. case BO_Add:
  12574. case BO_Xor:
  12575. case BO_Or:
  12576. case BO_LOr:
  12577. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  12578. if (Type->isScalarType() || Type->isAnyComplexType())
  12579. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  12580. break;
  12581. case BO_Mul:
  12582. case BO_LAnd:
  12583. if (Type->isScalarType() || Type->isAnyComplexType()) {
  12584. // '*' and '&&' reduction ops - initializer is '1'.
  12585. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  12586. }
  12587. break;
  12588. case BO_And: {
  12589. // '&' reduction op - initializer is '~0'.
  12590. QualType OrigType = Type;
  12591. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  12592. Type = ComplexTy->getElementType();
  12593. if (Type->isRealFloatingType()) {
  12594. llvm::APFloat InitValue =
  12595. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  12596. /*isIEEE=*/true);
  12597. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12598. Type, ELoc);
  12599. } else if (Type->isScalarType()) {
  12600. uint64_t Size = Context.getTypeSize(Type);
  12601. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  12602. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  12603. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12604. }
  12605. if (Init && OrigType->isAnyComplexType()) {
  12606. // Init = 0xFFFF + 0xFFFFi;
  12607. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  12608. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  12609. }
  12610. Type = OrigType;
  12611. break;
  12612. }
  12613. case BO_LT:
  12614. case BO_GT: {
  12615. // 'min' reduction op - initializer is 'Largest representable number in
  12616. // the reduction list item type'.
  12617. // 'max' reduction op - initializer is 'Least representable number in
  12618. // the reduction list item type'.
  12619. if (Type->isIntegerType() || Type->isPointerType()) {
  12620. bool IsSigned = Type->hasSignedIntegerRepresentation();
  12621. uint64_t Size = Context.getTypeSize(Type);
  12622. QualType IntTy =
  12623. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  12624. llvm::APInt InitValue =
  12625. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  12626. : llvm::APInt::getMinValue(Size)
  12627. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  12628. : llvm::APInt::getMaxValue(Size);
  12629. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12630. if (Type->isPointerType()) {
  12631. // Cast to pointer type.
  12632. ExprResult CastExpr = S.BuildCStyleCastExpr(
  12633. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  12634. if (CastExpr.isInvalid())
  12635. continue;
  12636. Init = CastExpr.get();
  12637. }
  12638. } else if (Type->isRealFloatingType()) {
  12639. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  12640. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  12641. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12642. Type, ELoc);
  12643. }
  12644. break;
  12645. }
  12646. case BO_PtrMemD:
  12647. case BO_PtrMemI:
  12648. case BO_MulAssign:
  12649. case BO_Div:
  12650. case BO_Rem:
  12651. case BO_Sub:
  12652. case BO_Shl:
  12653. case BO_Shr:
  12654. case BO_LE:
  12655. case BO_GE:
  12656. case BO_EQ:
  12657. case BO_NE:
  12658. case BO_Cmp:
  12659. case BO_AndAssign:
  12660. case BO_XorAssign:
  12661. case BO_OrAssign:
  12662. case BO_Assign:
  12663. case BO_AddAssign:
  12664. case BO_SubAssign:
  12665. case BO_DivAssign:
  12666. case BO_RemAssign:
  12667. case BO_ShlAssign:
  12668. case BO_ShrAssign:
  12669. case BO_Comma:
  12670. llvm_unreachable("Unexpected reduction operation");
  12671. }
  12672. }
  12673. if (Init && DeclareReductionRef.isUnset())
  12674. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  12675. else if (!Init)
  12676. S.ActOnUninitializedDecl(RHSVD);
  12677. if (RHSVD->isInvalidDecl())
  12678. continue;
  12679. if (!RHSVD->hasInit() &&
  12680. (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
  12681. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  12682. << Type << ReductionIdRange;
  12683. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12684. VarDecl::DeclarationOnly;
  12685. S.Diag(D->getLocation(),
  12686. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12687. << D;
  12688. continue;
  12689. }
  12690. // Store initializer for single element in private copy. Will be used during
  12691. // codegen.
  12692. PrivateVD->setInit(RHSVD->getInit());
  12693. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  12694. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  12695. ExprResult ReductionOp;
  12696. if (DeclareReductionRef.isUsable()) {
  12697. QualType RedTy = DeclareReductionRef.get()->getType();
  12698. QualType PtrRedTy = Context.getPointerType(RedTy);
  12699. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  12700. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  12701. if (!BasePath.empty()) {
  12702. LHS = S.DefaultLvalueConversion(LHS.get());
  12703. RHS = S.DefaultLvalueConversion(RHS.get());
  12704. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12705. CK_UncheckedDerivedToBase, LHS.get(),
  12706. &BasePath, LHS.get()->getValueKind());
  12707. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12708. CK_UncheckedDerivedToBase, RHS.get(),
  12709. &BasePath, RHS.get()->getValueKind());
  12710. }
  12711. FunctionProtoType::ExtProtoInfo EPI;
  12712. QualType Params[] = {PtrRedTy, PtrRedTy};
  12713. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  12714. auto *OVE = new (Context) OpaqueValueExpr(
  12715. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  12716. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  12717. Expr *Args[] = {LHS.get(), RHS.get()};
  12718. ReductionOp =
  12719. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  12720. } else {
  12721. ReductionOp = S.BuildBinOp(
  12722. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  12723. if (ReductionOp.isUsable()) {
  12724. if (BOK != BO_LT && BOK != BO_GT) {
  12725. ReductionOp =
  12726. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12727. BO_Assign, LHSDRE, ReductionOp.get());
  12728. } else {
  12729. auto *ConditionalOp = new (Context)
  12730. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  12731. Type, VK_LValue, OK_Ordinary);
  12732. ReductionOp =
  12733. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12734. BO_Assign, LHSDRE, ConditionalOp);
  12735. }
  12736. if (ReductionOp.isUsable())
  12737. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  12738. /*DiscardedValue*/ false);
  12739. }
  12740. if (!ReductionOp.isUsable())
  12741. continue;
  12742. }
  12743. // OpenMP [2.15.4.6, Restrictions, p.2]
  12744. // A list item that appears in an in_reduction clause of a task construct
  12745. // must appear in a task_reduction clause of a construct associated with a
  12746. // taskgroup region that includes the participating task in its taskgroup
  12747. // set. The construct associated with the innermost region that meets this
  12748. // condition must specify the same reduction-identifier as the in_reduction
  12749. // clause.
  12750. if (ClauseKind == OMPC_in_reduction) {
  12751. SourceRange ParentSR;
  12752. BinaryOperatorKind ParentBOK;
  12753. const Expr *ParentReductionOp;
  12754. Expr *ParentBOKTD, *ParentReductionOpTD;
  12755. DSAStackTy::DSAVarData ParentBOKDSA =
  12756. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  12757. ParentBOKTD);
  12758. DSAStackTy::DSAVarData ParentReductionOpDSA =
  12759. Stack->getTopMostTaskgroupReductionData(
  12760. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  12761. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  12762. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  12763. if (!IsParentBOK && !IsParentReductionOp) {
  12764. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  12765. continue;
  12766. }
  12767. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  12768. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  12769. IsParentReductionOp) {
  12770. bool EmitError = true;
  12771. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  12772. llvm::FoldingSetNodeID RedId, ParentRedId;
  12773. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  12774. DeclareReductionRef.get()->Profile(RedId, Context,
  12775. /*Canonical=*/true);
  12776. EmitError = RedId != ParentRedId;
  12777. }
  12778. if (EmitError) {
  12779. S.Diag(ReductionId.getBeginLoc(),
  12780. diag::err_omp_reduction_identifier_mismatch)
  12781. << ReductionIdRange << RefExpr->getSourceRange();
  12782. S.Diag(ParentSR.getBegin(),
  12783. diag::note_omp_previous_reduction_identifier)
  12784. << ParentSR
  12785. << (IsParentBOK ? ParentBOKDSA.RefExpr
  12786. : ParentReductionOpDSA.RefExpr)
  12787. ->getSourceRange();
  12788. continue;
  12789. }
  12790. }
  12791. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  12792. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  12793. }
  12794. DeclRefExpr *Ref = nullptr;
  12795. Expr *VarsExpr = RefExpr->IgnoreParens();
  12796. if (!VD && !S.CurContext->isDependentContext()) {
  12797. if (ASE || OASE) {
  12798. TransformExprToCaptures RebuildToCapture(S, D);
  12799. VarsExpr =
  12800. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  12801. Ref = RebuildToCapture.getCapturedExpr();
  12802. } else {
  12803. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  12804. }
  12805. if (!S.isOpenMPCapturedDecl(D)) {
  12806. RD.ExprCaptures.emplace_back(Ref->getDecl());
  12807. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12808. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  12809. if (!RefRes.isUsable())
  12810. continue;
  12811. ExprResult PostUpdateRes =
  12812. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  12813. RefRes.get());
  12814. if (!PostUpdateRes.isUsable())
  12815. continue;
  12816. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  12817. Stack->getCurrentDirective() == OMPD_taskgroup) {
  12818. S.Diag(RefExpr->getExprLoc(),
  12819. diag::err_omp_reduction_non_addressable_expression)
  12820. << RefExpr->getSourceRange();
  12821. continue;
  12822. }
  12823. RD.ExprPostUpdates.emplace_back(
  12824. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  12825. }
  12826. }
  12827. }
  12828. // All reduction items are still marked as reduction (to do not increase
  12829. // code base size).
  12830. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  12831. if (CurrDir == OMPD_taskgroup) {
  12832. if (DeclareReductionRef.isUsable())
  12833. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  12834. DeclareReductionRef.get());
  12835. else
  12836. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  12837. }
  12838. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  12839. TaskgroupDescriptor);
  12840. }
  12841. return RD.Vars.empty();
  12842. }
  12843. OMPClause *Sema::ActOnOpenMPReductionClause(
  12844. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12845. SourceLocation ColonLoc, SourceLocation EndLoc,
  12846. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12847. ArrayRef<Expr *> UnresolvedReductions) {
  12848. ReductionData RD(VarList.size());
  12849. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  12850. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12851. ReductionIdScopeSpec, ReductionId,
  12852. UnresolvedReductions, RD))
  12853. return nullptr;
  12854. return OMPReductionClause::Create(
  12855. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12856. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12857. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12858. buildPreInits(Context, RD.ExprCaptures),
  12859. buildPostUpdate(*this, RD.ExprPostUpdates));
  12860. }
  12861. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  12862. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12863. SourceLocation ColonLoc, SourceLocation EndLoc,
  12864. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12865. ArrayRef<Expr *> UnresolvedReductions) {
  12866. ReductionData RD(VarList.size());
  12867. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  12868. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12869. ReductionIdScopeSpec, ReductionId,
  12870. UnresolvedReductions, RD))
  12871. return nullptr;
  12872. return OMPTaskReductionClause::Create(
  12873. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12874. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12875. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12876. buildPreInits(Context, RD.ExprCaptures),
  12877. buildPostUpdate(*this, RD.ExprPostUpdates));
  12878. }
  12879. OMPClause *Sema::ActOnOpenMPInReductionClause(
  12880. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12881. SourceLocation ColonLoc, SourceLocation EndLoc,
  12882. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12883. ArrayRef<Expr *> UnresolvedReductions) {
  12884. ReductionData RD(VarList.size());
  12885. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  12886. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12887. ReductionIdScopeSpec, ReductionId,
  12888. UnresolvedReductions, RD))
  12889. return nullptr;
  12890. return OMPInReductionClause::Create(
  12891. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12892. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12893. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  12894. buildPreInits(Context, RD.ExprCaptures),
  12895. buildPostUpdate(*this, RD.ExprPostUpdates));
  12896. }
  12897. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  12898. SourceLocation LinLoc) {
  12899. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  12900. LinKind == OMPC_LINEAR_unknown) {
  12901. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  12902. return true;
  12903. }
  12904. return false;
  12905. }
  12906. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  12907. OpenMPLinearClauseKind LinKind,
  12908. QualType Type) {
  12909. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  12910. // A variable must not have an incomplete type or a reference type.
  12911. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  12912. return true;
  12913. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  12914. !Type->isReferenceType()) {
  12915. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  12916. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  12917. return true;
  12918. }
  12919. Type = Type.getNonReferenceType();
  12920. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  12921. // A variable that is privatized must not have a const-qualified type
  12922. // unless it is of class type with a mutable member. This restriction does
  12923. // not apply to the firstprivate clause.
  12924. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  12925. return true;
  12926. // A list item must be of integral or pointer type.
  12927. Type = Type.getUnqualifiedType().getCanonicalType();
  12928. const auto *Ty = Type.getTypePtrOrNull();
  12929. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  12930. !Ty->isPointerType())) {
  12931. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  12932. if (D) {
  12933. bool IsDecl =
  12934. !VD ||
  12935. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12936. Diag(D->getLocation(),
  12937. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12938. << D;
  12939. }
  12940. return true;
  12941. }
  12942. return false;
  12943. }
  12944. OMPClause *Sema::ActOnOpenMPLinearClause(
  12945. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  12946. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  12947. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12948. SmallVector<Expr *, 8> Vars;
  12949. SmallVector<Expr *, 8> Privates;
  12950. SmallVector<Expr *, 8> Inits;
  12951. SmallVector<Decl *, 4> ExprCaptures;
  12952. SmallVector<Expr *, 4> ExprPostUpdates;
  12953. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  12954. LinKind = OMPC_LINEAR_val;
  12955. for (Expr *RefExpr : VarList) {
  12956. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12957. SourceLocation ELoc;
  12958. SourceRange ERange;
  12959. Expr *SimpleRefExpr = RefExpr;
  12960. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12961. if (Res.second) {
  12962. // It will be analyzed later.
  12963. Vars.push_back(RefExpr);
  12964. Privates.push_back(nullptr);
  12965. Inits.push_back(nullptr);
  12966. }
  12967. ValueDecl *D = Res.first;
  12968. if (!D)
  12969. continue;
  12970. QualType Type = D->getType();
  12971. auto *VD = dyn_cast<VarDecl>(D);
  12972. // OpenMP [2.14.3.7, linear clause]
  12973. // A list-item cannot appear in more than one linear clause.
  12974. // A list-item that appears in a linear clause cannot appear in any
  12975. // other data-sharing attribute clause.
  12976. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12977. if (DVar.RefExpr) {
  12978. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  12979. << getOpenMPClauseName(OMPC_linear);
  12980. reportOriginalDsa(*this, DSAStack, D, DVar);
  12981. continue;
  12982. }
  12983. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  12984. continue;
  12985. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12986. // Build private copy of original var.
  12987. VarDecl *Private =
  12988. buildVarDecl(*this, ELoc, Type, D->getName(),
  12989. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12990. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12991. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  12992. // Build var to save initial value.
  12993. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  12994. Expr *InitExpr;
  12995. DeclRefExpr *Ref = nullptr;
  12996. if (!VD && !CurContext->isDependentContext()) {
  12997. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  12998. if (!isOpenMPCapturedDecl(D)) {
  12999. ExprCaptures.push_back(Ref->getDecl());
  13000. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  13001. ExprResult RefRes = DefaultLvalueConversion(Ref);
  13002. if (!RefRes.isUsable())
  13003. continue;
  13004. ExprResult PostUpdateRes =
  13005. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  13006. SimpleRefExpr, RefRes.get());
  13007. if (!PostUpdateRes.isUsable())
  13008. continue;
  13009. ExprPostUpdates.push_back(
  13010. IgnoredValueConversions(PostUpdateRes.get()).get());
  13011. }
  13012. }
  13013. }
  13014. if (LinKind == OMPC_LINEAR_uval)
  13015. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  13016. else
  13017. InitExpr = VD ? SimpleRefExpr : Ref;
  13018. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  13019. /*DirectInit=*/false);
  13020. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  13021. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  13022. Vars.push_back((VD || CurContext->isDependentContext())
  13023. ? RefExpr->IgnoreParens()
  13024. : Ref);
  13025. Privates.push_back(PrivateRef);
  13026. Inits.push_back(InitRef);
  13027. }
  13028. if (Vars.empty())
  13029. return nullptr;
  13030. Expr *StepExpr = Step;
  13031. Expr *CalcStepExpr = nullptr;
  13032. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  13033. !Step->isInstantiationDependent() &&
  13034. !Step->containsUnexpandedParameterPack()) {
  13035. SourceLocation StepLoc = Step->getBeginLoc();
  13036. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  13037. if (Val.isInvalid())
  13038. return nullptr;
  13039. StepExpr = Val.get();
  13040. // Build var to save the step value.
  13041. VarDecl *SaveVar =
  13042. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  13043. ExprResult SaveRef =
  13044. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  13045. ExprResult CalcStep =
  13046. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  13047. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  13048. // Warn about zero linear step (it would be probably better specified as
  13049. // making corresponding variables 'const').
  13050. llvm::APSInt Result;
  13051. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  13052. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  13053. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  13054. << (Vars.size() > 1);
  13055. if (!IsConstant && CalcStep.isUsable()) {
  13056. // Calculate the step beforehand instead of doing this on each iteration.
  13057. // (This is not used if the number of iterations may be kfold-ed).
  13058. CalcStepExpr = CalcStep.get();
  13059. }
  13060. }
  13061. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  13062. ColonLoc, EndLoc, Vars, Privates, Inits,
  13063. StepExpr, CalcStepExpr,
  13064. buildPreInits(Context, ExprCaptures),
  13065. buildPostUpdate(*this, ExprPostUpdates));
  13066. }
  13067. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  13068. Expr *NumIterations, Sema &SemaRef,
  13069. Scope *S, DSAStackTy *Stack) {
  13070. // Walk the vars and build update/final expressions for the CodeGen.
  13071. SmallVector<Expr *, 8> Updates;
  13072. SmallVector<Expr *, 8> Finals;
  13073. SmallVector<Expr *, 8> UsedExprs;
  13074. Expr *Step = Clause.getStep();
  13075. Expr *CalcStep = Clause.getCalcStep();
  13076. // OpenMP [2.14.3.7, linear clause]
  13077. // If linear-step is not specified it is assumed to be 1.
  13078. if (!Step)
  13079. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  13080. else if (CalcStep)
  13081. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  13082. bool HasErrors = false;
  13083. auto CurInit = Clause.inits().begin();
  13084. auto CurPrivate = Clause.privates().begin();
  13085. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  13086. for (Expr *RefExpr : Clause.varlists()) {
  13087. SourceLocation ELoc;
  13088. SourceRange ERange;
  13089. Expr *SimpleRefExpr = RefExpr;
  13090. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  13091. ValueDecl *D = Res.first;
  13092. if (Res.second || !D) {
  13093. Updates.push_back(nullptr);
  13094. Finals.push_back(nullptr);
  13095. HasErrors = true;
  13096. continue;
  13097. }
  13098. auto &&Info = Stack->isLoopControlVariable(D);
  13099. // OpenMP [2.15.11, distribute simd Construct]
  13100. // A list item may not appear in a linear clause, unless it is the loop
  13101. // iteration variable.
  13102. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  13103. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  13104. SemaRef.Diag(ELoc,
  13105. diag::err_omp_linear_distribute_var_non_loop_iteration);
  13106. Updates.push_back(nullptr);
  13107. Finals.push_back(nullptr);
  13108. HasErrors = true;
  13109. continue;
  13110. }
  13111. Expr *InitExpr = *CurInit;
  13112. // Build privatized reference to the current linear var.
  13113. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  13114. Expr *CapturedRef;
  13115. if (LinKind == OMPC_LINEAR_uval)
  13116. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  13117. else
  13118. CapturedRef =
  13119. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  13120. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  13121. /*RefersToCapture=*/true);
  13122. // Build update: Var = InitExpr + IV * Step
  13123. ExprResult Update;
  13124. if (!Info.first)
  13125. Update = buildCounterUpdate(
  13126. SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
  13127. /*Subtract=*/false, /*IsNonRectangularLB=*/false);
  13128. else
  13129. Update = *CurPrivate;
  13130. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  13131. /*DiscardedValue*/ false);
  13132. // Build final: Var = InitExpr + NumIterations * Step
  13133. ExprResult Final;
  13134. if (!Info.first)
  13135. Final =
  13136. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  13137. InitExpr, NumIterations, Step, /*Subtract=*/false,
  13138. /*IsNonRectangularLB=*/false);
  13139. else
  13140. Final = *CurPrivate;
  13141. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  13142. /*DiscardedValue*/ false);
  13143. if (!Update.isUsable() || !Final.isUsable()) {
  13144. Updates.push_back(nullptr);
  13145. Finals.push_back(nullptr);
  13146. UsedExprs.push_back(nullptr);
  13147. HasErrors = true;
  13148. } else {
  13149. Updates.push_back(Update.get());
  13150. Finals.push_back(Final.get());
  13151. if (!Info.first)
  13152. UsedExprs.push_back(SimpleRefExpr);
  13153. }
  13154. ++CurInit;
  13155. ++CurPrivate;
  13156. }
  13157. if (Expr *S = Clause.getStep())
  13158. UsedExprs.push_back(S);
  13159. // Fill the remaining part with the nullptr.
  13160. UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
  13161. Clause.setUpdates(Updates);
  13162. Clause.setFinals(Finals);
  13163. Clause.setUsedExprs(UsedExprs);
  13164. return HasErrors;
  13165. }
  13166. OMPClause *Sema::ActOnOpenMPAlignedClause(
  13167. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  13168. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  13169. SmallVector<Expr *, 8> Vars;
  13170. for (Expr *RefExpr : VarList) {
  13171. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  13172. SourceLocation ELoc;
  13173. SourceRange ERange;
  13174. Expr *SimpleRefExpr = RefExpr;
  13175. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13176. if (Res.second) {
  13177. // It will be analyzed later.
  13178. Vars.push_back(RefExpr);
  13179. }
  13180. ValueDecl *D = Res.first;
  13181. if (!D)
  13182. continue;
  13183. QualType QType = D->getType();
  13184. auto *VD = dyn_cast<VarDecl>(D);
  13185. // OpenMP [2.8.1, simd construct, Restrictions]
  13186. // The type of list items appearing in the aligned clause must be
  13187. // array, pointer, reference to array, or reference to pointer.
  13188. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  13189. const Type *Ty = QType.getTypePtrOrNull();
  13190. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  13191. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  13192. << QType << getLangOpts().CPlusPlus << ERange;
  13193. bool IsDecl =
  13194. !VD ||
  13195. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  13196. Diag(D->getLocation(),
  13197. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  13198. << D;
  13199. continue;
  13200. }
  13201. // OpenMP [2.8.1, simd construct, Restrictions]
  13202. // A list-item cannot appear in more than one aligned clause.
  13203. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  13204. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  13205. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  13206. << getOpenMPClauseName(OMPC_aligned);
  13207. continue;
  13208. }
  13209. DeclRefExpr *Ref = nullptr;
  13210. if (!VD && isOpenMPCapturedDecl(D))
  13211. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  13212. Vars.push_back(DefaultFunctionArrayConversion(
  13213. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  13214. .get());
  13215. }
  13216. // OpenMP [2.8.1, simd construct, Description]
  13217. // The parameter of the aligned clause, alignment, must be a constant
  13218. // positive integer expression.
  13219. // If no optional parameter is specified, implementation-defined default
  13220. // alignments for SIMD instructions on the target platforms are assumed.
  13221. if (Alignment != nullptr) {
  13222. ExprResult AlignResult =
  13223. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  13224. if (AlignResult.isInvalid())
  13225. return nullptr;
  13226. Alignment = AlignResult.get();
  13227. }
  13228. if (Vars.empty())
  13229. return nullptr;
  13230. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  13231. EndLoc, Vars, Alignment);
  13232. }
  13233. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  13234. SourceLocation StartLoc,
  13235. SourceLocation LParenLoc,
  13236. SourceLocation EndLoc) {
  13237. SmallVector<Expr *, 8> Vars;
  13238. SmallVector<Expr *, 8> SrcExprs;
  13239. SmallVector<Expr *, 8> DstExprs;
  13240. SmallVector<Expr *, 8> AssignmentOps;
  13241. for (Expr *RefExpr : VarList) {
  13242. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  13243. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  13244. // It will be analyzed later.
  13245. Vars.push_back(RefExpr);
  13246. SrcExprs.push_back(nullptr);
  13247. DstExprs.push_back(nullptr);
  13248. AssignmentOps.push_back(nullptr);
  13249. continue;
  13250. }
  13251. SourceLocation ELoc = RefExpr->getExprLoc();
  13252. // OpenMP [2.1, C/C++]
  13253. // A list item is a variable name.
  13254. // OpenMP [2.14.4.1, Restrictions, p.1]
  13255. // A list item that appears in a copyin clause must be threadprivate.
  13256. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  13257. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  13258. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  13259. << 0 << RefExpr->getSourceRange();
  13260. continue;
  13261. }
  13262. Decl *D = DE->getDecl();
  13263. auto *VD = cast<VarDecl>(D);
  13264. QualType Type = VD->getType();
  13265. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  13266. // It will be analyzed later.
  13267. Vars.push_back(DE);
  13268. SrcExprs.push_back(nullptr);
  13269. DstExprs.push_back(nullptr);
  13270. AssignmentOps.push_back(nullptr);
  13271. continue;
  13272. }
  13273. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  13274. // A list item that appears in a copyin clause must be threadprivate.
  13275. if (!DSAStack->isThreadPrivate(VD)) {
  13276. Diag(ELoc, diag::err_omp_required_access)
  13277. << getOpenMPClauseName(OMPC_copyin)
  13278. << getOpenMPDirectiveName(OMPD_threadprivate);
  13279. continue;
  13280. }
  13281. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  13282. // A variable of class type (or array thereof) that appears in a
  13283. // copyin clause requires an accessible, unambiguous copy assignment
  13284. // operator for the class type.
  13285. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  13286. VarDecl *SrcVD =
  13287. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  13288. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  13289. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  13290. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  13291. VarDecl *DstVD =
  13292. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  13293. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  13294. DeclRefExpr *PseudoDstExpr =
  13295. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  13296. // For arrays generate assignment operation for single element and replace
  13297. // it by the original array element in CodeGen.
  13298. ExprResult AssignmentOp =
  13299. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  13300. PseudoSrcExpr);
  13301. if (AssignmentOp.isInvalid())
  13302. continue;
  13303. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  13304. /*DiscardedValue*/ false);
  13305. if (AssignmentOp.isInvalid())
  13306. continue;
  13307. DSAStack->addDSA(VD, DE, OMPC_copyin);
  13308. Vars.push_back(DE);
  13309. SrcExprs.push_back(PseudoSrcExpr);
  13310. DstExprs.push_back(PseudoDstExpr);
  13311. AssignmentOps.push_back(AssignmentOp.get());
  13312. }
  13313. if (Vars.empty())
  13314. return nullptr;
  13315. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  13316. SrcExprs, DstExprs, AssignmentOps);
  13317. }
  13318. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  13319. SourceLocation StartLoc,
  13320. SourceLocation LParenLoc,
  13321. SourceLocation EndLoc) {
  13322. SmallVector<Expr *, 8> Vars;
  13323. SmallVector<Expr *, 8> SrcExprs;
  13324. SmallVector<Expr *, 8> DstExprs;
  13325. SmallVector<Expr *, 8> AssignmentOps;
  13326. for (Expr *RefExpr : VarList) {
  13327. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  13328. SourceLocation ELoc;
  13329. SourceRange ERange;
  13330. Expr *SimpleRefExpr = RefExpr;
  13331. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13332. if (Res.second) {
  13333. // It will be analyzed later.
  13334. Vars.push_back(RefExpr);
  13335. SrcExprs.push_back(nullptr);
  13336. DstExprs.push_back(nullptr);
  13337. AssignmentOps.push_back(nullptr);
  13338. }
  13339. ValueDecl *D = Res.first;
  13340. if (!D)
  13341. continue;
  13342. QualType Type = D->getType();
  13343. auto *VD = dyn_cast<VarDecl>(D);
  13344. // OpenMP [2.14.4.2, Restrictions, p.2]
  13345. // A list item that appears in a copyprivate clause may not appear in a
  13346. // private or firstprivate clause on the single construct.
  13347. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  13348. DSAStackTy::DSAVarData DVar =
  13349. DSAStack->getTopDSA(D, /*FromParent=*/false);
  13350. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  13351. DVar.RefExpr) {
  13352. Diag(ELoc, diag::err_omp_wrong_dsa)
  13353. << getOpenMPClauseName(DVar.CKind)
  13354. << getOpenMPClauseName(OMPC_copyprivate);
  13355. reportOriginalDsa(*this, DSAStack, D, DVar);
  13356. continue;
  13357. }
  13358. // OpenMP [2.11.4.2, Restrictions, p.1]
  13359. // All list items that appear in a copyprivate clause must be either
  13360. // threadprivate or private in the enclosing context.
  13361. if (DVar.CKind == OMPC_unknown) {
  13362. DVar = DSAStack->getImplicitDSA(D, false);
  13363. if (DVar.CKind == OMPC_shared) {
  13364. Diag(ELoc, diag::err_omp_required_access)
  13365. << getOpenMPClauseName(OMPC_copyprivate)
  13366. << "threadprivate or private in the enclosing context";
  13367. reportOriginalDsa(*this, DSAStack, D, DVar);
  13368. continue;
  13369. }
  13370. }
  13371. }
  13372. // Variably modified types are not supported.
  13373. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  13374. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  13375. << getOpenMPClauseName(OMPC_copyprivate) << Type
  13376. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  13377. bool IsDecl =
  13378. !VD ||
  13379. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  13380. Diag(D->getLocation(),
  13381. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  13382. << D;
  13383. continue;
  13384. }
  13385. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  13386. // A variable of class type (or array thereof) that appears in a
  13387. // copyin clause requires an accessible, unambiguous copy assignment
  13388. // operator for the class type.
  13389. Type = Context.getBaseElementType(Type.getNonReferenceType())
  13390. .getUnqualifiedType();
  13391. VarDecl *SrcVD =
  13392. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  13393. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13394. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  13395. VarDecl *DstVD =
  13396. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  13397. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13398. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  13399. ExprResult AssignmentOp = BuildBinOp(
  13400. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  13401. if (AssignmentOp.isInvalid())
  13402. continue;
  13403. AssignmentOp =
  13404. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  13405. if (AssignmentOp.isInvalid())
  13406. continue;
  13407. // No need to mark vars as copyprivate, they are already threadprivate or
  13408. // implicitly private.
  13409. assert(VD || isOpenMPCapturedDecl(D));
  13410. Vars.push_back(
  13411. VD ? RefExpr->IgnoreParens()
  13412. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  13413. SrcExprs.push_back(PseudoSrcExpr);
  13414. DstExprs.push_back(PseudoDstExpr);
  13415. AssignmentOps.push_back(AssignmentOp.get());
  13416. }
  13417. if (Vars.empty())
  13418. return nullptr;
  13419. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13420. Vars, SrcExprs, DstExprs, AssignmentOps);
  13421. }
  13422. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  13423. SourceLocation StartLoc,
  13424. SourceLocation LParenLoc,
  13425. SourceLocation EndLoc) {
  13426. if (VarList.empty())
  13427. return nullptr;
  13428. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  13429. }
  13430. OMPClause *
  13431. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  13432. SourceLocation DepLoc, SourceLocation ColonLoc,
  13433. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  13434. SourceLocation LParenLoc, SourceLocation EndLoc) {
  13435. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  13436. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  13437. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13438. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  13439. return nullptr;
  13440. }
  13441. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  13442. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  13443. DepKind == OMPC_DEPEND_sink)) {
  13444. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  13445. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13446. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  13447. /*Last=*/OMPC_DEPEND_unknown, Except)
  13448. << getOpenMPClauseName(OMPC_depend);
  13449. return nullptr;
  13450. }
  13451. SmallVector<Expr *, 8> Vars;
  13452. DSAStackTy::OperatorOffsetTy OpsOffs;
  13453. llvm::APSInt DepCounter(/*BitWidth=*/32);
  13454. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  13455. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  13456. if (const Expr *OrderedCountExpr =
  13457. DSAStack->getParentOrderedRegionParam().first) {
  13458. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  13459. TotalDepCount.setIsUnsigned(/*Val=*/true);
  13460. }
  13461. }
  13462. for (Expr *RefExpr : VarList) {
  13463. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  13464. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  13465. // It will be analyzed later.
  13466. Vars.push_back(RefExpr);
  13467. continue;
  13468. }
  13469. SourceLocation ELoc = RefExpr->getExprLoc();
  13470. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  13471. if (DepKind == OMPC_DEPEND_sink) {
  13472. if (DSAStack->getParentOrderedRegionParam().first &&
  13473. DepCounter >= TotalDepCount) {
  13474. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  13475. continue;
  13476. }
  13477. ++DepCounter;
  13478. // OpenMP [2.13.9, Summary]
  13479. // depend(dependence-type : vec), where dependence-type is:
  13480. // 'sink' and where vec is the iteration vector, which has the form:
  13481. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  13482. // where n is the value specified by the ordered clause in the loop
  13483. // directive, xi denotes the loop iteration variable of the i-th nested
  13484. // loop associated with the loop directive, and di is a constant
  13485. // non-negative integer.
  13486. if (CurContext->isDependentContext()) {
  13487. // It will be analyzed later.
  13488. Vars.push_back(RefExpr);
  13489. continue;
  13490. }
  13491. SimpleExpr = SimpleExpr->IgnoreImplicit();
  13492. OverloadedOperatorKind OOK = OO_None;
  13493. SourceLocation OOLoc;
  13494. Expr *LHS = SimpleExpr;
  13495. Expr *RHS = nullptr;
  13496. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  13497. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  13498. OOLoc = BO->getOperatorLoc();
  13499. LHS = BO->getLHS()->IgnoreParenImpCasts();
  13500. RHS = BO->getRHS()->IgnoreParenImpCasts();
  13501. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  13502. OOK = OCE->getOperator();
  13503. OOLoc = OCE->getOperatorLoc();
  13504. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13505. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  13506. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  13507. OOK = MCE->getMethodDecl()
  13508. ->getNameInfo()
  13509. .getName()
  13510. .getCXXOverloadedOperator();
  13511. OOLoc = MCE->getCallee()->getExprLoc();
  13512. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  13513. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13514. }
  13515. SourceLocation ELoc;
  13516. SourceRange ERange;
  13517. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  13518. if (Res.second) {
  13519. // It will be analyzed later.
  13520. Vars.push_back(RefExpr);
  13521. }
  13522. ValueDecl *D = Res.first;
  13523. if (!D)
  13524. continue;
  13525. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  13526. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  13527. continue;
  13528. }
  13529. if (RHS) {
  13530. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  13531. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  13532. if (RHSRes.isInvalid())
  13533. continue;
  13534. }
  13535. if (!CurContext->isDependentContext() &&
  13536. DSAStack->getParentOrderedRegionParam().first &&
  13537. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  13538. const ValueDecl *VD =
  13539. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  13540. if (VD)
  13541. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13542. << 1 << VD;
  13543. else
  13544. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  13545. continue;
  13546. }
  13547. OpsOffs.emplace_back(RHS, OOK);
  13548. } else {
  13549. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  13550. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  13551. (ASE &&
  13552. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  13553. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  13554. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13555. << RefExpr->getSourceRange();
  13556. continue;
  13557. }
  13558. ExprResult Res;
  13559. {
  13560. Sema::TentativeAnalysisScope Trap(*this);
  13561. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  13562. RefExpr->IgnoreParenImpCasts());
  13563. }
  13564. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  13565. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13566. << RefExpr->getSourceRange();
  13567. continue;
  13568. }
  13569. }
  13570. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  13571. }
  13572. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  13573. TotalDepCount > VarList.size() &&
  13574. DSAStack->getParentOrderedRegionParam().first &&
  13575. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  13576. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13577. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  13578. }
  13579. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  13580. Vars.empty())
  13581. return nullptr;
  13582. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13583. DepKind, DepLoc, ColonLoc, Vars,
  13584. TotalDepCount.getZExtValue());
  13585. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  13586. DSAStack->isParentOrderedRegion())
  13587. DSAStack->addDoacrossDependClause(C, OpsOffs);
  13588. return C;
  13589. }
  13590. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  13591. SourceLocation LParenLoc,
  13592. SourceLocation EndLoc) {
  13593. Expr *ValExpr = Device;
  13594. Stmt *HelperValStmt = nullptr;
  13595. // OpenMP [2.9.1, Restrictions]
  13596. // The device expression must evaluate to a non-negative integer value.
  13597. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  13598. /*StrictlyPositive=*/false))
  13599. return nullptr;
  13600. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13601. OpenMPDirectiveKind CaptureRegion =
  13602. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  13603. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13604. ValExpr = MakeFullExpr(ValExpr).get();
  13605. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13606. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13607. HelperValStmt = buildPreInits(Context, Captures);
  13608. }
  13609. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  13610. StartLoc, LParenLoc, EndLoc);
  13611. }
  13612. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  13613. DSAStackTy *Stack, QualType QTy,
  13614. bool FullCheck = true) {
  13615. NamedDecl *ND;
  13616. if (QTy->isIncompleteType(&ND)) {
  13617. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  13618. return false;
  13619. }
  13620. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  13621. !QTy.isTrivialType(SemaRef.Context))
  13622. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  13623. return true;
  13624. }
  13625. /// Return true if it can be proven that the provided array expression
  13626. /// (array section or array subscript) does NOT specify the whole size of the
  13627. /// array whose base type is \a BaseQTy.
  13628. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  13629. const Expr *E,
  13630. QualType BaseQTy) {
  13631. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13632. // If this is an array subscript, it refers to the whole size if the size of
  13633. // the dimension is constant and equals 1. Also, an array section assumes the
  13634. // format of an array subscript if no colon is used.
  13635. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  13636. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13637. return ATy->getSize().getSExtValue() != 1;
  13638. // Size can't be evaluated statically.
  13639. return false;
  13640. }
  13641. assert(OASE && "Expecting array section if not an array subscript.");
  13642. const Expr *LowerBound = OASE->getLowerBound();
  13643. const Expr *Length = OASE->getLength();
  13644. // If there is a lower bound that does not evaluates to zero, we are not
  13645. // covering the whole dimension.
  13646. if (LowerBound) {
  13647. Expr::EvalResult Result;
  13648. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13649. return false; // Can't get the integer value as a constant.
  13650. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  13651. if (ConstLowerBound.getSExtValue())
  13652. return true;
  13653. }
  13654. // If we don't have a length we covering the whole dimension.
  13655. if (!Length)
  13656. return false;
  13657. // If the base is a pointer, we don't have a way to get the size of the
  13658. // pointee.
  13659. if (BaseQTy->isPointerType())
  13660. return false;
  13661. // We can only check if the length is the same as the size of the dimension
  13662. // if we have a constant array.
  13663. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  13664. if (!CATy)
  13665. return false;
  13666. Expr::EvalResult Result;
  13667. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13668. return false; // Can't get the integer value as a constant.
  13669. llvm::APSInt ConstLength = Result.Val.getInt();
  13670. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  13671. }
  13672. // Return true if it can be proven that the provided array expression (array
  13673. // section or array subscript) does NOT specify a single element of the array
  13674. // whose base type is \a BaseQTy.
  13675. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  13676. const Expr *E,
  13677. QualType BaseQTy) {
  13678. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13679. // An array subscript always refer to a single element. Also, an array section
  13680. // assumes the format of an array subscript if no colon is used.
  13681. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  13682. return false;
  13683. assert(OASE && "Expecting array section if not an array subscript.");
  13684. const Expr *Length = OASE->getLength();
  13685. // If we don't have a length we have to check if the array has unitary size
  13686. // for this dimension. Also, we should always expect a length if the base type
  13687. // is pointer.
  13688. if (!Length) {
  13689. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13690. return ATy->getSize().getSExtValue() != 1;
  13691. // We cannot assume anything.
  13692. return false;
  13693. }
  13694. // Check if the length evaluates to 1.
  13695. Expr::EvalResult Result;
  13696. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13697. return false; // Can't get the integer value as a constant.
  13698. llvm::APSInt ConstLength = Result.Val.getInt();
  13699. return ConstLength.getSExtValue() != 1;
  13700. }
  13701. // Return the expression of the base of the mappable expression or null if it
  13702. // cannot be determined and do all the necessary checks to see if the expression
  13703. // is valid as a standalone mappable expression. In the process, record all the
  13704. // components of the expression.
  13705. static const Expr *checkMapClauseExpressionBase(
  13706. Sema &SemaRef, Expr *E,
  13707. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  13708. OpenMPClauseKind CKind, bool NoDiagnose) {
  13709. SourceLocation ELoc = E->getExprLoc();
  13710. SourceRange ERange = E->getSourceRange();
  13711. // The base of elements of list in a map clause have to be either:
  13712. // - a reference to variable or field.
  13713. // - a member expression.
  13714. // - an array expression.
  13715. //
  13716. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  13717. // reference to 'r'.
  13718. //
  13719. // If we have:
  13720. //
  13721. // struct SS {
  13722. // Bla S;
  13723. // foo() {
  13724. // #pragma omp target map (S.Arr[:12]);
  13725. // }
  13726. // }
  13727. //
  13728. // We want to retrieve the member expression 'this->S';
  13729. const Expr *RelevantExpr = nullptr;
  13730. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  13731. // If a list item is an array section, it must specify contiguous storage.
  13732. //
  13733. // For this restriction it is sufficient that we make sure only references
  13734. // to variables or fields and array expressions, and that no array sections
  13735. // exist except in the rightmost expression (unless they cover the whole
  13736. // dimension of the array). E.g. these would be invalid:
  13737. //
  13738. // r.ArrS[3:5].Arr[6:7]
  13739. //
  13740. // r.ArrS[3:5].x
  13741. //
  13742. // but these would be valid:
  13743. // r.ArrS[3].Arr[6:7]
  13744. //
  13745. // r.ArrS[3].x
  13746. bool AllowUnitySizeArraySection = true;
  13747. bool AllowWholeSizeArraySection = true;
  13748. while (!RelevantExpr) {
  13749. E = E->IgnoreParenImpCasts();
  13750. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  13751. if (!isa<VarDecl>(CurE->getDecl()))
  13752. return nullptr;
  13753. RelevantExpr = CurE;
  13754. // If we got a reference to a declaration, we should not expect any array
  13755. // section before that.
  13756. AllowUnitySizeArraySection = false;
  13757. AllowWholeSizeArraySection = false;
  13758. // Record the component.
  13759. CurComponents.emplace_back(CurE, CurE->getDecl());
  13760. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  13761. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  13762. if (isa<CXXThisExpr>(BaseE))
  13763. // We found a base expression: this->Val.
  13764. RelevantExpr = CurE;
  13765. else
  13766. E = BaseE;
  13767. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  13768. if (!NoDiagnose) {
  13769. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  13770. << CurE->getSourceRange();
  13771. return nullptr;
  13772. }
  13773. if (RelevantExpr)
  13774. return nullptr;
  13775. continue;
  13776. }
  13777. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  13778. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  13779. // A bit-field cannot appear in a map clause.
  13780. //
  13781. if (FD->isBitField()) {
  13782. if (!NoDiagnose) {
  13783. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  13784. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  13785. return nullptr;
  13786. }
  13787. if (RelevantExpr)
  13788. return nullptr;
  13789. continue;
  13790. }
  13791. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13792. // If the type of a list item is a reference to a type T then the type
  13793. // will be considered to be T for all purposes of this clause.
  13794. QualType CurType = BaseE->getType().getNonReferenceType();
  13795. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  13796. // A list item cannot be a variable that is a member of a structure with
  13797. // a union type.
  13798. //
  13799. if (CurType->isUnionType()) {
  13800. if (!NoDiagnose) {
  13801. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  13802. << CurE->getSourceRange();
  13803. return nullptr;
  13804. }
  13805. continue;
  13806. }
  13807. // If we got a member expression, we should not expect any array section
  13808. // before that:
  13809. //
  13810. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  13811. // If a list item is an element of a structure, only the rightmost symbol
  13812. // of the variable reference can be an array section.
  13813. //
  13814. AllowUnitySizeArraySection = false;
  13815. AllowWholeSizeArraySection = false;
  13816. // Record the component.
  13817. CurComponents.emplace_back(CurE, FD);
  13818. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  13819. E = CurE->getBase()->IgnoreParenImpCasts();
  13820. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  13821. if (!NoDiagnose) {
  13822. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13823. << 0 << CurE->getSourceRange();
  13824. return nullptr;
  13825. }
  13826. continue;
  13827. }
  13828. // If we got an array subscript that express the whole dimension we
  13829. // can have any array expressions before. If it only expressing part of
  13830. // the dimension, we can only have unitary-size array expressions.
  13831. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  13832. E->getType()))
  13833. AllowWholeSizeArraySection = false;
  13834. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13835. Expr::EvalResult Result;
  13836. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  13837. if (!Result.Val.getInt().isNullValue()) {
  13838. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13839. diag::err_omp_invalid_map_this_expr);
  13840. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13841. diag::note_omp_invalid_subscript_on_this_ptr_map);
  13842. }
  13843. }
  13844. RelevantExpr = TE;
  13845. }
  13846. // Record the component - we don't have any declaration associated.
  13847. CurComponents.emplace_back(CurE, nullptr);
  13848. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  13849. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  13850. E = CurE->getBase()->IgnoreParenImpCasts();
  13851. QualType CurType =
  13852. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13853. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13854. // If the type of a list item is a reference to a type T then the type
  13855. // will be considered to be T for all purposes of this clause.
  13856. if (CurType->isReferenceType())
  13857. CurType = CurType->getPointeeType();
  13858. bool IsPointer = CurType->isAnyPointerType();
  13859. if (!IsPointer && !CurType->isArrayType()) {
  13860. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13861. << 0 << CurE->getSourceRange();
  13862. return nullptr;
  13863. }
  13864. bool NotWhole =
  13865. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  13866. bool NotUnity =
  13867. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  13868. if (AllowWholeSizeArraySection) {
  13869. // Any array section is currently allowed. Allowing a whole size array
  13870. // section implies allowing a unity array section as well.
  13871. //
  13872. // If this array section refers to the whole dimension we can still
  13873. // accept other array sections before this one, except if the base is a
  13874. // pointer. Otherwise, only unitary sections are accepted.
  13875. if (NotWhole || IsPointer)
  13876. AllowWholeSizeArraySection = false;
  13877. } else if (AllowUnitySizeArraySection && NotUnity) {
  13878. // A unity or whole array section is not allowed and that is not
  13879. // compatible with the properties of the current array section.
  13880. SemaRef.Diag(
  13881. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  13882. << CurE->getSourceRange();
  13883. return nullptr;
  13884. }
  13885. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13886. Expr::EvalResult ResultR;
  13887. Expr::EvalResult ResultL;
  13888. if (CurE->getLength()->EvaluateAsInt(ResultR,
  13889. SemaRef.getASTContext())) {
  13890. if (!ResultR.Val.getInt().isOneValue()) {
  13891. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13892. diag::err_omp_invalid_map_this_expr);
  13893. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13894. diag::note_omp_invalid_length_on_this_ptr_mapping);
  13895. }
  13896. }
  13897. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  13898. ResultL, SemaRef.getASTContext())) {
  13899. if (!ResultL.Val.getInt().isNullValue()) {
  13900. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13901. diag::err_omp_invalid_map_this_expr);
  13902. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13903. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  13904. }
  13905. }
  13906. RelevantExpr = TE;
  13907. }
  13908. // Record the component - we don't have any declaration associated.
  13909. CurComponents.emplace_back(CurE, nullptr);
  13910. } else {
  13911. if (!NoDiagnose) {
  13912. // If nothing else worked, this is not a valid map clause expression.
  13913. SemaRef.Diag(
  13914. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  13915. << ERange;
  13916. }
  13917. return nullptr;
  13918. }
  13919. }
  13920. return RelevantExpr;
  13921. }
  13922. // Return true if expression E associated with value VD has conflicts with other
  13923. // map information.
  13924. static bool checkMapConflicts(
  13925. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  13926. bool CurrentRegionOnly,
  13927. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  13928. OpenMPClauseKind CKind) {
  13929. assert(VD && E);
  13930. SourceLocation ELoc = E->getExprLoc();
  13931. SourceRange ERange = E->getSourceRange();
  13932. // In order to easily check the conflicts we need to match each component of
  13933. // the expression under test with the components of the expressions that are
  13934. // already in the stack.
  13935. assert(!CurComponents.empty() && "Map clause expression with no components!");
  13936. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  13937. "Map clause expression with unexpected base!");
  13938. // Variables to help detecting enclosing problems in data environment nests.
  13939. bool IsEnclosedByDataEnvironmentExpr = false;
  13940. const Expr *EnclosingExpr = nullptr;
  13941. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  13942. VD, CurrentRegionOnly,
  13943. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  13944. ERange, CKind, &EnclosingExpr,
  13945. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  13946. StackComponents,
  13947. OpenMPClauseKind) {
  13948. assert(!StackComponents.empty() &&
  13949. "Map clause expression with no components!");
  13950. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  13951. "Map clause expression with unexpected base!");
  13952. (void)VD;
  13953. // The whole expression in the stack.
  13954. const Expr *RE = StackComponents.front().getAssociatedExpression();
  13955. // Expressions must start from the same base. Here we detect at which
  13956. // point both expressions diverge from each other and see if we can
  13957. // detect if the memory referred to both expressions is contiguous and
  13958. // do not overlap.
  13959. auto CI = CurComponents.rbegin();
  13960. auto CE = CurComponents.rend();
  13961. auto SI = StackComponents.rbegin();
  13962. auto SE = StackComponents.rend();
  13963. for (; CI != CE && SI != SE; ++CI, ++SI) {
  13964. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  13965. // At most one list item can be an array item derived from a given
  13966. // variable in map clauses of the same construct.
  13967. if (CurrentRegionOnly &&
  13968. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  13969. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  13970. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  13971. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  13972. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  13973. diag::err_omp_multiple_array_items_in_map_clause)
  13974. << CI->getAssociatedExpression()->getSourceRange();
  13975. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  13976. diag::note_used_here)
  13977. << SI->getAssociatedExpression()->getSourceRange();
  13978. return true;
  13979. }
  13980. // Do both expressions have the same kind?
  13981. if (CI->getAssociatedExpression()->getStmtClass() !=
  13982. SI->getAssociatedExpression()->getStmtClass())
  13983. break;
  13984. // Are we dealing with different variables/fields?
  13985. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  13986. break;
  13987. }
  13988. // Check if the extra components of the expressions in the enclosing
  13989. // data environment are redundant for the current base declaration.
  13990. // If they are, the maps completely overlap, which is legal.
  13991. for (; SI != SE; ++SI) {
  13992. QualType Type;
  13993. if (const auto *ASE =
  13994. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  13995. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  13996. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  13997. SI->getAssociatedExpression())) {
  13998. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  13999. Type =
  14000. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  14001. }
  14002. if (Type.isNull() || Type->isAnyPointerType() ||
  14003. checkArrayExpressionDoesNotReferToWholeSize(
  14004. SemaRef, SI->getAssociatedExpression(), Type))
  14005. break;
  14006. }
  14007. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  14008. // List items of map clauses in the same construct must not share
  14009. // original storage.
  14010. //
  14011. // If the expressions are exactly the same or one is a subset of the
  14012. // other, it means they are sharing storage.
  14013. if (CI == CE && SI == SE) {
  14014. if (CurrentRegionOnly) {
  14015. if (CKind == OMPC_map) {
  14016. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  14017. } else {
  14018. assert(CKind == OMPC_to || CKind == OMPC_from);
  14019. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  14020. << ERange;
  14021. }
  14022. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  14023. << RE->getSourceRange();
  14024. return true;
  14025. }
  14026. // If we find the same expression in the enclosing data environment,
  14027. // that is legal.
  14028. IsEnclosedByDataEnvironmentExpr = true;
  14029. return false;
  14030. }
  14031. QualType DerivedType =
  14032. std::prev(CI)->getAssociatedDeclaration()->getType();
  14033. SourceLocation DerivedLoc =
  14034. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  14035. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  14036. // If the type of a list item is a reference to a type T then the type
  14037. // will be considered to be T for all purposes of this clause.
  14038. DerivedType = DerivedType.getNonReferenceType();
  14039. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  14040. // A variable for which the type is pointer and an array section
  14041. // derived from that variable must not appear as list items of map
  14042. // clauses of the same construct.
  14043. //
  14044. // Also, cover one of the cases in:
  14045. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  14046. // If any part of the original storage of a list item has corresponding
  14047. // storage in the device data environment, all of the original storage
  14048. // must have corresponding storage in the device data environment.
  14049. //
  14050. if (DerivedType->isAnyPointerType()) {
  14051. if (CI == CE || SI == SE) {
  14052. SemaRef.Diag(
  14053. DerivedLoc,
  14054. diag::err_omp_pointer_mapped_along_with_derived_section)
  14055. << DerivedLoc;
  14056. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  14057. << RE->getSourceRange();
  14058. return true;
  14059. }
  14060. if (CI->getAssociatedExpression()->getStmtClass() !=
  14061. SI->getAssociatedExpression()->getStmtClass() ||
  14062. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  14063. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  14064. assert(CI != CE && SI != SE);
  14065. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  14066. << DerivedLoc;
  14067. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  14068. << RE->getSourceRange();
  14069. return true;
  14070. }
  14071. }
  14072. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  14073. // List items of map clauses in the same construct must not share
  14074. // original storage.
  14075. //
  14076. // An expression is a subset of the other.
  14077. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  14078. if (CKind == OMPC_map) {
  14079. if (CI != CE || SI != SE) {
  14080. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  14081. // a pointer.
  14082. auto Begin =
  14083. CI != CE ? CurComponents.begin() : StackComponents.begin();
  14084. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  14085. auto It = Begin;
  14086. while (It != End && !It->getAssociatedDeclaration())
  14087. std::advance(It, 1);
  14088. assert(It != End &&
  14089. "Expected at least one component with the declaration.");
  14090. if (It != Begin && It->getAssociatedDeclaration()
  14091. ->getType()
  14092. .getCanonicalType()
  14093. ->isAnyPointerType()) {
  14094. IsEnclosedByDataEnvironmentExpr = false;
  14095. EnclosingExpr = nullptr;
  14096. return false;
  14097. }
  14098. }
  14099. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  14100. } else {
  14101. assert(CKind == OMPC_to || CKind == OMPC_from);
  14102. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  14103. << ERange;
  14104. }
  14105. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  14106. << RE->getSourceRange();
  14107. return true;
  14108. }
  14109. // The current expression uses the same base as other expression in the
  14110. // data environment but does not contain it completely.
  14111. if (!CurrentRegionOnly && SI != SE)
  14112. EnclosingExpr = RE;
  14113. // The current expression is a subset of the expression in the data
  14114. // environment.
  14115. IsEnclosedByDataEnvironmentExpr |=
  14116. (!CurrentRegionOnly && CI != CE && SI == SE);
  14117. return false;
  14118. });
  14119. if (CurrentRegionOnly)
  14120. return FoundError;
  14121. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  14122. // If any part of the original storage of a list item has corresponding
  14123. // storage in the device data environment, all of the original storage must
  14124. // have corresponding storage in the device data environment.
  14125. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  14126. // If a list item is an element of a structure, and a different element of
  14127. // the structure has a corresponding list item in the device data environment
  14128. // prior to a task encountering the construct associated with the map clause,
  14129. // then the list item must also have a corresponding list item in the device
  14130. // data environment prior to the task encountering the construct.
  14131. //
  14132. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  14133. SemaRef.Diag(ELoc,
  14134. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  14135. << ERange;
  14136. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  14137. << EnclosingExpr->getSourceRange();
  14138. return true;
  14139. }
  14140. return FoundError;
  14141. }
  14142. // Look up the user-defined mapper given the mapper name and mapped type, and
  14143. // build a reference to it.
  14144. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  14145. CXXScopeSpec &MapperIdScopeSpec,
  14146. const DeclarationNameInfo &MapperId,
  14147. QualType Type,
  14148. Expr *UnresolvedMapper) {
  14149. if (MapperIdScopeSpec.isInvalid())
  14150. return ExprError();
  14151. // Get the actual type for the array type.
  14152. if (Type->isArrayType()) {
  14153. assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
  14154. Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
  14155. }
  14156. // Find all user-defined mappers with the given MapperId.
  14157. SmallVector<UnresolvedSet<8>, 4> Lookups;
  14158. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  14159. Lookup.suppressDiagnostics();
  14160. if (S) {
  14161. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  14162. NamedDecl *D = Lookup.getRepresentativeDecl();
  14163. while (S && !S->isDeclScope(D))
  14164. S = S->getParent();
  14165. if (S)
  14166. S = S->getParent();
  14167. Lookups.emplace_back();
  14168. Lookups.back().append(Lookup.begin(), Lookup.end());
  14169. Lookup.clear();
  14170. }
  14171. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  14172. // Extract the user-defined mappers with the given MapperId.
  14173. Lookups.push_back(UnresolvedSet<8>());
  14174. for (NamedDecl *D : ULE->decls()) {
  14175. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  14176. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  14177. Lookups.back().addDecl(DMD);
  14178. }
  14179. }
  14180. // Defer the lookup for dependent types. The results will be passed through
  14181. // UnresolvedMapper on instantiation.
  14182. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  14183. Type->isInstantiationDependentType() ||
  14184. Type->containsUnexpandedParameterPack() ||
  14185. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  14186. return !D->isInvalidDecl() &&
  14187. (D->getType()->isDependentType() ||
  14188. D->getType()->isInstantiationDependentType() ||
  14189. D->getType()->containsUnexpandedParameterPack());
  14190. })) {
  14191. UnresolvedSet<8> URS;
  14192. for (const UnresolvedSet<8> &Set : Lookups) {
  14193. if (Set.empty())
  14194. continue;
  14195. URS.append(Set.begin(), Set.end());
  14196. }
  14197. return UnresolvedLookupExpr::Create(
  14198. SemaRef.Context, /*NamingClass=*/nullptr,
  14199. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  14200. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  14201. }
  14202. SourceLocation Loc = MapperId.getLoc();
  14203. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14204. // The type must be of struct, union or class type in C and C++
  14205. if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
  14206. (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
  14207. SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
  14208. return ExprError();
  14209. }
  14210. // Perform argument dependent lookup.
  14211. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  14212. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  14213. // Return the first user-defined mapper with the desired type.
  14214. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  14215. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  14216. if (!D->isInvalidDecl() &&
  14217. SemaRef.Context.hasSameType(D->getType(), Type))
  14218. return D;
  14219. return nullptr;
  14220. }))
  14221. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  14222. // Find the first user-defined mapper with a type derived from the desired
  14223. // type.
  14224. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  14225. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  14226. if (!D->isInvalidDecl() &&
  14227. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  14228. !Type.isMoreQualifiedThan(D->getType()))
  14229. return D;
  14230. return nullptr;
  14231. })) {
  14232. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  14233. /*DetectVirtual=*/false);
  14234. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  14235. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  14236. VD->getType().getUnqualifiedType()))) {
  14237. if (SemaRef.CheckBaseClassAccess(
  14238. Loc, VD->getType(), Type, Paths.front(),
  14239. /*DiagID=*/0) != Sema::AR_inaccessible) {
  14240. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  14241. }
  14242. }
  14243. }
  14244. }
  14245. // Report error if a mapper is specified, but cannot be found.
  14246. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  14247. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  14248. << Type << MapperId.getName();
  14249. return ExprError();
  14250. }
  14251. return ExprEmpty();
  14252. }
  14253. namespace {
  14254. // Utility struct that gathers all the related lists associated with a mappable
  14255. // expression.
  14256. struct MappableVarListInfo {
  14257. // The list of expressions.
  14258. ArrayRef<Expr *> VarList;
  14259. // The list of processed expressions.
  14260. SmallVector<Expr *, 16> ProcessedVarList;
  14261. // The mappble components for each expression.
  14262. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  14263. // The base declaration of the variable.
  14264. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  14265. // The reference to the user-defined mapper associated with every expression.
  14266. SmallVector<Expr *, 16> UDMapperList;
  14267. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  14268. // We have a list of components and base declarations for each entry in the
  14269. // variable list.
  14270. VarComponents.reserve(VarList.size());
  14271. VarBaseDeclarations.reserve(VarList.size());
  14272. }
  14273. };
  14274. }
  14275. // Check the validity of the provided variable list for the provided clause kind
  14276. // \a CKind. In the check process the valid expressions, mappable expression
  14277. // components, variables, and user-defined mappers are extracted and used to
  14278. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  14279. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  14280. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  14281. static void checkMappableExpressionList(
  14282. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  14283. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  14284. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  14285. ArrayRef<Expr *> UnresolvedMappers,
  14286. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  14287. bool IsMapTypeImplicit = false) {
  14288. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  14289. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  14290. "Unexpected clause kind with mappable expressions!");
  14291. // If the identifier of user-defined mapper is not specified, it is "default".
  14292. // We do not change the actual name in this clause to distinguish whether a
  14293. // mapper is specified explicitly, i.e., it is not explicitly specified when
  14294. // MapperId.getName() is empty.
  14295. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  14296. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  14297. MapperId.setName(DeclNames.getIdentifier(
  14298. &SemaRef.getASTContext().Idents.get("default")));
  14299. }
  14300. // Iterators to find the current unresolved mapper expression.
  14301. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  14302. bool UpdateUMIt = false;
  14303. Expr *UnresolvedMapper = nullptr;
  14304. // Keep track of the mappable components and base declarations in this clause.
  14305. // Each entry in the list is going to have a list of components associated. We
  14306. // record each set of the components so that we can build the clause later on.
  14307. // In the end we should have the same amount of declarations and component
  14308. // lists.
  14309. for (Expr *RE : MVLI.VarList) {
  14310. assert(RE && "Null expr in omp to/from/map clause");
  14311. SourceLocation ELoc = RE->getExprLoc();
  14312. // Find the current unresolved mapper expression.
  14313. if (UpdateUMIt && UMIt != UMEnd) {
  14314. UMIt++;
  14315. assert(
  14316. UMIt != UMEnd &&
  14317. "Expect the size of UnresolvedMappers to match with that of VarList");
  14318. }
  14319. UpdateUMIt = true;
  14320. if (UMIt != UMEnd)
  14321. UnresolvedMapper = *UMIt;
  14322. const Expr *VE = RE->IgnoreParenLValueCasts();
  14323. if (VE->isValueDependent() || VE->isTypeDependent() ||
  14324. VE->isInstantiationDependent() ||
  14325. VE->containsUnexpandedParameterPack()) {
  14326. // Try to find the associated user-defined mapper.
  14327. ExprResult ER = buildUserDefinedMapperRef(
  14328. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14329. VE->getType().getCanonicalType(), UnresolvedMapper);
  14330. if (ER.isInvalid())
  14331. continue;
  14332. MVLI.UDMapperList.push_back(ER.get());
  14333. // We can only analyze this information once the missing information is
  14334. // resolved.
  14335. MVLI.ProcessedVarList.push_back(RE);
  14336. continue;
  14337. }
  14338. Expr *SimpleExpr = RE->IgnoreParenCasts();
  14339. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  14340. SemaRef.Diag(ELoc,
  14341. diag::err_omp_expected_named_var_member_or_array_expression)
  14342. << RE->getSourceRange();
  14343. continue;
  14344. }
  14345. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  14346. ValueDecl *CurDeclaration = nullptr;
  14347. // Obtain the array or member expression bases if required. Also, fill the
  14348. // components array with all the components identified in the process.
  14349. const Expr *BE = checkMapClauseExpressionBase(
  14350. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  14351. if (!BE)
  14352. continue;
  14353. assert(!CurComponents.empty() &&
  14354. "Invalid mappable expression information.");
  14355. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  14356. // Add store "this" pointer to class in DSAStackTy for future checking
  14357. DSAS->addMappedClassesQualTypes(TE->getType());
  14358. // Try to find the associated user-defined mapper.
  14359. ExprResult ER = buildUserDefinedMapperRef(
  14360. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14361. VE->getType().getCanonicalType(), UnresolvedMapper);
  14362. if (ER.isInvalid())
  14363. continue;
  14364. MVLI.UDMapperList.push_back(ER.get());
  14365. // Skip restriction checking for variable or field declarations
  14366. MVLI.ProcessedVarList.push_back(RE);
  14367. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14368. MVLI.VarComponents.back().append(CurComponents.begin(),
  14369. CurComponents.end());
  14370. MVLI.VarBaseDeclarations.push_back(nullptr);
  14371. continue;
  14372. }
  14373. // For the following checks, we rely on the base declaration which is
  14374. // expected to be associated with the last component. The declaration is
  14375. // expected to be a variable or a field (if 'this' is being mapped).
  14376. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  14377. assert(CurDeclaration && "Null decl on map clause.");
  14378. assert(
  14379. CurDeclaration->isCanonicalDecl() &&
  14380. "Expecting components to have associated only canonical declarations.");
  14381. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  14382. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  14383. assert((VD || FD) && "Only variables or fields are expected here!");
  14384. (void)FD;
  14385. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  14386. // threadprivate variables cannot appear in a map clause.
  14387. // OpenMP 4.5 [2.10.5, target update Construct]
  14388. // threadprivate variables cannot appear in a from clause.
  14389. if (VD && DSAS->isThreadPrivate(VD)) {
  14390. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14391. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  14392. << getOpenMPClauseName(CKind);
  14393. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  14394. continue;
  14395. }
  14396. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14397. // A list item cannot appear in both a map clause and a data-sharing
  14398. // attribute clause on the same construct.
  14399. // Check conflicts with other map clause expressions. We check the conflicts
  14400. // with the current construct separately from the enclosing data
  14401. // environment, because the restrictions are different. We only have to
  14402. // check conflicts across regions for the map clauses.
  14403. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14404. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  14405. break;
  14406. if (CKind == OMPC_map &&
  14407. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14408. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  14409. break;
  14410. // OpenMP 4.5 [2.10.5, target update Construct]
  14411. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  14412. // If the type of a list item is a reference to a type T then the type will
  14413. // be considered to be T for all purposes of this clause.
  14414. auto I = llvm::find_if(
  14415. CurComponents,
  14416. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  14417. return MC.getAssociatedDeclaration();
  14418. });
  14419. assert(I != CurComponents.end() && "Null decl on map clause.");
  14420. QualType Type =
  14421. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  14422. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  14423. // A list item in a to or from clause must have a mappable type.
  14424. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14425. // A list item must have a mappable type.
  14426. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  14427. DSAS, Type))
  14428. continue;
  14429. if (CKind == OMPC_map) {
  14430. // target enter data
  14431. // OpenMP [2.10.2, Restrictions, p. 99]
  14432. // A map-type must be specified in all map clauses and must be either
  14433. // to or alloc.
  14434. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  14435. if (DKind == OMPD_target_enter_data &&
  14436. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  14437. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14438. << (IsMapTypeImplicit ? 1 : 0)
  14439. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14440. << getOpenMPDirectiveName(DKind);
  14441. continue;
  14442. }
  14443. // target exit_data
  14444. // OpenMP [2.10.3, Restrictions, p. 102]
  14445. // A map-type must be specified in all map clauses and must be either
  14446. // from, release, or delete.
  14447. if (DKind == OMPD_target_exit_data &&
  14448. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  14449. MapType == OMPC_MAP_delete)) {
  14450. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14451. << (IsMapTypeImplicit ? 1 : 0)
  14452. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14453. << getOpenMPDirectiveName(DKind);
  14454. continue;
  14455. }
  14456. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  14457. // A list item cannot appear in both a map clause and a data-sharing
  14458. // attribute clause on the same construct
  14459. //
  14460. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  14461. // A list item cannot appear in both a map clause and a data-sharing
  14462. // attribute clause on the same construct unless the construct is a
  14463. // combined construct.
  14464. if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
  14465. isOpenMPTargetExecutionDirective(DKind)) ||
  14466. DKind == OMPD_target)) {
  14467. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14468. if (isOpenMPPrivate(DVar.CKind)) {
  14469. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  14470. << getOpenMPClauseName(DVar.CKind)
  14471. << getOpenMPClauseName(OMPC_map)
  14472. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  14473. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  14474. continue;
  14475. }
  14476. }
  14477. }
  14478. // Try to find the associated user-defined mapper.
  14479. ExprResult ER = buildUserDefinedMapperRef(
  14480. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14481. Type.getCanonicalType(), UnresolvedMapper);
  14482. if (ER.isInvalid())
  14483. continue;
  14484. MVLI.UDMapperList.push_back(ER.get());
  14485. // Save the current expression.
  14486. MVLI.ProcessedVarList.push_back(RE);
  14487. // Store the components in the stack so that they can be used to check
  14488. // against other clauses later on.
  14489. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  14490. /*WhereFoundClauseKind=*/OMPC_map);
  14491. // Save the components and declaration to create the clause. For purposes of
  14492. // the clause creation, any component list that has has base 'this' uses
  14493. // null as base declaration.
  14494. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14495. MVLI.VarComponents.back().append(CurComponents.begin(),
  14496. CurComponents.end());
  14497. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  14498. : CurDeclaration);
  14499. }
  14500. }
  14501. OMPClause *Sema::ActOnOpenMPMapClause(
  14502. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  14503. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  14504. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  14505. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  14506. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  14507. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  14508. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  14509. OMPC_MAP_MODIFIER_unknown,
  14510. OMPC_MAP_MODIFIER_unknown};
  14511. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  14512. // Process map-type-modifiers, flag errors for duplicate modifiers.
  14513. unsigned Count = 0;
  14514. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  14515. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  14516. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  14517. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  14518. continue;
  14519. }
  14520. assert(Count < OMPMapClause::NumberOfModifiers &&
  14521. "Modifiers exceed the allowed number of map type modifiers");
  14522. Modifiers[Count] = MapTypeModifiers[I];
  14523. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  14524. ++Count;
  14525. }
  14526. MappableVarListInfo MVLI(VarList);
  14527. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  14528. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  14529. MapType, IsMapTypeImplicit);
  14530. // We need to produce a map clause even if we don't have variables so that
  14531. // other diagnostics related with non-existing map clauses are accurate.
  14532. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  14533. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  14534. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  14535. MapperIdScopeSpec.getWithLocInContext(Context),
  14536. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  14537. }
  14538. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  14539. TypeResult ParsedType) {
  14540. assert(ParsedType.isUsable());
  14541. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  14542. if (ReductionType.isNull())
  14543. return QualType();
  14544. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  14545. // A type name in a declare reduction directive cannot be a function type, an
  14546. // array type, a reference type, or a type qualified with const, volatile or
  14547. // restrict.
  14548. if (ReductionType.hasQualifiers()) {
  14549. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  14550. return QualType();
  14551. }
  14552. if (ReductionType->isFunctionType()) {
  14553. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  14554. return QualType();
  14555. }
  14556. if (ReductionType->isReferenceType()) {
  14557. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  14558. return QualType();
  14559. }
  14560. if (ReductionType->isArrayType()) {
  14561. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  14562. return QualType();
  14563. }
  14564. return ReductionType;
  14565. }
  14566. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  14567. Scope *S, DeclContext *DC, DeclarationName Name,
  14568. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  14569. AccessSpecifier AS, Decl *PrevDeclInScope) {
  14570. SmallVector<Decl *, 8> Decls;
  14571. Decls.reserve(ReductionTypes.size());
  14572. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  14573. forRedeclarationInCurContext());
  14574. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  14575. // A reduction-identifier may not be re-declared in the current scope for the
  14576. // same type or for a type that is compatible according to the base language
  14577. // rules.
  14578. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14579. OMPDeclareReductionDecl *PrevDRD = nullptr;
  14580. bool InCompoundScope = true;
  14581. if (S != nullptr) {
  14582. // Find previous declaration with the same name not referenced in other
  14583. // declarations.
  14584. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14585. InCompoundScope =
  14586. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14587. LookupName(Lookup, S);
  14588. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14589. /*AllowInlineNamespace=*/false);
  14590. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  14591. LookupResult::Filter Filter = Lookup.makeFilter();
  14592. while (Filter.hasNext()) {
  14593. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  14594. if (InCompoundScope) {
  14595. auto I = UsedAsPrevious.find(PrevDecl);
  14596. if (I == UsedAsPrevious.end())
  14597. UsedAsPrevious[PrevDecl] = false;
  14598. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  14599. UsedAsPrevious[D] = true;
  14600. }
  14601. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14602. PrevDecl->getLocation();
  14603. }
  14604. Filter.done();
  14605. if (InCompoundScope) {
  14606. for (const auto &PrevData : UsedAsPrevious) {
  14607. if (!PrevData.second) {
  14608. PrevDRD = PrevData.first;
  14609. break;
  14610. }
  14611. }
  14612. }
  14613. } else if (PrevDeclInScope != nullptr) {
  14614. auto *PrevDRDInScope = PrevDRD =
  14615. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  14616. do {
  14617. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  14618. PrevDRDInScope->getLocation();
  14619. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  14620. } while (PrevDRDInScope != nullptr);
  14621. }
  14622. for (const auto &TyData : ReductionTypes) {
  14623. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  14624. bool Invalid = false;
  14625. if (I != PreviousRedeclTypes.end()) {
  14626. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  14627. << TyData.first;
  14628. Diag(I->second, diag::note_previous_definition);
  14629. Invalid = true;
  14630. }
  14631. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  14632. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  14633. Name, TyData.first, PrevDRD);
  14634. DC->addDecl(DRD);
  14635. DRD->setAccess(AS);
  14636. Decls.push_back(DRD);
  14637. if (Invalid)
  14638. DRD->setInvalidDecl();
  14639. else
  14640. PrevDRD = DRD;
  14641. }
  14642. return DeclGroupPtrTy::make(
  14643. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  14644. }
  14645. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  14646. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14647. // Enter new function scope.
  14648. PushFunctionScope();
  14649. setFunctionHasBranchProtectedScope();
  14650. getCurFunction()->setHasOMPDeclareReductionCombiner();
  14651. if (S != nullptr)
  14652. PushDeclContext(S, DRD);
  14653. else
  14654. CurContext = DRD;
  14655. PushExpressionEvaluationContext(
  14656. ExpressionEvaluationContext::PotentiallyEvaluated);
  14657. QualType ReductionType = DRD->getType();
  14658. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  14659. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  14660. // uses semantics of argument handles by value, but it should be passed by
  14661. // reference. C lang does not support references, so pass all parameters as
  14662. // pointers.
  14663. // Create 'T omp_in;' variable.
  14664. VarDecl *OmpInParm =
  14665. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  14666. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  14667. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  14668. // uses semantics of argument handles by value, but it should be passed by
  14669. // reference. C lang does not support references, so pass all parameters as
  14670. // pointers.
  14671. // Create 'T omp_out;' variable.
  14672. VarDecl *OmpOutParm =
  14673. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  14674. if (S != nullptr) {
  14675. PushOnScopeChains(OmpInParm, S);
  14676. PushOnScopeChains(OmpOutParm, S);
  14677. } else {
  14678. DRD->addDecl(OmpInParm);
  14679. DRD->addDecl(OmpOutParm);
  14680. }
  14681. Expr *InE =
  14682. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  14683. Expr *OutE =
  14684. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  14685. DRD->setCombinerData(InE, OutE);
  14686. }
  14687. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  14688. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14689. DiscardCleanupsInEvaluationContext();
  14690. PopExpressionEvaluationContext();
  14691. PopDeclContext();
  14692. PopFunctionScopeInfo();
  14693. if (Combiner != nullptr)
  14694. DRD->setCombiner(Combiner);
  14695. else
  14696. DRD->setInvalidDecl();
  14697. }
  14698. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  14699. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14700. // Enter new function scope.
  14701. PushFunctionScope();
  14702. setFunctionHasBranchProtectedScope();
  14703. if (S != nullptr)
  14704. PushDeclContext(S, DRD);
  14705. else
  14706. CurContext = DRD;
  14707. PushExpressionEvaluationContext(
  14708. ExpressionEvaluationContext::PotentiallyEvaluated);
  14709. QualType ReductionType = DRD->getType();
  14710. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  14711. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  14712. // uses semantics of argument handles by value, but it should be passed by
  14713. // reference. C lang does not support references, so pass all parameters as
  14714. // pointers.
  14715. // Create 'T omp_priv;' variable.
  14716. VarDecl *OmpPrivParm =
  14717. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  14718. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  14719. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  14720. // uses semantics of argument handles by value, but it should be passed by
  14721. // reference. C lang does not support references, so pass all parameters as
  14722. // pointers.
  14723. // Create 'T omp_orig;' variable.
  14724. VarDecl *OmpOrigParm =
  14725. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  14726. if (S != nullptr) {
  14727. PushOnScopeChains(OmpPrivParm, S);
  14728. PushOnScopeChains(OmpOrigParm, S);
  14729. } else {
  14730. DRD->addDecl(OmpPrivParm);
  14731. DRD->addDecl(OmpOrigParm);
  14732. }
  14733. Expr *OrigE =
  14734. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  14735. Expr *PrivE =
  14736. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  14737. DRD->setInitializerData(OrigE, PrivE);
  14738. return OmpPrivParm;
  14739. }
  14740. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  14741. VarDecl *OmpPrivParm) {
  14742. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14743. DiscardCleanupsInEvaluationContext();
  14744. PopExpressionEvaluationContext();
  14745. PopDeclContext();
  14746. PopFunctionScopeInfo();
  14747. if (Initializer != nullptr) {
  14748. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  14749. } else if (OmpPrivParm->hasInit()) {
  14750. DRD->setInitializer(OmpPrivParm->getInit(),
  14751. OmpPrivParm->isDirectInit()
  14752. ? OMPDeclareReductionDecl::DirectInit
  14753. : OMPDeclareReductionDecl::CopyInit);
  14754. } else {
  14755. DRD->setInvalidDecl();
  14756. }
  14757. }
  14758. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  14759. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  14760. for (Decl *D : DeclReductions.get()) {
  14761. if (IsValid) {
  14762. if (S)
  14763. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  14764. /*AddToContext=*/false);
  14765. } else {
  14766. D->setInvalidDecl();
  14767. }
  14768. }
  14769. return DeclReductions;
  14770. }
  14771. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  14772. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14773. QualType T = TInfo->getType();
  14774. if (D.isInvalidType())
  14775. return true;
  14776. if (getLangOpts().CPlusPlus) {
  14777. // Check that there are no default arguments (C++ only).
  14778. CheckExtraCXXDefaultArguments(D);
  14779. }
  14780. return CreateParsedType(T, TInfo);
  14781. }
  14782. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  14783. TypeResult ParsedType) {
  14784. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  14785. QualType MapperType = GetTypeFromParser(ParsedType.get());
  14786. assert(!MapperType.isNull() && "Expect valid mapper type");
  14787. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14788. // The type must be of struct, union or class type in C and C++
  14789. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  14790. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  14791. return QualType();
  14792. }
  14793. return MapperType;
  14794. }
  14795. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  14796. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  14797. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  14798. Decl *PrevDeclInScope) {
  14799. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  14800. forRedeclarationInCurContext());
  14801. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14802. // A mapper-identifier may not be redeclared in the current scope for the
  14803. // same type or for a type that is compatible according to the base language
  14804. // rules.
  14805. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14806. OMPDeclareMapperDecl *PrevDMD = nullptr;
  14807. bool InCompoundScope = true;
  14808. if (S != nullptr) {
  14809. // Find previous declaration with the same name not referenced in other
  14810. // declarations.
  14811. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14812. InCompoundScope =
  14813. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14814. LookupName(Lookup, S);
  14815. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14816. /*AllowInlineNamespace=*/false);
  14817. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  14818. LookupResult::Filter Filter = Lookup.makeFilter();
  14819. while (Filter.hasNext()) {
  14820. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  14821. if (InCompoundScope) {
  14822. auto I = UsedAsPrevious.find(PrevDecl);
  14823. if (I == UsedAsPrevious.end())
  14824. UsedAsPrevious[PrevDecl] = false;
  14825. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  14826. UsedAsPrevious[D] = true;
  14827. }
  14828. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14829. PrevDecl->getLocation();
  14830. }
  14831. Filter.done();
  14832. if (InCompoundScope) {
  14833. for (const auto &PrevData : UsedAsPrevious) {
  14834. if (!PrevData.second) {
  14835. PrevDMD = PrevData.first;
  14836. break;
  14837. }
  14838. }
  14839. }
  14840. } else if (PrevDeclInScope) {
  14841. auto *PrevDMDInScope = PrevDMD =
  14842. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  14843. do {
  14844. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  14845. PrevDMDInScope->getLocation();
  14846. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  14847. } while (PrevDMDInScope != nullptr);
  14848. }
  14849. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  14850. bool Invalid = false;
  14851. if (I != PreviousRedeclTypes.end()) {
  14852. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  14853. << MapperType << Name;
  14854. Diag(I->second, diag::note_previous_definition);
  14855. Invalid = true;
  14856. }
  14857. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  14858. MapperType, VN, PrevDMD);
  14859. DC->addDecl(DMD);
  14860. DMD->setAccess(AS);
  14861. if (Invalid)
  14862. DMD->setInvalidDecl();
  14863. // Enter new function scope.
  14864. PushFunctionScope();
  14865. setFunctionHasBranchProtectedScope();
  14866. CurContext = DMD;
  14867. return DMD;
  14868. }
  14869. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  14870. Scope *S,
  14871. QualType MapperType,
  14872. SourceLocation StartLoc,
  14873. DeclarationName VN) {
  14874. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  14875. if (S)
  14876. PushOnScopeChains(VD, S);
  14877. else
  14878. DMD->addDecl(VD);
  14879. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  14880. DMD->setMapperVarRef(MapperVarRefExpr);
  14881. }
  14882. Sema::DeclGroupPtrTy
  14883. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  14884. ArrayRef<OMPClause *> ClauseList) {
  14885. PopDeclContext();
  14886. PopFunctionScopeInfo();
  14887. if (D) {
  14888. if (S)
  14889. PushOnScopeChains(D, S, /*AddToContext=*/false);
  14890. D->CreateClauses(Context, ClauseList);
  14891. }
  14892. return DeclGroupPtrTy::make(DeclGroupRef(D));
  14893. }
  14894. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  14895. SourceLocation StartLoc,
  14896. SourceLocation LParenLoc,
  14897. SourceLocation EndLoc) {
  14898. Expr *ValExpr = NumTeams;
  14899. Stmt *HelperValStmt = nullptr;
  14900. // OpenMP [teams Constrcut, Restrictions]
  14901. // The num_teams expression must evaluate to a positive integer value.
  14902. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  14903. /*StrictlyPositive=*/true))
  14904. return nullptr;
  14905. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14906. OpenMPDirectiveKind CaptureRegion =
  14907. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  14908. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14909. ValExpr = MakeFullExpr(ValExpr).get();
  14910. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14911. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14912. HelperValStmt = buildPreInits(Context, Captures);
  14913. }
  14914. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  14915. StartLoc, LParenLoc, EndLoc);
  14916. }
  14917. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  14918. SourceLocation StartLoc,
  14919. SourceLocation LParenLoc,
  14920. SourceLocation EndLoc) {
  14921. Expr *ValExpr = ThreadLimit;
  14922. Stmt *HelperValStmt = nullptr;
  14923. // OpenMP [teams Constrcut, Restrictions]
  14924. // The thread_limit expression must evaluate to a positive integer value.
  14925. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  14926. /*StrictlyPositive=*/true))
  14927. return nullptr;
  14928. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14929. OpenMPDirectiveKind CaptureRegion =
  14930. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  14931. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14932. ValExpr = MakeFullExpr(ValExpr).get();
  14933. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14934. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14935. HelperValStmt = buildPreInits(Context, Captures);
  14936. }
  14937. return new (Context) OMPThreadLimitClause(
  14938. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  14939. }
  14940. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  14941. SourceLocation StartLoc,
  14942. SourceLocation LParenLoc,
  14943. SourceLocation EndLoc) {
  14944. Expr *ValExpr = Priority;
  14945. Stmt *HelperValStmt = nullptr;
  14946. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  14947. // OpenMP [2.9.1, task Constrcut]
  14948. // The priority-value is a non-negative numerical scalar expression.
  14949. if (!isNonNegativeIntegerValue(
  14950. ValExpr, *this, OMPC_priority,
  14951. /*StrictlyPositive=*/false, /*BuildCapture=*/true,
  14952. DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
  14953. return nullptr;
  14954. return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
  14955. StartLoc, LParenLoc, EndLoc);
  14956. }
  14957. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  14958. SourceLocation StartLoc,
  14959. SourceLocation LParenLoc,
  14960. SourceLocation EndLoc) {
  14961. Expr *ValExpr = Grainsize;
  14962. Stmt *HelperValStmt = nullptr;
  14963. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  14964. // OpenMP [2.9.2, taskloop Constrcut]
  14965. // The parameter of the grainsize clause must be a positive integer
  14966. // expression.
  14967. if (!isNonNegativeIntegerValue(
  14968. ValExpr, *this, OMPC_grainsize,
  14969. /*StrictlyPositive=*/true, /*BuildCapture=*/true,
  14970. DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
  14971. return nullptr;
  14972. return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
  14973. StartLoc, LParenLoc, EndLoc);
  14974. }
  14975. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  14976. SourceLocation StartLoc,
  14977. SourceLocation LParenLoc,
  14978. SourceLocation EndLoc) {
  14979. Expr *ValExpr = NumTasks;
  14980. Stmt *HelperValStmt = nullptr;
  14981. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  14982. // OpenMP [2.9.2, taskloop Constrcut]
  14983. // The parameter of the num_tasks clause must be a positive integer
  14984. // expression.
  14985. if (!isNonNegativeIntegerValue(
  14986. ValExpr, *this, OMPC_num_tasks,
  14987. /*StrictlyPositive=*/true, /*BuildCapture=*/true,
  14988. DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
  14989. return nullptr;
  14990. return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
  14991. StartLoc, LParenLoc, EndLoc);
  14992. }
  14993. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  14994. SourceLocation LParenLoc,
  14995. SourceLocation EndLoc) {
  14996. // OpenMP [2.13.2, critical construct, Description]
  14997. // ... where hint-expression is an integer constant expression that evaluates
  14998. // to a valid lock hint.
  14999. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  15000. if (HintExpr.isInvalid())
  15001. return nullptr;
  15002. return new (Context)
  15003. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  15004. }
  15005. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  15006. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  15007. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  15008. SourceLocation EndLoc) {
  15009. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  15010. std::string Values;
  15011. Values += "'";
  15012. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  15013. Values += "'";
  15014. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  15015. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  15016. return nullptr;
  15017. }
  15018. Expr *ValExpr = ChunkSize;
  15019. Stmt *HelperValStmt = nullptr;
  15020. if (ChunkSize) {
  15021. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  15022. !ChunkSize->isInstantiationDependent() &&
  15023. !ChunkSize->containsUnexpandedParameterPack()) {
  15024. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  15025. ExprResult Val =
  15026. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  15027. if (Val.isInvalid())
  15028. return nullptr;
  15029. ValExpr = Val.get();
  15030. // OpenMP [2.7.1, Restrictions]
  15031. // chunk_size must be a loop invariant integer expression with a positive
  15032. // value.
  15033. llvm::APSInt Result;
  15034. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  15035. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  15036. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  15037. << "dist_schedule" << ChunkSize->getSourceRange();
  15038. return nullptr;
  15039. }
  15040. } else if (getOpenMPCaptureRegionForClause(
  15041. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  15042. OMPD_unknown &&
  15043. !CurContext->isDependentContext()) {
  15044. ValExpr = MakeFullExpr(ValExpr).get();
  15045. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  15046. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  15047. HelperValStmt = buildPreInits(Context, Captures);
  15048. }
  15049. }
  15050. }
  15051. return new (Context)
  15052. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  15053. Kind, ValExpr, HelperValStmt);
  15054. }
  15055. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  15056. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  15057. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  15058. SourceLocation KindLoc, SourceLocation EndLoc) {
  15059. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  15060. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  15061. std::string Value;
  15062. SourceLocation Loc;
  15063. Value += "'";
  15064. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  15065. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  15066. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  15067. Loc = MLoc;
  15068. } else {
  15069. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  15070. OMPC_DEFAULTMAP_scalar);
  15071. Loc = KindLoc;
  15072. }
  15073. Value += "'";
  15074. Diag(Loc, diag::err_omp_unexpected_clause_value)
  15075. << Value << getOpenMPClauseName(OMPC_defaultmap);
  15076. return nullptr;
  15077. }
  15078. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  15079. return new (Context)
  15080. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  15081. }
  15082. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  15083. DeclContext *CurLexicalContext = getCurLexicalContext();
  15084. if (!CurLexicalContext->isFileContext() &&
  15085. !CurLexicalContext->isExternCContext() &&
  15086. !CurLexicalContext->isExternCXXContext() &&
  15087. !isa<CXXRecordDecl>(CurLexicalContext) &&
  15088. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  15089. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  15090. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  15091. Diag(Loc, diag::err_omp_region_not_file_context);
  15092. return false;
  15093. }
  15094. ++DeclareTargetNestingLevel;
  15095. return true;
  15096. }
  15097. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  15098. assert(DeclareTargetNestingLevel > 0 &&
  15099. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  15100. --DeclareTargetNestingLevel;
  15101. }
  15102. NamedDecl *
  15103. Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
  15104. const DeclarationNameInfo &Id,
  15105. NamedDeclSetType &SameDirectiveDecls) {
  15106. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  15107. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  15108. if (Lookup.isAmbiguous())
  15109. return nullptr;
  15110. Lookup.suppressDiagnostics();
  15111. if (!Lookup.isSingleResult()) {
  15112. VarOrFuncDeclFilterCCC CCC(*this);
  15113. if (TypoCorrection Corrected =
  15114. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  15115. CTK_ErrorRecovery)) {
  15116. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  15117. << Id.getName());
  15118. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  15119. return nullptr;
  15120. }
  15121. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  15122. return nullptr;
  15123. }
  15124. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  15125. if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
  15126. !isa<FunctionTemplateDecl>(ND)) {
  15127. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  15128. return nullptr;
  15129. }
  15130. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  15131. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  15132. return ND;
  15133. }
  15134. void Sema::ActOnOpenMPDeclareTargetName(
  15135. NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
  15136. OMPDeclareTargetDeclAttr::DevTypeTy DT) {
  15137. assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  15138. isa<FunctionTemplateDecl>(ND)) &&
  15139. "Expected variable, function or function template.");
  15140. // Diagnose marking after use as it may lead to incorrect diagnosis and
  15141. // codegen.
  15142. if (LangOpts.OpenMP >= 50 &&
  15143. (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
  15144. Diag(Loc, diag::warn_omp_declare_target_after_first_use);
  15145. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  15146. OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
  15147. if (DevTy.hasValue() && *DevTy != DT) {
  15148. Diag(Loc, diag::err_omp_device_type_mismatch)
  15149. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
  15150. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
  15151. return;
  15152. }
  15153. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  15154. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
  15155. if (!Res) {
  15156. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
  15157. SourceRange(Loc, Loc));
  15158. ND->addAttr(A);
  15159. if (ASTMutationListener *ML = Context.getASTMutationListener())
  15160. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  15161. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
  15162. } else if (*Res != MT) {
  15163. Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
  15164. }
  15165. }
  15166. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  15167. Sema &SemaRef, Decl *D) {
  15168. if (!D || !isa<VarDecl>(D))
  15169. return;
  15170. auto *VD = cast<VarDecl>(D);
  15171. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  15172. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  15173. if (SemaRef.LangOpts.OpenMP >= 50 &&
  15174. (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
  15175. SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
  15176. VD->hasGlobalStorage()) {
  15177. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  15178. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  15179. if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
  15180. // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
  15181. // If a lambda declaration and definition appears between a
  15182. // declare target directive and the matching end declare target
  15183. // directive, all variables that are captured by the lambda
  15184. // expression must also appear in a to clause.
  15185. SemaRef.Diag(VD->getLocation(),
  15186. diag::err_omp_lambda_capture_in_declare_target_not_to);
  15187. SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
  15188. << VD << 0 << SR;
  15189. return;
  15190. }
  15191. }
  15192. if (MapTy.hasValue())
  15193. return;
  15194. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  15195. SemaRef.Diag(SL, diag::note_used_here) << SR;
  15196. }
  15197. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  15198. Sema &SemaRef, DSAStackTy *Stack,
  15199. ValueDecl *VD) {
  15200. return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
  15201. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  15202. /*FullCheck=*/false);
  15203. }
  15204. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  15205. SourceLocation IdLoc) {
  15206. if (!D || D->isInvalidDecl())
  15207. return;
  15208. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  15209. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  15210. if (auto *VD = dyn_cast<VarDecl>(D)) {
  15211. // Only global variables can be marked as declare target.
  15212. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  15213. !VD->isStaticDataMember())
  15214. return;
  15215. // 2.10.6: threadprivate variable cannot appear in a declare target
  15216. // directive.
  15217. if (DSAStack->isThreadPrivate(VD)) {
  15218. Diag(SL, diag::err_omp_threadprivate_in_target);
  15219. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  15220. return;
  15221. }
  15222. }
  15223. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  15224. D = FTD->getTemplatedDecl();
  15225. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  15226. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  15227. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  15228. if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  15229. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  15230. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  15231. return;
  15232. }
  15233. // Mark the function as must be emitted for the device.
  15234. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  15235. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  15236. if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  15237. *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
  15238. checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
  15239. if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  15240. *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
  15241. checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
  15242. }
  15243. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  15244. // Problem if any with var declared with incomplete type will be reported
  15245. // as normal, so no need to check it here.
  15246. if ((E || !VD->getType()->isIncompleteType()) &&
  15247. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  15248. return;
  15249. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  15250. // Checking declaration inside declare target region.
  15251. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  15252. isa<FunctionTemplateDecl>(D)) {
  15253. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  15254. Context, OMPDeclareTargetDeclAttr::MT_To,
  15255. OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
  15256. D->addAttr(A);
  15257. if (ASTMutationListener *ML = Context.getASTMutationListener())
  15258. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  15259. }
  15260. return;
  15261. }
  15262. }
  15263. if (!E)
  15264. return;
  15265. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  15266. }
  15267. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  15268. CXXScopeSpec &MapperIdScopeSpec,
  15269. DeclarationNameInfo &MapperId,
  15270. const OMPVarListLocTy &Locs,
  15271. ArrayRef<Expr *> UnresolvedMappers) {
  15272. MappableVarListInfo MVLI(VarList);
  15273. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  15274. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  15275. if (MVLI.ProcessedVarList.empty())
  15276. return nullptr;
  15277. return OMPToClause::Create(
  15278. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  15279. MVLI.VarComponents, MVLI.UDMapperList,
  15280. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  15281. }
  15282. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  15283. CXXScopeSpec &MapperIdScopeSpec,
  15284. DeclarationNameInfo &MapperId,
  15285. const OMPVarListLocTy &Locs,
  15286. ArrayRef<Expr *> UnresolvedMappers) {
  15287. MappableVarListInfo MVLI(VarList);
  15288. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  15289. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  15290. if (MVLI.ProcessedVarList.empty())
  15291. return nullptr;
  15292. return OMPFromClause::Create(
  15293. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  15294. MVLI.VarComponents, MVLI.UDMapperList,
  15295. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  15296. }
  15297. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  15298. const OMPVarListLocTy &Locs) {
  15299. MappableVarListInfo MVLI(VarList);
  15300. SmallVector<Expr *, 8> PrivateCopies;
  15301. SmallVector<Expr *, 8> Inits;
  15302. for (Expr *RefExpr : VarList) {
  15303. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  15304. SourceLocation ELoc;
  15305. SourceRange ERange;
  15306. Expr *SimpleRefExpr = RefExpr;
  15307. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15308. if (Res.second) {
  15309. // It will be analyzed later.
  15310. MVLI.ProcessedVarList.push_back(RefExpr);
  15311. PrivateCopies.push_back(nullptr);
  15312. Inits.push_back(nullptr);
  15313. }
  15314. ValueDecl *D = Res.first;
  15315. if (!D)
  15316. continue;
  15317. QualType Type = D->getType();
  15318. Type = Type.getNonReferenceType().getUnqualifiedType();
  15319. auto *VD = dyn_cast<VarDecl>(D);
  15320. // Item should be a pointer or reference to pointer.
  15321. if (!Type->isPointerType()) {
  15322. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  15323. << 0 << RefExpr->getSourceRange();
  15324. continue;
  15325. }
  15326. // Build the private variable and the expression that refers to it.
  15327. auto VDPrivate =
  15328. buildVarDecl(*this, ELoc, Type, D->getName(),
  15329. D->hasAttrs() ? &D->getAttrs() : nullptr,
  15330. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  15331. if (VDPrivate->isInvalidDecl())
  15332. continue;
  15333. CurContext->addDecl(VDPrivate);
  15334. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  15335. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  15336. // Add temporary variable to initialize the private copy of the pointer.
  15337. VarDecl *VDInit =
  15338. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  15339. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  15340. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  15341. AddInitializerToDecl(VDPrivate,
  15342. DefaultLvalueConversion(VDInitRefExpr).get(),
  15343. /*DirectInit=*/false);
  15344. // If required, build a capture to implement the privatization initialized
  15345. // with the current list item value.
  15346. DeclRefExpr *Ref = nullptr;
  15347. if (!VD)
  15348. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  15349. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  15350. PrivateCopies.push_back(VDPrivateRefExpr);
  15351. Inits.push_back(VDInitRefExpr);
  15352. // We need to add a data sharing attribute for this variable to make sure it
  15353. // is correctly captured. A variable that shows up in a use_device_ptr has
  15354. // similar properties of a first private variable.
  15355. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  15356. // Create a mappable component for the list item. List items in this clause
  15357. // only need a component.
  15358. MVLI.VarBaseDeclarations.push_back(D);
  15359. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15360. MVLI.VarComponents.back().push_back(
  15361. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  15362. }
  15363. if (MVLI.ProcessedVarList.empty())
  15364. return nullptr;
  15365. return OMPUseDevicePtrClause::Create(
  15366. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  15367. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  15368. }
  15369. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  15370. const OMPVarListLocTy &Locs) {
  15371. MappableVarListInfo MVLI(VarList);
  15372. for (Expr *RefExpr : VarList) {
  15373. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  15374. SourceLocation ELoc;
  15375. SourceRange ERange;
  15376. Expr *SimpleRefExpr = RefExpr;
  15377. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15378. if (Res.second) {
  15379. // It will be analyzed later.
  15380. MVLI.ProcessedVarList.push_back(RefExpr);
  15381. }
  15382. ValueDecl *D = Res.first;
  15383. if (!D)
  15384. continue;
  15385. QualType Type = D->getType();
  15386. // item should be a pointer or array or reference to pointer or array
  15387. if (!Type.getNonReferenceType()->isPointerType() &&
  15388. !Type.getNonReferenceType()->isArrayType()) {
  15389. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  15390. << 0 << RefExpr->getSourceRange();
  15391. continue;
  15392. }
  15393. // Check if the declaration in the clause does not show up in any data
  15394. // sharing attribute.
  15395. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  15396. if (isOpenMPPrivate(DVar.CKind)) {
  15397. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  15398. << getOpenMPClauseName(DVar.CKind)
  15399. << getOpenMPClauseName(OMPC_is_device_ptr)
  15400. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  15401. reportOriginalDsa(*this, DSAStack, D, DVar);
  15402. continue;
  15403. }
  15404. const Expr *ConflictExpr;
  15405. if (DSAStack->checkMappableExprComponentListsForDecl(
  15406. D, /*CurrentRegionOnly=*/true,
  15407. [&ConflictExpr](
  15408. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  15409. OpenMPClauseKind) -> bool {
  15410. ConflictExpr = R.front().getAssociatedExpression();
  15411. return true;
  15412. })) {
  15413. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  15414. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  15415. << ConflictExpr->getSourceRange();
  15416. continue;
  15417. }
  15418. // Store the components in the stack so that they can be used to check
  15419. // against other clauses later on.
  15420. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  15421. DSAStack->addMappableExpressionComponents(
  15422. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  15423. // Record the expression we've just processed.
  15424. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  15425. // Create a mappable component for the list item. List items in this clause
  15426. // only need a component. We use a null declaration to signal fields in
  15427. // 'this'.
  15428. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  15429. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  15430. "Unexpected device pointer expression!");
  15431. MVLI.VarBaseDeclarations.push_back(
  15432. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  15433. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15434. MVLI.VarComponents.back().push_back(MC);
  15435. }
  15436. if (MVLI.ProcessedVarList.empty())
  15437. return nullptr;
  15438. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  15439. MVLI.VarBaseDeclarations,
  15440. MVLI.VarComponents);
  15441. }
  15442. OMPClause *Sema::ActOnOpenMPAllocateClause(
  15443. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  15444. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  15445. if (Allocator) {
  15446. // OpenMP [2.11.4 allocate Clause, Description]
  15447. // allocator is an expression of omp_allocator_handle_t type.
  15448. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  15449. return nullptr;
  15450. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  15451. if (AllocatorRes.isInvalid())
  15452. return nullptr;
  15453. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  15454. DSAStack->getOMPAllocatorHandleT(),
  15455. Sema::AA_Initializing,
  15456. /*AllowExplicit=*/true);
  15457. if (AllocatorRes.isInvalid())
  15458. return nullptr;
  15459. Allocator = AllocatorRes.get();
  15460. } else {
  15461. // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
  15462. // allocate clauses that appear on a target construct or on constructs in a
  15463. // target region must specify an allocator expression unless a requires
  15464. // directive with the dynamic_allocators clause is present in the same
  15465. // compilation unit.
  15466. if (LangOpts.OpenMPIsDevice &&
  15467. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  15468. targetDiag(StartLoc, diag::err_expected_allocator_expression);
  15469. }
  15470. // Analyze and build list of variables.
  15471. SmallVector<Expr *, 8> Vars;
  15472. for (Expr *RefExpr : VarList) {
  15473. assert(RefExpr && "NULL expr in OpenMP private clause.");
  15474. SourceLocation ELoc;
  15475. SourceRange ERange;
  15476. Expr *SimpleRefExpr = RefExpr;
  15477. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15478. if (Res.second) {
  15479. // It will be analyzed later.
  15480. Vars.push_back(RefExpr);
  15481. }
  15482. ValueDecl *D = Res.first;
  15483. if (!D)
  15484. continue;
  15485. auto *VD = dyn_cast<VarDecl>(D);
  15486. DeclRefExpr *Ref = nullptr;
  15487. if (!VD && !CurContext->isDependentContext())
  15488. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  15489. Vars.push_back((VD || CurContext->isDependentContext())
  15490. ? RefExpr->IgnoreParens()
  15491. : Ref);
  15492. }
  15493. if (Vars.empty())
  15494. return nullptr;
  15495. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  15496. ColonLoc, EndLoc, Vars);
  15497. }