SemaOpenMP.cpp 644 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254
  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. isOpenMPTeamsDirective(DVar.DKind)) {
  893. DVar.CKind = OMPC_shared;
  894. return DVar;
  895. }
  896. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  897. // in a Construct, implicitly determined, p.4]
  898. // In a task construct, if no default clause is present, a variable that in
  899. // the enclosing context is determined to be shared by all implicit tasks
  900. // bound to the current team is shared.
  901. if (isOpenMPTaskingDirective(DVar.DKind)) {
  902. DSAVarData DVarTemp;
  903. const_iterator I = Iter, E = end();
  904. do {
  905. ++I;
  906. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  907. // Referenced in a Construct, implicitly determined, p.6]
  908. // In a task construct, if no default clause is present, a variable
  909. // whose data-sharing attribute is not determined by the rules above is
  910. // firstprivate.
  911. DVarTemp = getDSA(I, D);
  912. if (DVarTemp.CKind != OMPC_shared) {
  913. DVar.RefExpr = nullptr;
  914. DVar.CKind = OMPC_firstprivate;
  915. return DVar;
  916. }
  917. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  918. DVar.CKind =
  919. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  920. return DVar;
  921. }
  922. }
  923. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  924. // in a Construct, implicitly determined, p.3]
  925. // For constructs other than task, if no default clause is present, these
  926. // variables inherit their data-sharing attributes from the enclosing
  927. // context.
  928. return getDSA(++Iter, D);
  929. }
  930. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  931. const Expr *NewDE) {
  932. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  933. D = getCanonicalDecl(D);
  934. SharingMapTy &StackElem = getTopOfStack();
  935. auto It = StackElem.AlignedMap.find(D);
  936. if (It == StackElem.AlignedMap.end()) {
  937. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  938. StackElem.AlignedMap[D] = NewDE;
  939. return nullptr;
  940. }
  941. assert(It->second && "Unexpected nullptr expr in the aligned map");
  942. return It->second;
  943. }
  944. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  945. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  946. D = getCanonicalDecl(D);
  947. SharingMapTy &StackElem = getTopOfStack();
  948. StackElem.LCVMap.try_emplace(
  949. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  950. }
  951. const DSAStackTy::LCDeclInfo
  952. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  953. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  954. D = getCanonicalDecl(D);
  955. const SharingMapTy &StackElem = getTopOfStack();
  956. auto It = StackElem.LCVMap.find(D);
  957. if (It != StackElem.LCVMap.end())
  958. return It->second;
  959. return {0, nullptr};
  960. }
  961. const DSAStackTy::LCDeclInfo
  962. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  963. const SharingMapTy *Parent = getSecondOnStackOrNull();
  964. assert(Parent && "Data-sharing attributes stack is empty");
  965. D = getCanonicalDecl(D);
  966. auto It = Parent->LCVMap.find(D);
  967. if (It != Parent->LCVMap.end())
  968. return It->second;
  969. return {0, nullptr};
  970. }
  971. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  972. const SharingMapTy *Parent = getSecondOnStackOrNull();
  973. assert(Parent && "Data-sharing attributes stack is empty");
  974. if (Parent->LCVMap.size() < I)
  975. return nullptr;
  976. for (const auto &Pair : Parent->LCVMap)
  977. if (Pair.second.first == I)
  978. return Pair.first;
  979. return nullptr;
  980. }
  981. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  982. DeclRefExpr *PrivateCopy) {
  983. D = getCanonicalDecl(D);
  984. if (A == OMPC_threadprivate) {
  985. DSAInfo &Data = Threadprivates[D];
  986. Data.Attributes = A;
  987. Data.RefExpr.setPointer(E);
  988. Data.PrivateCopy = nullptr;
  989. } else {
  990. DSAInfo &Data = getTopOfStack().SharingMap[D];
  991. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  992. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  993. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  994. (isLoopControlVariable(D).first && A == OMPC_private));
  995. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  996. Data.RefExpr.setInt(/*IntVal=*/true);
  997. return;
  998. }
  999. const bool IsLastprivate =
  1000. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  1001. Data.Attributes = A;
  1002. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  1003. Data.PrivateCopy = PrivateCopy;
  1004. if (PrivateCopy) {
  1005. DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
  1006. Data.Attributes = A;
  1007. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  1008. Data.PrivateCopy = nullptr;
  1009. }
  1010. }
  1011. }
  1012. /// Build a variable declaration for OpenMP loop iteration variable.
  1013. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  1014. StringRef Name, const AttrVec *Attrs = nullptr,
  1015. DeclRefExpr *OrigRef = nullptr) {
  1016. DeclContext *DC = SemaRef.CurContext;
  1017. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1018. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1019. auto *Decl =
  1020. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  1021. if (Attrs) {
  1022. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  1023. I != E; ++I)
  1024. Decl->addAttr(*I);
  1025. }
  1026. Decl->setImplicit();
  1027. if (OrigRef) {
  1028. Decl->addAttr(
  1029. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  1030. }
  1031. return Decl;
  1032. }
  1033. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  1034. SourceLocation Loc,
  1035. bool RefersToCapture = false) {
  1036. D->setReferenced();
  1037. D->markUsed(S.Context);
  1038. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  1039. SourceLocation(), D, RefersToCapture, Loc, Ty,
  1040. VK_LValue);
  1041. }
  1042. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1043. BinaryOperatorKind BOK) {
  1044. D = getCanonicalDecl(D);
  1045. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1046. assert(
  1047. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1048. "Additional reduction info may be specified only for reduction items.");
  1049. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1050. assert(ReductionData.ReductionRange.isInvalid() &&
  1051. getTopOfStack().Directive == OMPD_taskgroup &&
  1052. "Additional reduction info may be specified only once for reduction "
  1053. "items.");
  1054. ReductionData.set(BOK, SR);
  1055. Expr *&TaskgroupReductionRef =
  1056. getTopOfStack().TaskgroupReductionRef;
  1057. if (!TaskgroupReductionRef) {
  1058. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1059. SemaRef.Context.VoidPtrTy, ".task_red.");
  1060. TaskgroupReductionRef =
  1061. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1062. }
  1063. }
  1064. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1065. const Expr *ReductionRef) {
  1066. D = getCanonicalDecl(D);
  1067. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1068. assert(
  1069. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1070. "Additional reduction info may be specified only for reduction items.");
  1071. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1072. assert(ReductionData.ReductionRange.isInvalid() &&
  1073. getTopOfStack().Directive == OMPD_taskgroup &&
  1074. "Additional reduction info may be specified only once for reduction "
  1075. "items.");
  1076. ReductionData.set(ReductionRef, SR);
  1077. Expr *&TaskgroupReductionRef =
  1078. getTopOfStack().TaskgroupReductionRef;
  1079. if (!TaskgroupReductionRef) {
  1080. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1081. SemaRef.Context.VoidPtrTy, ".task_red.");
  1082. TaskgroupReductionRef =
  1083. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1084. }
  1085. }
  1086. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1087. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  1088. Expr *&TaskgroupDescriptor) const {
  1089. D = getCanonicalDecl(D);
  1090. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1091. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1092. const DSAInfo &Data = I->SharingMap.lookup(D);
  1093. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1094. continue;
  1095. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1096. if (!ReductionData.ReductionOp ||
  1097. ReductionData.ReductionOp.is<const Expr *>())
  1098. return DSAVarData();
  1099. SR = ReductionData.ReductionRange;
  1100. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  1101. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1102. "expression for the descriptor is not "
  1103. "set.");
  1104. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1105. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1106. Data.PrivateCopy, I->DefaultAttrLoc);
  1107. }
  1108. return DSAVarData();
  1109. }
  1110. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1111. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  1112. Expr *&TaskgroupDescriptor) const {
  1113. D = getCanonicalDecl(D);
  1114. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1115. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1116. const DSAInfo &Data = I->SharingMap.lookup(D);
  1117. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1118. continue;
  1119. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1120. if (!ReductionData.ReductionOp ||
  1121. !ReductionData.ReductionOp.is<const Expr *>())
  1122. return DSAVarData();
  1123. SR = ReductionData.ReductionRange;
  1124. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1125. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1126. "expression for the descriptor is not "
  1127. "set.");
  1128. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1129. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1130. Data.PrivateCopy, I->DefaultAttrLoc);
  1131. }
  1132. return DSAVarData();
  1133. }
  1134. bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
  1135. D = D->getCanonicalDecl();
  1136. for (const_iterator E = end(); I != E; ++I) {
  1137. if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
  1138. isOpenMPTargetExecutionDirective(I->Directive)) {
  1139. Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  1140. Scope *CurScope = getCurScope();
  1141. while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
  1142. CurScope = CurScope->getParent();
  1143. return CurScope != TopScope;
  1144. }
  1145. }
  1146. return false;
  1147. }
  1148. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1149. bool AcceptIfMutable = true,
  1150. bool *IsClassType = nullptr) {
  1151. ASTContext &Context = SemaRef.getASTContext();
  1152. Type = Type.getNonReferenceType().getCanonicalType();
  1153. bool IsConstant = Type.isConstant(Context);
  1154. Type = Context.getBaseElementType(Type);
  1155. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1156. ? Type->getAsCXXRecordDecl()
  1157. : nullptr;
  1158. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1159. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1160. RD = CTD->getTemplatedDecl();
  1161. if (IsClassType)
  1162. *IsClassType = RD;
  1163. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1164. RD->hasDefinition() && RD->hasMutableFields());
  1165. }
  1166. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1167. QualType Type, OpenMPClauseKind CKind,
  1168. SourceLocation ELoc,
  1169. bool AcceptIfMutable = true,
  1170. bool ListItemNotVar = false) {
  1171. ASTContext &Context = SemaRef.getASTContext();
  1172. bool IsClassType;
  1173. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1174. unsigned Diag = ListItemNotVar
  1175. ? diag::err_omp_const_list_item
  1176. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1177. : diag::err_omp_const_variable;
  1178. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1179. if (!ListItemNotVar && D) {
  1180. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1181. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1182. VarDecl::DeclarationOnly;
  1183. SemaRef.Diag(D->getLocation(),
  1184. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1185. << D;
  1186. }
  1187. return true;
  1188. }
  1189. return false;
  1190. }
  1191. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1192. bool FromParent) {
  1193. D = getCanonicalDecl(D);
  1194. DSAVarData DVar;
  1195. auto *VD = dyn_cast<VarDecl>(D);
  1196. auto TI = Threadprivates.find(D);
  1197. if (TI != Threadprivates.end()) {
  1198. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1199. DVar.CKind = OMPC_threadprivate;
  1200. return DVar;
  1201. }
  1202. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1203. DVar.RefExpr = buildDeclRefExpr(
  1204. SemaRef, VD, D->getType().getNonReferenceType(),
  1205. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1206. DVar.CKind = OMPC_threadprivate;
  1207. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1208. return DVar;
  1209. }
  1210. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1211. // in a Construct, C/C++, predetermined, p.1]
  1212. // Variables appearing in threadprivate directives are threadprivate.
  1213. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1214. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1215. SemaRef.getLangOpts().OpenMPUseTLS &&
  1216. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1217. (VD && VD->getStorageClass() == SC_Register &&
  1218. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1219. DVar.RefExpr = buildDeclRefExpr(
  1220. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1221. DVar.CKind = OMPC_threadprivate;
  1222. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1223. return DVar;
  1224. }
  1225. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1226. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1227. !isLoopControlVariable(D).first) {
  1228. const_iterator IterTarget =
  1229. std::find_if(begin(), end(), [](const SharingMapTy &Data) {
  1230. return isOpenMPTargetExecutionDirective(Data.Directive);
  1231. });
  1232. if (IterTarget != end()) {
  1233. const_iterator ParentIterTarget = IterTarget + 1;
  1234. for (const_iterator Iter = begin();
  1235. Iter != ParentIterTarget; ++Iter) {
  1236. if (isOpenMPLocal(VD, Iter)) {
  1237. DVar.RefExpr =
  1238. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1239. D->getLocation());
  1240. DVar.CKind = OMPC_threadprivate;
  1241. return DVar;
  1242. }
  1243. }
  1244. if (!isClauseParsingMode() || IterTarget != begin()) {
  1245. auto DSAIter = IterTarget->SharingMap.find(D);
  1246. if (DSAIter != IterTarget->SharingMap.end() &&
  1247. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1248. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1249. DVar.CKind = OMPC_threadprivate;
  1250. return DVar;
  1251. }
  1252. const_iterator End = end();
  1253. if (!SemaRef.isOpenMPCapturedByRef(
  1254. D, std::distance(ParentIterTarget, End),
  1255. /*OpenMPCaptureLevel=*/0)) {
  1256. DVar.RefExpr =
  1257. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1258. IterTarget->ConstructLoc);
  1259. DVar.CKind = OMPC_threadprivate;
  1260. return DVar;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. if (isStackEmpty())
  1266. // Not in OpenMP execution region and top scope was already checked.
  1267. return DVar;
  1268. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1269. // in a Construct, C/C++, predetermined, p.4]
  1270. // Static data members are shared.
  1271. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1272. // in a Construct, C/C++, predetermined, p.7]
  1273. // Variables with static storage duration that are declared in a scope
  1274. // inside the construct are shared.
  1275. if (VD && VD->isStaticDataMember()) {
  1276. // Check for explicitly specified attributes.
  1277. const_iterator I = begin();
  1278. const_iterator EndI = end();
  1279. if (FromParent && I != EndI)
  1280. ++I;
  1281. auto It = I->SharingMap.find(D);
  1282. if (It != I->SharingMap.end()) {
  1283. const DSAInfo &Data = It->getSecond();
  1284. DVar.RefExpr = Data.RefExpr.getPointer();
  1285. DVar.PrivateCopy = Data.PrivateCopy;
  1286. DVar.CKind = Data.Attributes;
  1287. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1288. DVar.DKind = I->Directive;
  1289. return DVar;
  1290. }
  1291. DVar.CKind = OMPC_shared;
  1292. return DVar;
  1293. }
  1294. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1295. // The predetermined shared attribute for const-qualified types having no
  1296. // mutable members was removed after OpenMP 3.1.
  1297. if (SemaRef.LangOpts.OpenMP <= 31) {
  1298. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1299. // in a Construct, C/C++, predetermined, p.6]
  1300. // Variables with const qualified type having no mutable member are
  1301. // shared.
  1302. if (isConstNotMutableType(SemaRef, D->getType())) {
  1303. // Variables with const-qualified type having no mutable member may be
  1304. // listed in a firstprivate clause, even if they are static data members.
  1305. DSAVarData DVarTemp = hasInnermostDSA(
  1306. D,
  1307. [](OpenMPClauseKind C) {
  1308. return C == OMPC_firstprivate || C == OMPC_shared;
  1309. },
  1310. MatchesAlways, FromParent);
  1311. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1312. return DVarTemp;
  1313. DVar.CKind = OMPC_shared;
  1314. return DVar;
  1315. }
  1316. }
  1317. // Explicitly specified attributes and local variables with predetermined
  1318. // attributes.
  1319. const_iterator I = begin();
  1320. const_iterator EndI = end();
  1321. if (FromParent && I != EndI)
  1322. ++I;
  1323. auto It = I->SharingMap.find(D);
  1324. if (It != I->SharingMap.end()) {
  1325. const DSAInfo &Data = It->getSecond();
  1326. DVar.RefExpr = Data.RefExpr.getPointer();
  1327. DVar.PrivateCopy = Data.PrivateCopy;
  1328. DVar.CKind = Data.Attributes;
  1329. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1330. DVar.DKind = I->Directive;
  1331. }
  1332. return DVar;
  1333. }
  1334. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1335. bool FromParent) const {
  1336. if (isStackEmpty()) {
  1337. const_iterator I;
  1338. return getDSA(I, D);
  1339. }
  1340. D = getCanonicalDecl(D);
  1341. const_iterator StartI = begin();
  1342. const_iterator EndI = end();
  1343. if (FromParent && StartI != EndI)
  1344. ++StartI;
  1345. return getDSA(StartI, D);
  1346. }
  1347. const DSAStackTy::DSAVarData
  1348. DSAStackTy::hasDSA(ValueDecl *D,
  1349. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1350. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1351. bool FromParent) const {
  1352. if (isStackEmpty())
  1353. return {};
  1354. D = getCanonicalDecl(D);
  1355. const_iterator I = begin();
  1356. const_iterator EndI = end();
  1357. if (FromParent && I != EndI)
  1358. ++I;
  1359. for (; I != EndI; ++I) {
  1360. if (!DPred(I->Directive) &&
  1361. !isImplicitOrExplicitTaskingRegion(I->Directive))
  1362. continue;
  1363. const_iterator NewI = I;
  1364. DSAVarData DVar = getDSA(NewI, D);
  1365. if (I == NewI && CPred(DVar.CKind))
  1366. return DVar;
  1367. }
  1368. return {};
  1369. }
  1370. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1371. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1372. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1373. bool FromParent) const {
  1374. if (isStackEmpty())
  1375. return {};
  1376. D = getCanonicalDecl(D);
  1377. const_iterator StartI = begin();
  1378. const_iterator EndI = end();
  1379. if (FromParent && StartI != EndI)
  1380. ++StartI;
  1381. if (StartI == EndI || !DPred(StartI->Directive))
  1382. return {};
  1383. const_iterator NewI = StartI;
  1384. DSAVarData DVar = getDSA(NewI, D);
  1385. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1386. }
  1387. bool DSAStackTy::hasExplicitDSA(
  1388. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1389. unsigned Level, bool NotLastprivate) const {
  1390. if (getStackSize() <= Level)
  1391. return false;
  1392. D = getCanonicalDecl(D);
  1393. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1394. auto I = StackElem.SharingMap.find(D);
  1395. if (I != StackElem.SharingMap.end() &&
  1396. I->getSecond().RefExpr.getPointer() &&
  1397. CPred(I->getSecond().Attributes) &&
  1398. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1399. return true;
  1400. // Check predetermined rules for the loop control variables.
  1401. auto LI = StackElem.LCVMap.find(D);
  1402. if (LI != StackElem.LCVMap.end())
  1403. return CPred(OMPC_private);
  1404. return false;
  1405. }
  1406. bool DSAStackTy::hasExplicitDirective(
  1407. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1408. unsigned Level) const {
  1409. if (getStackSize() <= Level)
  1410. return false;
  1411. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1412. return DPred(StackElem.Directive);
  1413. }
  1414. bool DSAStackTy::hasDirective(
  1415. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1416. const DeclarationNameInfo &, SourceLocation)>
  1417. DPred,
  1418. bool FromParent) const {
  1419. // We look only in the enclosing region.
  1420. size_t Skip = FromParent ? 2 : 1;
  1421. for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
  1422. I != E; ++I) {
  1423. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1424. return true;
  1425. }
  1426. return false;
  1427. }
  1428. void Sema::InitDataSharingAttributesStack() {
  1429. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1430. }
  1431. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1432. void Sema::pushOpenMPFunctionRegion() {
  1433. DSAStack->pushFunction();
  1434. }
  1435. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1436. DSAStack->popFunction(OldFSI);
  1437. }
  1438. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1439. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1440. "Expected OpenMP device compilation.");
  1441. return !S.isInOpenMPTargetExecutionDirective() &&
  1442. !S.isInOpenMPDeclareTargetContext();
  1443. }
  1444. namespace {
  1445. /// Status of the function emission on the host/device.
  1446. enum class FunctionEmissionStatus {
  1447. Emitted,
  1448. Discarded,
  1449. Unknown,
  1450. };
  1451. } // anonymous namespace
  1452. /// Do we know that we will eventually codegen the given function?
  1453. static FunctionEmissionStatus isKnownDeviceEmitted(Sema &S, FunctionDecl *FD) {
  1454. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1455. "Expected OpenMP device compilation.");
  1456. // Templates are emitted when they're instantiated.
  1457. if (FD->isDependentContext())
  1458. return FunctionEmissionStatus::Discarded;
  1459. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1460. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  1461. if (DevTy.hasValue())
  1462. return (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  1463. ? FunctionEmissionStatus::Discarded
  1464. : FunctionEmissionStatus::Emitted;
  1465. // Otherwise, the function is known-emitted if it's in our set of
  1466. // known-emitted functions.
  1467. return (S.DeviceKnownEmittedFns.count(FD) > 0)
  1468. ? FunctionEmissionStatus::Emitted
  1469. : FunctionEmissionStatus::Unknown;
  1470. }
  1471. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1472. unsigned DiagID) {
  1473. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1474. "Expected OpenMP device compilation.");
  1475. FunctionEmissionStatus FES =
  1476. isKnownDeviceEmitted(*this, getCurFunctionDecl());
  1477. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1478. switch (FES) {
  1479. case FunctionEmissionStatus::Emitted:
  1480. Kind = DeviceDiagBuilder::K_Immediate;
  1481. break;
  1482. case FunctionEmissionStatus::Unknown:
  1483. Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
  1484. : DeviceDiagBuilder::K_Immediate;
  1485. break;
  1486. case FunctionEmissionStatus::Discarded:
  1487. Kind = DeviceDiagBuilder::K_Nop;
  1488. break;
  1489. }
  1490. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1491. }
  1492. /// Do we know that we will eventually codegen the given function?
  1493. static FunctionEmissionStatus isKnownHostEmitted(Sema &S, FunctionDecl *FD) {
  1494. assert(S.LangOpts.OpenMP && !S.LangOpts.OpenMPIsDevice &&
  1495. "Expected OpenMP host compilation.");
  1496. // In OpenMP 4.5 all the functions are host functions.
  1497. if (S.LangOpts.OpenMP <= 45)
  1498. return FunctionEmissionStatus::Emitted;
  1499. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1500. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  1501. if (DevTy.hasValue())
  1502. return (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  1503. ? FunctionEmissionStatus::Discarded
  1504. : FunctionEmissionStatus::Emitted;
  1505. // Otherwise, the function is known-emitted if it's in our set of
  1506. // known-emitted functions.
  1507. return (S.DeviceKnownEmittedFns.count(FD) > 0)
  1508. ? FunctionEmissionStatus::Emitted
  1509. : FunctionEmissionStatus::Unknown;
  1510. }
  1511. Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
  1512. unsigned DiagID) {
  1513. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1514. "Expected OpenMP host compilation.");
  1515. FunctionEmissionStatus FES =
  1516. isKnownHostEmitted(*this, getCurFunctionDecl());
  1517. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1518. switch (FES) {
  1519. case FunctionEmissionStatus::Emitted:
  1520. Kind = DeviceDiagBuilder::K_Immediate;
  1521. break;
  1522. case FunctionEmissionStatus::Unknown:
  1523. Kind = DeviceDiagBuilder::K_Deferred;
  1524. break;
  1525. case FunctionEmissionStatus::Discarded:
  1526. Kind = DeviceDiagBuilder::K_Nop;
  1527. break;
  1528. }
  1529. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1530. }
  1531. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
  1532. bool CheckForDelayedContext) {
  1533. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1534. "Expected OpenMP device compilation.");
  1535. assert(Callee && "Callee may not be null.");
  1536. Callee = Callee->getMostRecentDecl();
  1537. FunctionDecl *Caller = getCurFunctionDecl();
  1538. // host only function are not available on the device.
  1539. if (Caller &&
  1540. (isKnownDeviceEmitted(*this, Caller) == FunctionEmissionStatus::Emitted ||
  1541. (!isOpenMPDeviceDelayedContext(*this) &&
  1542. isKnownDeviceEmitted(*this, Caller) ==
  1543. FunctionEmissionStatus::Unknown)) &&
  1544. isKnownDeviceEmitted(*this, Callee) ==
  1545. FunctionEmissionStatus::Discarded) {
  1546. StringRef HostDevTy =
  1547. getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1548. Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
  1549. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1550. diag::note_omp_marked_device_type_here)
  1551. << HostDevTy;
  1552. return;
  1553. }
  1554. // If the caller is known-emitted, mark the callee as known-emitted.
  1555. // Otherwise, mark the call in our call graph so we can traverse it later.
  1556. if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
  1557. (!Caller && !CheckForDelayedContext) ||
  1558. (Caller &&
  1559. isKnownDeviceEmitted(*this, Caller) == FunctionEmissionStatus::Emitted))
  1560. markKnownEmitted(*this, Caller, Callee, Loc,
  1561. [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
  1562. return CheckForDelayedContext &&
  1563. isKnownDeviceEmitted(S, FD) ==
  1564. FunctionEmissionStatus::Emitted;
  1565. });
  1566. else if (Caller)
  1567. DeviceCallGraph[Caller].insert({Callee, Loc});
  1568. }
  1569. void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
  1570. bool CheckCaller) {
  1571. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1572. "Expected OpenMP host compilation.");
  1573. assert(Callee && "Callee may not be null.");
  1574. Callee = Callee->getMostRecentDecl();
  1575. FunctionDecl *Caller = getCurFunctionDecl();
  1576. // device only function are not available on the host.
  1577. if (Caller &&
  1578. isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted &&
  1579. isKnownHostEmitted(*this, Callee) == FunctionEmissionStatus::Discarded) {
  1580. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1581. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1582. Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
  1583. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1584. diag::note_omp_marked_device_type_here)
  1585. << NoHostDevTy;
  1586. return;
  1587. }
  1588. // If the caller is known-emitted, mark the callee as known-emitted.
  1589. // Otherwise, mark the call in our call graph so we can traverse it later.
  1590. if ((!CheckCaller && !Caller) ||
  1591. (Caller &&
  1592. isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted))
  1593. markKnownEmitted(
  1594. *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
  1595. return CheckCaller &&
  1596. isKnownHostEmitted(S, FD) == FunctionEmissionStatus::Emitted;
  1597. });
  1598. else if (Caller)
  1599. DeviceCallGraph[Caller].insert({Callee, Loc});
  1600. }
  1601. void Sema::checkOpenMPDeviceExpr(const Expr *E) {
  1602. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1603. "OpenMP device compilation mode is expected.");
  1604. QualType Ty = E->getType();
  1605. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1606. ((Ty->isFloat128Type() ||
  1607. (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
  1608. !Context.getTargetInfo().hasFloat128Type()) ||
  1609. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1610. !Context.getTargetInfo().hasInt128Type()))
  1611. targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
  1612. << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
  1613. << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
  1614. }
  1615. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
  1616. unsigned OpenMPCaptureLevel) const {
  1617. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1618. ASTContext &Ctx = getASTContext();
  1619. bool IsByRef = true;
  1620. // Find the directive that is associated with the provided scope.
  1621. D = cast<ValueDecl>(D->getCanonicalDecl());
  1622. QualType Ty = D->getType();
  1623. bool IsVariableUsedInMapClause = false;
  1624. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1625. // This table summarizes how a given variable should be passed to the device
  1626. // given its type and the clauses where it appears. This table is based on
  1627. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1628. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1629. //
  1630. // =========================================================================
  1631. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1632. // | |(tofrom:scalar)| | pvt | | | |
  1633. // =========================================================================
  1634. // | scl | | | | - | | bycopy|
  1635. // | scl | | - | x | - | - | bycopy|
  1636. // | scl | | x | - | - | - | null |
  1637. // | scl | x | | | - | | byref |
  1638. // | scl | x | - | x | - | - | bycopy|
  1639. // | scl | x | x | - | - | - | null |
  1640. // | scl | | - | - | - | x | byref |
  1641. // | scl | x | - | - | - | x | byref |
  1642. //
  1643. // | agg | n.a. | | | - | | byref |
  1644. // | agg | n.a. | - | x | - | - | byref |
  1645. // | agg | n.a. | x | - | - | - | null |
  1646. // | agg | n.a. | - | - | - | x | byref |
  1647. // | agg | n.a. | - | - | - | x[] | byref |
  1648. //
  1649. // | ptr | n.a. | | | - | | bycopy|
  1650. // | ptr | n.a. | - | x | - | - | bycopy|
  1651. // | ptr | n.a. | x | - | - | - | null |
  1652. // | ptr | n.a. | - | - | - | x | byref |
  1653. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1654. // | ptr | n.a. | - | - | x | | bycopy|
  1655. // | ptr | n.a. | - | - | x | x | bycopy|
  1656. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1657. // =========================================================================
  1658. // Legend:
  1659. // scl - scalar
  1660. // ptr - pointer
  1661. // agg - aggregate
  1662. // x - applies
  1663. // - - invalid in this combination
  1664. // [] - mapped with an array section
  1665. // byref - should be mapped by reference
  1666. // byval - should be mapped by value
  1667. // null - initialize a local variable to null on the device
  1668. //
  1669. // Observations:
  1670. // - All scalar declarations that show up in a map clause have to be passed
  1671. // by reference, because they may have been mapped in the enclosing data
  1672. // environment.
  1673. // - If the scalar value does not fit the size of uintptr, it has to be
  1674. // passed by reference, regardless the result in the table above.
  1675. // - For pointers mapped by value that have either an implicit map or an
  1676. // array section, the runtime library may pass the NULL value to the
  1677. // device instead of the value passed to it by the compiler.
  1678. if (Ty->isReferenceType())
  1679. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1680. // Locate map clauses and see if the variable being captured is referred to
  1681. // in any of those clauses. Here we only care about variables, not fields,
  1682. // because fields are part of aggregates.
  1683. bool IsVariableAssociatedWithSection = false;
  1684. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1685. D, Level,
  1686. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1687. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1688. MapExprComponents,
  1689. OpenMPClauseKind WhereFoundClauseKind) {
  1690. // Only the map clause information influences how a variable is
  1691. // captured. E.g. is_device_ptr does not require changing the default
  1692. // behavior.
  1693. if (WhereFoundClauseKind != OMPC_map)
  1694. return false;
  1695. auto EI = MapExprComponents.rbegin();
  1696. auto EE = MapExprComponents.rend();
  1697. assert(EI != EE && "Invalid map expression!");
  1698. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1699. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1700. ++EI;
  1701. if (EI == EE)
  1702. return false;
  1703. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1704. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1705. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1706. IsVariableAssociatedWithSection = true;
  1707. // There is nothing more we need to know about this variable.
  1708. return true;
  1709. }
  1710. // Keep looking for more map info.
  1711. return false;
  1712. });
  1713. if (IsVariableUsedInMapClause) {
  1714. // If variable is identified in a map clause it is always captured by
  1715. // reference except if it is a pointer that is dereferenced somehow.
  1716. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1717. } else {
  1718. // By default, all the data that has a scalar type is mapped by copy
  1719. // (except for reduction variables).
  1720. IsByRef =
  1721. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1722. !Ty->isAnyPointerType()) ||
  1723. !Ty->isScalarType() ||
  1724. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1725. DSAStack->hasExplicitDSA(
  1726. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1727. }
  1728. }
  1729. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1730. IsByRef =
  1731. ((IsVariableUsedInMapClause &&
  1732. DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
  1733. OMPD_target) ||
  1734. !DSAStack->hasExplicitDSA(
  1735. D,
  1736. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1737. Level, /*NotLastprivate=*/true)) &&
  1738. // If the variable is artificial and must be captured by value - try to
  1739. // capture by value.
  1740. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1741. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1742. }
  1743. // When passing data by copy, we need to make sure it fits the uintptr size
  1744. // and alignment, because the runtime library only deals with uintptr types.
  1745. // If it does not fit the uintptr size, we need to pass the data by reference
  1746. // instead.
  1747. if (!IsByRef &&
  1748. (Ctx.getTypeSizeInChars(Ty) >
  1749. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1750. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1751. IsByRef = true;
  1752. }
  1753. return IsByRef;
  1754. }
  1755. unsigned Sema::getOpenMPNestingLevel() const {
  1756. assert(getLangOpts().OpenMP);
  1757. return DSAStack->getNestingLevel();
  1758. }
  1759. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1760. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1761. !DSAStack->isClauseParsingMode()) ||
  1762. DSAStack->hasDirective(
  1763. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1764. SourceLocation) -> bool {
  1765. return isOpenMPTargetExecutionDirective(K);
  1766. },
  1767. false);
  1768. }
  1769. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
  1770. unsigned StopAt) {
  1771. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1772. D = getCanonicalDecl(D);
  1773. // If we want to determine whether the variable should be captured from the
  1774. // perspective of the current capturing scope, and we've already left all the
  1775. // capturing scopes of the top directive on the stack, check from the
  1776. // perspective of its parent directive (if any) instead.
  1777. DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
  1778. *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
  1779. // If we are attempting to capture a global variable in a directive with
  1780. // 'target' we return true so that this global is also mapped to the device.
  1781. //
  1782. auto *VD = dyn_cast<VarDecl>(D);
  1783. if (VD && !VD->hasLocalStorage() &&
  1784. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1785. if (isInOpenMPDeclareTargetContext()) {
  1786. // Try to mark variable as declare target if it is used in capturing
  1787. // regions.
  1788. if (LangOpts.OpenMP <= 45 &&
  1789. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1790. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1791. return nullptr;
  1792. } else if (isInOpenMPTargetExecutionDirective()) {
  1793. // If the declaration is enclosed in a 'declare target' directive,
  1794. // then it should not be captured.
  1795. //
  1796. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1797. return nullptr;
  1798. return VD;
  1799. }
  1800. }
  1801. if (CheckScopeInfo) {
  1802. bool OpenMPFound = false;
  1803. for (unsigned I = StopAt + 1; I > 0; --I) {
  1804. FunctionScopeInfo *FSI = FunctionScopes[I - 1];
  1805. if(!isa<CapturingScopeInfo>(FSI))
  1806. return nullptr;
  1807. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  1808. if (RSI->CapRegionKind == CR_OpenMP) {
  1809. OpenMPFound = true;
  1810. break;
  1811. }
  1812. }
  1813. if (!OpenMPFound)
  1814. return nullptr;
  1815. }
  1816. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1817. (!DSAStack->isClauseParsingMode() ||
  1818. DSAStack->getParentDirective() != OMPD_unknown)) {
  1819. auto &&Info = DSAStack->isLoopControlVariable(D);
  1820. if (Info.first ||
  1821. (VD && VD->hasLocalStorage() &&
  1822. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1823. (VD && DSAStack->isForceVarCapturing()))
  1824. return VD ? VD : Info.second;
  1825. DSAStackTy::DSAVarData DVarPrivate =
  1826. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1827. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1828. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1829. // Threadprivate variables must not be captured.
  1830. if (isOpenMPThreadPrivate(DVarPrivate.CKind))
  1831. return nullptr;
  1832. // The variable is not private or it is the variable in the directive with
  1833. // default(none) clause and not used in any clause.
  1834. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1835. [](OpenMPDirectiveKind) { return true; },
  1836. DSAStack->isClauseParsingMode());
  1837. if (DVarPrivate.CKind != OMPC_unknown ||
  1838. (VD && DSAStack->getDefaultDSA() == DSA_none))
  1839. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1840. }
  1841. return nullptr;
  1842. }
  1843. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1844. unsigned Level) const {
  1845. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1846. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1847. FunctionScopesIndex -= Regions.size();
  1848. }
  1849. void Sema::startOpenMPLoop() {
  1850. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1851. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1852. DSAStack->loopInit();
  1853. }
  1854. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1855. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1856. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1857. if (DSAStack->getAssociatedLoops() > 0 &&
  1858. !DSAStack->isLoopStarted()) {
  1859. DSAStack->resetPossibleLoopCounter(D);
  1860. DSAStack->loopStart();
  1861. return true;
  1862. }
  1863. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1864. DSAStack->isLoopControlVariable(D).first) &&
  1865. !DSAStack->hasExplicitDSA(
  1866. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1867. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1868. return true;
  1869. }
  1870. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1871. if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
  1872. DSAStack->isForceVarCapturing() &&
  1873. !DSAStack->hasExplicitDSA(
  1874. D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
  1875. return true;
  1876. }
  1877. return DSAStack->hasExplicitDSA(
  1878. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1879. (DSAStack->isClauseParsingMode() &&
  1880. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1881. // Consider taskgroup reduction descriptor variable a private to avoid
  1882. // possible capture in the region.
  1883. (DSAStack->hasExplicitDirective(
  1884. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1885. Level) &&
  1886. DSAStack->isTaskgroupReductionRef(D, Level));
  1887. }
  1888. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1889. unsigned Level) {
  1890. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1891. D = getCanonicalDecl(D);
  1892. OpenMPClauseKind OMPC = OMPC_unknown;
  1893. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1894. const unsigned NewLevel = I - 1;
  1895. if (DSAStack->hasExplicitDSA(D,
  1896. [&OMPC](const OpenMPClauseKind K) {
  1897. if (isOpenMPPrivate(K)) {
  1898. OMPC = K;
  1899. return true;
  1900. }
  1901. return false;
  1902. },
  1903. NewLevel))
  1904. break;
  1905. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1906. D, NewLevel,
  1907. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1908. OpenMPClauseKind) { return true; })) {
  1909. OMPC = OMPC_map;
  1910. break;
  1911. }
  1912. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1913. NewLevel)) {
  1914. OMPC = OMPC_map;
  1915. if (D->getType()->isScalarType() &&
  1916. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1917. DefaultMapAttributes::DMA_tofrom_scalar)
  1918. OMPC = OMPC_firstprivate;
  1919. break;
  1920. }
  1921. }
  1922. if (OMPC != OMPC_unknown)
  1923. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1924. }
  1925. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1926. unsigned Level) const {
  1927. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1928. // Return true if the current level is no longer enclosed in a target region.
  1929. const auto *VD = dyn_cast<VarDecl>(D);
  1930. return VD && !VD->hasLocalStorage() &&
  1931. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1932. Level);
  1933. }
  1934. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1935. void Sema::finalizeOpenMPDelayedAnalysis() {
  1936. assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
  1937. // Diagnose implicit declare target functions and their callees.
  1938. for (const auto &CallerCallees : DeviceCallGraph) {
  1939. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1940. OMPDeclareTargetDeclAttr::getDeviceType(
  1941. CallerCallees.getFirst()->getMostRecentDecl());
  1942. // Ignore host functions during device analyzis.
  1943. if (LangOpts.OpenMPIsDevice && DevTy &&
  1944. *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  1945. continue;
  1946. // Ignore nohost functions during host analyzis.
  1947. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1948. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  1949. continue;
  1950. for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
  1951. &Callee : CallerCallees.getSecond()) {
  1952. const FunctionDecl *FD = Callee.first->getMostRecentDecl();
  1953. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1954. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  1955. if (LangOpts.OpenMPIsDevice && DevTy &&
  1956. *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
  1957. // Diagnose host function called during device codegen.
  1958. StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
  1959. OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1960. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1961. << HostDevTy << 0;
  1962. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1963. diag::note_omp_marked_device_type_here)
  1964. << HostDevTy;
  1965. continue;
  1966. }
  1967. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1968. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  1969. // Diagnose nohost function called during host codegen.
  1970. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1971. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1972. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1973. << NoHostDevTy << 1;
  1974. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1975. diag::note_omp_marked_device_type_here)
  1976. << NoHostDevTy;
  1977. continue;
  1978. }
  1979. }
  1980. }
  1981. }
  1982. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1983. const DeclarationNameInfo &DirName,
  1984. Scope *CurScope, SourceLocation Loc) {
  1985. DSAStack->push(DKind, DirName, CurScope, Loc);
  1986. PushExpressionEvaluationContext(
  1987. ExpressionEvaluationContext::PotentiallyEvaluated);
  1988. }
  1989. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1990. DSAStack->setClauseParsingMode(K);
  1991. }
  1992. void Sema::EndOpenMPClause() {
  1993. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1994. }
  1995. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  1996. ArrayRef<OMPClause *> Clauses);
  1997. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1998. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1999. // A variable of class type (or array thereof) that appears in a lastprivate
  2000. // clause requires an accessible, unambiguous default constructor for the
  2001. // class type, unless the list item is also specified in a firstprivate
  2002. // clause.
  2003. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  2004. for (OMPClause *C : D->clauses()) {
  2005. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  2006. SmallVector<Expr *, 8> PrivateCopies;
  2007. for (Expr *DE : Clause->varlists()) {
  2008. if (DE->isValueDependent() || DE->isTypeDependent()) {
  2009. PrivateCopies.push_back(nullptr);
  2010. continue;
  2011. }
  2012. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  2013. auto *VD = cast<VarDecl>(DRE->getDecl());
  2014. QualType Type = VD->getType().getNonReferenceType();
  2015. const DSAStackTy::DSAVarData DVar =
  2016. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2017. if (DVar.CKind == OMPC_lastprivate) {
  2018. // Generate helper private variable and initialize it with the
  2019. // default value. The address of the original variable is replaced
  2020. // by the address of the new private variable in CodeGen. This new
  2021. // variable is not added to IdResolver, so the code in the OpenMP
  2022. // region uses original variable for proper diagnostics.
  2023. VarDecl *VDPrivate = buildVarDecl(
  2024. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  2025. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  2026. ActOnUninitializedDecl(VDPrivate);
  2027. if (VDPrivate->isInvalidDecl()) {
  2028. PrivateCopies.push_back(nullptr);
  2029. continue;
  2030. }
  2031. PrivateCopies.push_back(buildDeclRefExpr(
  2032. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  2033. } else {
  2034. // The variable is also a firstprivate, so initialization sequence
  2035. // for private copy is generated already.
  2036. PrivateCopies.push_back(nullptr);
  2037. }
  2038. }
  2039. Clause->setPrivateCopies(PrivateCopies);
  2040. }
  2041. }
  2042. // Check allocate clauses.
  2043. if (!CurContext->isDependentContext())
  2044. checkAllocateClauses(*this, DSAStack, D->clauses());
  2045. }
  2046. DSAStack->pop();
  2047. DiscardCleanupsInEvaluationContext();
  2048. PopExpressionEvaluationContext();
  2049. }
  2050. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  2051. Expr *NumIterations, Sema &SemaRef,
  2052. Scope *S, DSAStackTy *Stack);
  2053. namespace {
  2054. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  2055. private:
  2056. Sema &SemaRef;
  2057. public:
  2058. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2059. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2060. NamedDecl *ND = Candidate.getCorrectionDecl();
  2061. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  2062. return VD->hasGlobalStorage() &&
  2063. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2064. SemaRef.getCurScope());
  2065. }
  2066. return false;
  2067. }
  2068. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2069. return std::make_unique<VarDeclFilterCCC>(*this);
  2070. }
  2071. };
  2072. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  2073. private:
  2074. Sema &SemaRef;
  2075. public:
  2076. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2077. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2078. NamedDecl *ND = Candidate.getCorrectionDecl();
  2079. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  2080. isa<FunctionDecl>(ND))) {
  2081. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2082. SemaRef.getCurScope());
  2083. }
  2084. return false;
  2085. }
  2086. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2087. return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
  2088. }
  2089. };
  2090. } // namespace
  2091. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  2092. CXXScopeSpec &ScopeSpec,
  2093. const DeclarationNameInfo &Id,
  2094. OpenMPDirectiveKind Kind) {
  2095. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  2096. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  2097. if (Lookup.isAmbiguous())
  2098. return ExprError();
  2099. VarDecl *VD;
  2100. if (!Lookup.isSingleResult()) {
  2101. VarDeclFilterCCC CCC(*this);
  2102. if (TypoCorrection Corrected =
  2103. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  2104. CTK_ErrorRecovery)) {
  2105. diagnoseTypo(Corrected,
  2106. PDiag(Lookup.empty()
  2107. ? diag::err_undeclared_var_use_suggest
  2108. : diag::err_omp_expected_var_arg_suggest)
  2109. << Id.getName());
  2110. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  2111. } else {
  2112. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  2113. : diag::err_omp_expected_var_arg)
  2114. << Id.getName();
  2115. return ExprError();
  2116. }
  2117. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  2118. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  2119. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  2120. return ExprError();
  2121. }
  2122. Lookup.suppressDiagnostics();
  2123. // OpenMP [2.9.2, Syntax, C/C++]
  2124. // Variables must be file-scope, namespace-scope, or static block-scope.
  2125. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  2126. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  2127. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  2128. bool IsDecl =
  2129. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2130. Diag(VD->getLocation(),
  2131. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2132. << VD;
  2133. return ExprError();
  2134. }
  2135. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  2136. NamedDecl *ND = CanonicalVD;
  2137. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  2138. // A threadprivate directive for file-scope variables must appear outside
  2139. // any definition or declaration.
  2140. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  2141. !getCurLexicalContext()->isTranslationUnit()) {
  2142. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2143. << getOpenMPDirectiveName(Kind) << VD;
  2144. bool IsDecl =
  2145. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2146. Diag(VD->getLocation(),
  2147. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2148. << VD;
  2149. return ExprError();
  2150. }
  2151. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  2152. // A threadprivate directive for static class member variables must appear
  2153. // in the class definition, in the same scope in which the member
  2154. // variables are declared.
  2155. if (CanonicalVD->isStaticDataMember() &&
  2156. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  2157. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2158. << getOpenMPDirectiveName(Kind) << VD;
  2159. bool IsDecl =
  2160. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2161. Diag(VD->getLocation(),
  2162. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2163. << VD;
  2164. return ExprError();
  2165. }
  2166. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  2167. // A threadprivate directive for namespace-scope variables must appear
  2168. // outside any definition or declaration other than the namespace
  2169. // definition itself.
  2170. if (CanonicalVD->getDeclContext()->isNamespace() &&
  2171. (!getCurLexicalContext()->isFileContext() ||
  2172. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  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.6]
  2183. // A threadprivate directive for static block-scope variables must appear
  2184. // in the scope of the variable and not in a nested scope.
  2185. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  2186. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  2187. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2188. << getOpenMPDirectiveName(Kind) << VD;
  2189. bool IsDecl =
  2190. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2191. Diag(VD->getLocation(),
  2192. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2193. << VD;
  2194. return ExprError();
  2195. }
  2196. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  2197. // A threadprivate directive must lexically precede all references to any
  2198. // of the variables in its list.
  2199. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  2200. !DSAStack->isThreadPrivate(VD)) {
  2201. Diag(Id.getLoc(), diag::err_omp_var_used)
  2202. << getOpenMPDirectiveName(Kind) << VD;
  2203. return ExprError();
  2204. }
  2205. QualType ExprType = VD->getType().getNonReferenceType();
  2206. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  2207. SourceLocation(), VD,
  2208. /*RefersToEnclosingVariableOrCapture=*/false,
  2209. Id.getLoc(), ExprType, VK_LValue);
  2210. }
  2211. Sema::DeclGroupPtrTy
  2212. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  2213. ArrayRef<Expr *> VarList) {
  2214. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  2215. CurContext->addDecl(D);
  2216. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2217. }
  2218. return nullptr;
  2219. }
  2220. namespace {
  2221. class LocalVarRefChecker final
  2222. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  2223. Sema &SemaRef;
  2224. public:
  2225. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2226. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2227. if (VD->hasLocalStorage()) {
  2228. SemaRef.Diag(E->getBeginLoc(),
  2229. diag::err_omp_local_var_in_threadprivate_init)
  2230. << E->getSourceRange();
  2231. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  2232. << VD << VD->getSourceRange();
  2233. return true;
  2234. }
  2235. }
  2236. return false;
  2237. }
  2238. bool VisitStmt(const Stmt *S) {
  2239. for (const Stmt *Child : S->children()) {
  2240. if (Child && Visit(Child))
  2241. return true;
  2242. }
  2243. return false;
  2244. }
  2245. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  2246. };
  2247. } // namespace
  2248. OMPThreadPrivateDecl *
  2249. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  2250. SmallVector<Expr *, 8> Vars;
  2251. for (Expr *RefExpr : VarList) {
  2252. auto *DE = cast<DeclRefExpr>(RefExpr);
  2253. auto *VD = cast<VarDecl>(DE->getDecl());
  2254. SourceLocation ILoc = DE->getExprLoc();
  2255. // Mark variable as used.
  2256. VD->setReferenced();
  2257. VD->markUsed(Context);
  2258. QualType QType = VD->getType();
  2259. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2260. // It will be analyzed later.
  2261. Vars.push_back(DE);
  2262. continue;
  2263. }
  2264. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2265. // A threadprivate variable must not have an incomplete type.
  2266. if (RequireCompleteType(ILoc, VD->getType(),
  2267. diag::err_omp_threadprivate_incomplete_type)) {
  2268. continue;
  2269. }
  2270. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2271. // A threadprivate variable must not have a reference type.
  2272. if (VD->getType()->isReferenceType()) {
  2273. Diag(ILoc, diag::err_omp_ref_type_arg)
  2274. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  2275. bool IsDecl =
  2276. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2277. Diag(VD->getLocation(),
  2278. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2279. << VD;
  2280. continue;
  2281. }
  2282. // Check if this is a TLS variable. If TLS is not being supported, produce
  2283. // the corresponding diagnostic.
  2284. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  2285. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  2286. getLangOpts().OpenMPUseTLS &&
  2287. getASTContext().getTargetInfo().isTLSSupported())) ||
  2288. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2289. !VD->isLocalVarDecl())) {
  2290. Diag(ILoc, diag::err_omp_var_thread_local)
  2291. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  2292. bool IsDecl =
  2293. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2294. Diag(VD->getLocation(),
  2295. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2296. << VD;
  2297. continue;
  2298. }
  2299. // Check if initial value of threadprivate variable reference variable with
  2300. // local storage (it is not supported by runtime).
  2301. if (const Expr *Init = VD->getAnyInitializer()) {
  2302. LocalVarRefChecker Checker(*this);
  2303. if (Checker.Visit(Init))
  2304. continue;
  2305. }
  2306. Vars.push_back(RefExpr);
  2307. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2308. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2309. Context, SourceRange(Loc, Loc)));
  2310. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2311. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2312. }
  2313. OMPThreadPrivateDecl *D = nullptr;
  2314. if (!Vars.empty()) {
  2315. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2316. Vars);
  2317. D->setAccess(AS_public);
  2318. }
  2319. return D;
  2320. }
  2321. static OMPAllocateDeclAttr::AllocatorTypeTy
  2322. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  2323. if (!Allocator)
  2324. return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2325. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2326. Allocator->isInstantiationDependent() ||
  2327. Allocator->containsUnexpandedParameterPack())
  2328. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2329. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2330. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2331. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2332. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  2333. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  2334. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  2335. llvm::FoldingSetNodeID AEId, DAEId;
  2336. AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  2337. DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
  2338. if (AEId == DAEId) {
  2339. AllocatorKindRes = AllocatorKind;
  2340. break;
  2341. }
  2342. }
  2343. return AllocatorKindRes;
  2344. }
  2345. static bool checkPreviousOMPAllocateAttribute(
  2346. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  2347. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  2348. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  2349. return false;
  2350. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  2351. Expr *PrevAllocator = A->getAllocator();
  2352. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  2353. getAllocatorKind(S, Stack, PrevAllocator);
  2354. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  2355. if (AllocatorsMatch &&
  2356. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  2357. Allocator && PrevAllocator) {
  2358. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2359. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  2360. llvm::FoldingSetNodeID AEId, PAEId;
  2361. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  2362. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  2363. AllocatorsMatch = AEId == PAEId;
  2364. }
  2365. if (!AllocatorsMatch) {
  2366. SmallString<256> AllocatorBuffer;
  2367. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  2368. if (Allocator)
  2369. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  2370. SmallString<256> PrevAllocatorBuffer;
  2371. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  2372. if (PrevAllocator)
  2373. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  2374. S.getPrintingPolicy());
  2375. SourceLocation AllocatorLoc =
  2376. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  2377. SourceRange AllocatorRange =
  2378. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  2379. SourceLocation PrevAllocatorLoc =
  2380. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  2381. SourceRange PrevAllocatorRange =
  2382. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  2383. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  2384. << (Allocator ? 1 : 0) << AllocatorStream.str()
  2385. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  2386. << AllocatorRange;
  2387. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  2388. << PrevAllocatorRange;
  2389. return true;
  2390. }
  2391. return false;
  2392. }
  2393. static void
  2394. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  2395. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  2396. Expr *Allocator, SourceRange SR) {
  2397. if (VD->hasAttr<OMPAllocateDeclAttr>())
  2398. return;
  2399. if (Allocator &&
  2400. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2401. Allocator->isInstantiationDependent() ||
  2402. Allocator->containsUnexpandedParameterPack()))
  2403. return;
  2404. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  2405. Allocator, SR);
  2406. VD->addAttr(A);
  2407. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  2408. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2409. }
  2410. Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
  2411. SourceLocation Loc, ArrayRef<Expr *> VarList,
  2412. ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
  2413. assert(Clauses.size() <= 1 && "Expected at most one clause.");
  2414. Expr *Allocator = nullptr;
  2415. if (Clauses.empty()) {
  2416. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  2417. // allocate directives that appear in a target region must specify an
  2418. // allocator clause unless a requires directive with the dynamic_allocators
  2419. // clause is present in the same compilation unit.
  2420. if (LangOpts.OpenMPIsDevice &&
  2421. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  2422. targetDiag(Loc, diag::err_expected_allocator_clause);
  2423. } else {
  2424. Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
  2425. }
  2426. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  2427. getAllocatorKind(*this, DSAStack, Allocator);
  2428. SmallVector<Expr *, 8> Vars;
  2429. for (Expr *RefExpr : VarList) {
  2430. auto *DE = cast<DeclRefExpr>(RefExpr);
  2431. auto *VD = cast<VarDecl>(DE->getDecl());
  2432. // Check if this is a TLS variable or global register.
  2433. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2434. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2435. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2436. !VD->isLocalVarDecl()))
  2437. continue;
  2438. // If the used several times in the allocate directive, the same allocator
  2439. // must be used.
  2440. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  2441. AllocatorKind, Allocator))
  2442. continue;
  2443. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  2444. // If a list item has a static storage type, the allocator expression in the
  2445. // allocator clause must be a constant expression that evaluates to one of
  2446. // the predefined memory allocator values.
  2447. if (Allocator && VD->hasGlobalStorage()) {
  2448. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  2449. Diag(Allocator->getExprLoc(),
  2450. diag::err_omp_expected_predefined_allocator)
  2451. << Allocator->getSourceRange();
  2452. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  2453. VarDecl::DeclarationOnly;
  2454. Diag(VD->getLocation(),
  2455. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2456. << VD;
  2457. continue;
  2458. }
  2459. }
  2460. Vars.push_back(RefExpr);
  2461. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
  2462. DE->getSourceRange());
  2463. }
  2464. if (Vars.empty())
  2465. return nullptr;
  2466. if (!Owner)
  2467. Owner = getCurLexicalContext();
  2468. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2469. D->setAccess(AS_public);
  2470. Owner->addDecl(D);
  2471. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2472. }
  2473. Sema::DeclGroupPtrTy
  2474. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2475. ArrayRef<OMPClause *> ClauseList) {
  2476. OMPRequiresDecl *D = nullptr;
  2477. if (!CurContext->isFileContext()) {
  2478. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2479. } else {
  2480. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2481. if (D) {
  2482. CurContext->addDecl(D);
  2483. DSAStack->addRequiresDecl(D);
  2484. }
  2485. }
  2486. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2487. }
  2488. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2489. ArrayRef<OMPClause *> ClauseList) {
  2490. /// For target specific clauses, the requires directive cannot be
  2491. /// specified after the handling of any of the target regions in the
  2492. /// current compilation unit.
  2493. ArrayRef<SourceLocation> TargetLocations =
  2494. DSAStack->getEncounteredTargetLocs();
  2495. if (!TargetLocations.empty()) {
  2496. for (const OMPClause *CNew : ClauseList) {
  2497. // Check if any of the requires clauses affect target regions.
  2498. if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
  2499. isa<OMPUnifiedAddressClause>(CNew) ||
  2500. isa<OMPReverseOffloadClause>(CNew) ||
  2501. isa<OMPDynamicAllocatorsClause>(CNew)) {
  2502. Diag(Loc, diag::err_omp_target_before_requires)
  2503. << getOpenMPClauseName(CNew->getClauseKind());
  2504. for (SourceLocation TargetLoc : TargetLocations) {
  2505. Diag(TargetLoc, diag::note_omp_requires_encountered_target);
  2506. }
  2507. }
  2508. }
  2509. }
  2510. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2511. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2512. ClauseList);
  2513. return nullptr;
  2514. }
  2515. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2516. const ValueDecl *D,
  2517. const DSAStackTy::DSAVarData &DVar,
  2518. bool IsLoopIterVar = false) {
  2519. if (DVar.RefExpr) {
  2520. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2521. << getOpenMPClauseName(DVar.CKind);
  2522. return;
  2523. }
  2524. enum {
  2525. PDSA_StaticMemberShared,
  2526. PDSA_StaticLocalVarShared,
  2527. PDSA_LoopIterVarPrivate,
  2528. PDSA_LoopIterVarLinear,
  2529. PDSA_LoopIterVarLastprivate,
  2530. PDSA_ConstVarShared,
  2531. PDSA_GlobalVarShared,
  2532. PDSA_TaskVarFirstprivate,
  2533. PDSA_LocalVarPrivate,
  2534. PDSA_Implicit
  2535. } Reason = PDSA_Implicit;
  2536. bool ReportHint = false;
  2537. auto ReportLoc = D->getLocation();
  2538. auto *VD = dyn_cast<VarDecl>(D);
  2539. if (IsLoopIterVar) {
  2540. if (DVar.CKind == OMPC_private)
  2541. Reason = PDSA_LoopIterVarPrivate;
  2542. else if (DVar.CKind == OMPC_lastprivate)
  2543. Reason = PDSA_LoopIterVarLastprivate;
  2544. else
  2545. Reason = PDSA_LoopIterVarLinear;
  2546. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2547. DVar.CKind == OMPC_firstprivate) {
  2548. Reason = PDSA_TaskVarFirstprivate;
  2549. ReportLoc = DVar.ImplicitDSALoc;
  2550. } else if (VD && VD->isStaticLocal())
  2551. Reason = PDSA_StaticLocalVarShared;
  2552. else if (VD && VD->isStaticDataMember())
  2553. Reason = PDSA_StaticMemberShared;
  2554. else if (VD && VD->isFileVarDecl())
  2555. Reason = PDSA_GlobalVarShared;
  2556. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2557. Reason = PDSA_ConstVarShared;
  2558. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2559. ReportHint = true;
  2560. Reason = PDSA_LocalVarPrivate;
  2561. }
  2562. if (Reason != PDSA_Implicit) {
  2563. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2564. << Reason << ReportHint
  2565. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2566. } else if (DVar.ImplicitDSALoc.isValid()) {
  2567. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2568. << getOpenMPClauseName(DVar.CKind);
  2569. }
  2570. }
  2571. namespace {
  2572. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2573. DSAStackTy *Stack;
  2574. Sema &SemaRef;
  2575. bool ErrorFound = false;
  2576. CapturedStmt *CS = nullptr;
  2577. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2578. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2579. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2580. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2581. void VisitSubCaptures(OMPExecutableDirective *S) {
  2582. // Check implicitly captured variables.
  2583. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2584. return;
  2585. visitSubCaptures(S->getInnermostCapturedStmt());
  2586. }
  2587. public:
  2588. void VisitDeclRefExpr(DeclRefExpr *E) {
  2589. if (E->isTypeDependent() || E->isValueDependent() ||
  2590. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2591. return;
  2592. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2593. // Check the datasharing rules for the expressions in the clauses.
  2594. if (!CS) {
  2595. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  2596. if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
  2597. Visit(CED->getInit());
  2598. return;
  2599. }
  2600. } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
  2601. // Do not analyze internal variables and do not enclose them into
  2602. // implicit clauses.
  2603. return;
  2604. VD = VD->getCanonicalDecl();
  2605. // Skip internally declared variables.
  2606. if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
  2607. return;
  2608. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2609. // Check if the variable has explicit DSA set and stop analysis if it so.
  2610. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2611. return;
  2612. // Skip internally declared static variables.
  2613. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2614. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2615. if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
  2616. (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  2617. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2618. return;
  2619. SourceLocation ELoc = E->getExprLoc();
  2620. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2621. // The default(none) clause requires that each variable that is referenced
  2622. // in the construct, and does not have a predetermined data-sharing
  2623. // attribute, must have its data-sharing attribute explicitly determined
  2624. // by being listed in a data-sharing attribute clause.
  2625. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2626. isImplicitOrExplicitTaskingRegion(DKind) &&
  2627. VarsWithInheritedDSA.count(VD) == 0) {
  2628. VarsWithInheritedDSA[VD] = E;
  2629. return;
  2630. }
  2631. if (isOpenMPTargetExecutionDirective(DKind) &&
  2632. !Stack->isLoopControlVariable(VD).first) {
  2633. if (!Stack->checkMappableExprComponentListsForDecl(
  2634. VD, /*CurrentRegionOnly=*/true,
  2635. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2636. StackComponents,
  2637. OpenMPClauseKind) {
  2638. // Variable is used if it has been marked as an array, array
  2639. // section or the variable iself.
  2640. return StackComponents.size() == 1 ||
  2641. std::all_of(
  2642. std::next(StackComponents.rbegin()),
  2643. StackComponents.rend(),
  2644. [](const OMPClauseMappableExprCommon::
  2645. MappableComponent &MC) {
  2646. return MC.getAssociatedDeclaration() ==
  2647. nullptr &&
  2648. (isa<OMPArraySectionExpr>(
  2649. MC.getAssociatedExpression()) ||
  2650. isa<ArraySubscriptExpr>(
  2651. MC.getAssociatedExpression()));
  2652. });
  2653. })) {
  2654. bool IsFirstprivate = false;
  2655. // By default lambdas are captured as firstprivates.
  2656. if (const auto *RD =
  2657. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2658. IsFirstprivate = RD->isLambda();
  2659. IsFirstprivate =
  2660. IsFirstprivate ||
  2661. (VD->getType().getNonReferenceType()->isScalarType() &&
  2662. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2663. if (IsFirstprivate)
  2664. ImplicitFirstprivate.emplace_back(E);
  2665. else
  2666. ImplicitMap.emplace_back(E);
  2667. return;
  2668. }
  2669. }
  2670. // OpenMP [2.9.3.6, Restrictions, p.2]
  2671. // A list item that appears in a reduction clause of the innermost
  2672. // enclosing worksharing or parallel construct may not be accessed in an
  2673. // explicit task.
  2674. DVar = Stack->hasInnermostDSA(
  2675. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2676. [](OpenMPDirectiveKind K) {
  2677. return isOpenMPParallelDirective(K) ||
  2678. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2679. },
  2680. /*FromParent=*/true);
  2681. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2682. ErrorFound = true;
  2683. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2684. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2685. return;
  2686. }
  2687. // Define implicit data-sharing attributes for task.
  2688. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2689. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2690. !Stack->isLoopControlVariable(VD).first) {
  2691. ImplicitFirstprivate.push_back(E);
  2692. return;
  2693. }
  2694. // Store implicitly used globals with declare target link for parent
  2695. // target.
  2696. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  2697. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2698. Stack->addToParentTargetRegionLinkGlobals(E);
  2699. return;
  2700. }
  2701. }
  2702. }
  2703. void VisitMemberExpr(MemberExpr *E) {
  2704. if (E->isTypeDependent() || E->isValueDependent() ||
  2705. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2706. return;
  2707. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2708. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2709. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2710. if (!FD)
  2711. return;
  2712. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2713. // Check if the variable has explicit DSA set and stop analysis if it
  2714. // so.
  2715. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2716. return;
  2717. if (isOpenMPTargetExecutionDirective(DKind) &&
  2718. !Stack->isLoopControlVariable(FD).first &&
  2719. !Stack->checkMappableExprComponentListsForDecl(
  2720. FD, /*CurrentRegionOnly=*/true,
  2721. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2722. StackComponents,
  2723. OpenMPClauseKind) {
  2724. return isa<CXXThisExpr>(
  2725. cast<MemberExpr>(
  2726. StackComponents.back().getAssociatedExpression())
  2727. ->getBase()
  2728. ->IgnoreParens());
  2729. })) {
  2730. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2731. // A bit-field cannot appear in a map clause.
  2732. //
  2733. if (FD->isBitField())
  2734. return;
  2735. // Check to see if the member expression is referencing a class that
  2736. // has already been explicitly mapped
  2737. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2738. return;
  2739. ImplicitMap.emplace_back(E);
  2740. return;
  2741. }
  2742. SourceLocation ELoc = E->getExprLoc();
  2743. // OpenMP [2.9.3.6, Restrictions, p.2]
  2744. // A list item that appears in a reduction clause of the innermost
  2745. // enclosing worksharing or parallel construct may not be accessed in
  2746. // an explicit task.
  2747. DVar = Stack->hasInnermostDSA(
  2748. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2749. [](OpenMPDirectiveKind K) {
  2750. return isOpenMPParallelDirective(K) ||
  2751. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2752. },
  2753. /*FromParent=*/true);
  2754. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2755. ErrorFound = true;
  2756. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2757. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2758. return;
  2759. }
  2760. // Define implicit data-sharing attributes for task.
  2761. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2762. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2763. !Stack->isLoopControlVariable(FD).first) {
  2764. // Check if there is a captured expression for the current field in the
  2765. // region. Do not mark it as firstprivate unless there is no captured
  2766. // expression.
  2767. // TODO: try to make it firstprivate.
  2768. if (DVar.CKind != OMPC_unknown)
  2769. ImplicitFirstprivate.push_back(E);
  2770. }
  2771. return;
  2772. }
  2773. if (isOpenMPTargetExecutionDirective(DKind)) {
  2774. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2775. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2776. /*NoDiagnose=*/true))
  2777. return;
  2778. const auto *VD = cast<ValueDecl>(
  2779. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2780. if (!Stack->checkMappableExprComponentListsForDecl(
  2781. VD, /*CurrentRegionOnly=*/true,
  2782. [&CurComponents](
  2783. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2784. StackComponents,
  2785. OpenMPClauseKind) {
  2786. auto CCI = CurComponents.rbegin();
  2787. auto CCE = CurComponents.rend();
  2788. for (const auto &SC : llvm::reverse(StackComponents)) {
  2789. // Do both expressions have the same kind?
  2790. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2791. SC.getAssociatedExpression()->getStmtClass())
  2792. if (!(isa<OMPArraySectionExpr>(
  2793. SC.getAssociatedExpression()) &&
  2794. isa<ArraySubscriptExpr>(
  2795. CCI->getAssociatedExpression())))
  2796. return false;
  2797. const Decl *CCD = CCI->getAssociatedDeclaration();
  2798. const Decl *SCD = SC.getAssociatedDeclaration();
  2799. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2800. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2801. if (SCD != CCD)
  2802. return false;
  2803. std::advance(CCI, 1);
  2804. if (CCI == CCE)
  2805. break;
  2806. }
  2807. return true;
  2808. })) {
  2809. Visit(E->getBase());
  2810. }
  2811. } else {
  2812. Visit(E->getBase());
  2813. }
  2814. }
  2815. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2816. for (OMPClause *C : S->clauses()) {
  2817. // Skip analysis of arguments of implicitly defined firstprivate clause
  2818. // for task|target directives.
  2819. // Skip analysis of arguments of implicitly defined map clause for target
  2820. // directives.
  2821. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2822. C->isImplicit())) {
  2823. for (Stmt *CC : C->children()) {
  2824. if (CC)
  2825. Visit(CC);
  2826. }
  2827. }
  2828. }
  2829. // Check implicitly captured variables.
  2830. VisitSubCaptures(S);
  2831. }
  2832. void VisitStmt(Stmt *S) {
  2833. for (Stmt *C : S->children()) {
  2834. if (C) {
  2835. // Check implicitly captured variables in the task-based directives to
  2836. // check if they must be firstprivatized.
  2837. Visit(C);
  2838. }
  2839. }
  2840. }
  2841. void visitSubCaptures(CapturedStmt *S) {
  2842. for (const CapturedStmt::Capture &Cap : S->captures()) {
  2843. if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
  2844. continue;
  2845. VarDecl *VD = Cap.getCapturedVar();
  2846. // Do not try to map the variable if it or its sub-component was mapped
  2847. // already.
  2848. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2849. Stack->checkMappableExprComponentListsForDecl(
  2850. VD, /*CurrentRegionOnly=*/true,
  2851. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2852. OpenMPClauseKind) { return true; }))
  2853. continue;
  2854. DeclRefExpr *DRE = buildDeclRefExpr(
  2855. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2856. Cap.getLocation(), /*RefersToCapture=*/true);
  2857. Visit(DRE);
  2858. }
  2859. }
  2860. bool isErrorFound() const { return ErrorFound; }
  2861. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2862. return ImplicitFirstprivate;
  2863. }
  2864. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2865. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2866. return VarsWithInheritedDSA;
  2867. }
  2868. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2869. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  2870. // Process declare target link variables for the target directives.
  2871. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  2872. for (DeclRefExpr *E : Stack->getLinkGlobals())
  2873. Visit(E);
  2874. }
  2875. }
  2876. };
  2877. } // namespace
  2878. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2879. switch (DKind) {
  2880. case OMPD_parallel:
  2881. case OMPD_parallel_for:
  2882. case OMPD_parallel_for_simd:
  2883. case OMPD_parallel_sections:
  2884. case OMPD_teams:
  2885. case OMPD_teams_distribute:
  2886. case OMPD_teams_distribute_simd: {
  2887. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2888. QualType KmpInt32PtrTy =
  2889. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2890. Sema::CapturedParamNameType Params[] = {
  2891. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2892. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2893. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2894. };
  2895. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2896. Params);
  2897. break;
  2898. }
  2899. case OMPD_target_teams:
  2900. case OMPD_target_parallel:
  2901. case OMPD_target_parallel_for:
  2902. case OMPD_target_parallel_for_simd:
  2903. case OMPD_target_teams_distribute:
  2904. case OMPD_target_teams_distribute_simd: {
  2905. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2906. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2907. QualType KmpInt32PtrTy =
  2908. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2909. QualType Args[] = {VoidPtrTy};
  2910. FunctionProtoType::ExtProtoInfo EPI;
  2911. EPI.Variadic = true;
  2912. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2913. Sema::CapturedParamNameType Params[] = {
  2914. std::make_pair(".global_tid.", KmpInt32Ty),
  2915. std::make_pair(".part_id.", KmpInt32PtrTy),
  2916. std::make_pair(".privates.", VoidPtrTy),
  2917. std::make_pair(
  2918. ".copy_fn.",
  2919. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2920. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2921. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2922. };
  2923. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2924. Params, /*OpenMPCaptureLevel=*/0);
  2925. // Mark this captured region as inlined, because we don't use outlined
  2926. // function directly.
  2927. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2928. AlwaysInlineAttr::CreateImplicit(
  2929. Context, {}, AttributeCommonInfo::AS_Keyword,
  2930. AlwaysInlineAttr::Keyword_forceinline));
  2931. Sema::CapturedParamNameType ParamsTarget[] = {
  2932. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2933. };
  2934. // Start a captured region for 'target' with no implicit parameters.
  2935. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2936. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  2937. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2938. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2939. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2940. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2941. };
  2942. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2943. // the same implicit parameters.
  2944. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2945. ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
  2946. break;
  2947. }
  2948. case OMPD_target:
  2949. case OMPD_target_simd: {
  2950. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2951. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2952. QualType KmpInt32PtrTy =
  2953. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2954. QualType Args[] = {VoidPtrTy};
  2955. FunctionProtoType::ExtProtoInfo EPI;
  2956. EPI.Variadic = true;
  2957. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2958. Sema::CapturedParamNameType Params[] = {
  2959. std::make_pair(".global_tid.", KmpInt32Ty),
  2960. std::make_pair(".part_id.", KmpInt32PtrTy),
  2961. std::make_pair(".privates.", VoidPtrTy),
  2962. std::make_pair(
  2963. ".copy_fn.",
  2964. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2965. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2966. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2967. };
  2968. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2969. Params, /*OpenMPCaptureLevel=*/0);
  2970. // Mark this captured region as inlined, because we don't use outlined
  2971. // function directly.
  2972. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2973. AlwaysInlineAttr::CreateImplicit(
  2974. Context, {}, AttributeCommonInfo::AS_Keyword,
  2975. AlwaysInlineAttr::Keyword_forceinline));
  2976. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2977. std::make_pair(StringRef(), QualType()),
  2978. /*OpenMPCaptureLevel=*/1);
  2979. break;
  2980. }
  2981. case OMPD_simd:
  2982. case OMPD_for:
  2983. case OMPD_for_simd:
  2984. case OMPD_sections:
  2985. case OMPD_section:
  2986. case OMPD_single:
  2987. case OMPD_master:
  2988. case OMPD_critical:
  2989. case OMPD_taskgroup:
  2990. case OMPD_distribute:
  2991. case OMPD_distribute_simd:
  2992. case OMPD_ordered:
  2993. case OMPD_atomic:
  2994. case OMPD_target_data: {
  2995. Sema::CapturedParamNameType Params[] = {
  2996. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2997. };
  2998. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2999. Params);
  3000. break;
  3001. }
  3002. case OMPD_task: {
  3003. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3004. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3005. QualType KmpInt32PtrTy =
  3006. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3007. QualType Args[] = {VoidPtrTy};
  3008. FunctionProtoType::ExtProtoInfo EPI;
  3009. EPI.Variadic = true;
  3010. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3011. Sema::CapturedParamNameType Params[] = {
  3012. std::make_pair(".global_tid.", KmpInt32Ty),
  3013. std::make_pair(".part_id.", KmpInt32PtrTy),
  3014. std::make_pair(".privates.", VoidPtrTy),
  3015. std::make_pair(
  3016. ".copy_fn.",
  3017. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3018. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3019. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3020. };
  3021. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3022. Params);
  3023. // Mark this captured region as inlined, because we don't use outlined
  3024. // function directly.
  3025. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3026. AlwaysInlineAttr::CreateImplicit(
  3027. Context, {}, AttributeCommonInfo::AS_Keyword,
  3028. AlwaysInlineAttr::Keyword_forceinline));
  3029. break;
  3030. }
  3031. case OMPD_taskloop:
  3032. case OMPD_taskloop_simd: {
  3033. QualType KmpInt32Ty =
  3034. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  3035. .withConst();
  3036. QualType KmpUInt64Ty =
  3037. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  3038. .withConst();
  3039. QualType KmpInt64Ty =
  3040. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  3041. .withConst();
  3042. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3043. QualType KmpInt32PtrTy =
  3044. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3045. QualType Args[] = {VoidPtrTy};
  3046. FunctionProtoType::ExtProtoInfo EPI;
  3047. EPI.Variadic = true;
  3048. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3049. Sema::CapturedParamNameType Params[] = {
  3050. std::make_pair(".global_tid.", KmpInt32Ty),
  3051. std::make_pair(".part_id.", KmpInt32PtrTy),
  3052. std::make_pair(".privates.", VoidPtrTy),
  3053. std::make_pair(
  3054. ".copy_fn.",
  3055. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3056. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3057. std::make_pair(".lb.", KmpUInt64Ty),
  3058. std::make_pair(".ub.", KmpUInt64Ty),
  3059. std::make_pair(".st.", KmpInt64Ty),
  3060. std::make_pair(".liter.", KmpInt32Ty),
  3061. std::make_pair(".reductions.", VoidPtrTy),
  3062. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3063. };
  3064. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3065. Params);
  3066. // Mark this captured region as inlined, because we don't use outlined
  3067. // function directly.
  3068. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3069. AlwaysInlineAttr::CreateImplicit(
  3070. Context, {}, AttributeCommonInfo::AS_Keyword,
  3071. AlwaysInlineAttr::Keyword_forceinline));
  3072. break;
  3073. }
  3074. case OMPD_distribute_parallel_for_simd:
  3075. case OMPD_distribute_parallel_for: {
  3076. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3077. QualType KmpInt32PtrTy =
  3078. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3079. Sema::CapturedParamNameType Params[] = {
  3080. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3081. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3082. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3083. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3084. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3085. };
  3086. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3087. Params);
  3088. break;
  3089. }
  3090. case OMPD_target_teams_distribute_parallel_for:
  3091. case OMPD_target_teams_distribute_parallel_for_simd: {
  3092. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3093. QualType KmpInt32PtrTy =
  3094. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3095. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3096. QualType Args[] = {VoidPtrTy};
  3097. FunctionProtoType::ExtProtoInfo EPI;
  3098. EPI.Variadic = true;
  3099. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3100. Sema::CapturedParamNameType Params[] = {
  3101. std::make_pair(".global_tid.", KmpInt32Ty),
  3102. std::make_pair(".part_id.", KmpInt32PtrTy),
  3103. std::make_pair(".privates.", VoidPtrTy),
  3104. std::make_pair(
  3105. ".copy_fn.",
  3106. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3107. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3108. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3109. };
  3110. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3111. Params, /*OpenMPCaptureLevel=*/0);
  3112. // Mark this captured region as inlined, because we don't use outlined
  3113. // function directly.
  3114. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3115. AlwaysInlineAttr::CreateImplicit(
  3116. Context, {}, AttributeCommonInfo::AS_Keyword,
  3117. AlwaysInlineAttr::Keyword_forceinline));
  3118. Sema::CapturedParamNameType ParamsTarget[] = {
  3119. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3120. };
  3121. // Start a captured region for 'target' with no implicit parameters.
  3122. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3123. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  3124. Sema::CapturedParamNameType ParamsTeams[] = {
  3125. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3126. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3127. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3128. };
  3129. // Start a captured region for 'target' with no implicit parameters.
  3130. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3131. ParamsTeams, /*OpenMPCaptureLevel=*/2);
  3132. Sema::CapturedParamNameType ParamsParallel[] = {
  3133. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3134. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3135. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3136. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3137. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3138. };
  3139. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3140. // the same implicit parameters.
  3141. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3142. ParamsParallel, /*OpenMPCaptureLevel=*/3);
  3143. break;
  3144. }
  3145. case OMPD_teams_distribute_parallel_for:
  3146. case OMPD_teams_distribute_parallel_for_simd: {
  3147. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3148. QualType KmpInt32PtrTy =
  3149. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3150. Sema::CapturedParamNameType ParamsTeams[] = {
  3151. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3152. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3153. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3154. };
  3155. // Start a captured region for 'target' with no implicit parameters.
  3156. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3157. ParamsTeams, /*OpenMPCaptureLevel=*/0);
  3158. Sema::CapturedParamNameType ParamsParallel[] = {
  3159. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3160. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3161. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3162. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3163. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3164. };
  3165. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3166. // the same implicit parameters.
  3167. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3168. ParamsParallel, /*OpenMPCaptureLevel=*/1);
  3169. break;
  3170. }
  3171. case OMPD_target_update:
  3172. case OMPD_target_enter_data:
  3173. case OMPD_target_exit_data: {
  3174. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3175. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3176. QualType KmpInt32PtrTy =
  3177. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3178. QualType Args[] = {VoidPtrTy};
  3179. FunctionProtoType::ExtProtoInfo EPI;
  3180. EPI.Variadic = true;
  3181. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3182. Sema::CapturedParamNameType Params[] = {
  3183. std::make_pair(".global_tid.", KmpInt32Ty),
  3184. std::make_pair(".part_id.", KmpInt32PtrTy),
  3185. std::make_pair(".privates.", VoidPtrTy),
  3186. std::make_pair(
  3187. ".copy_fn.",
  3188. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3189. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3190. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3191. };
  3192. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3193. Params);
  3194. // Mark this captured region as inlined, because we don't use outlined
  3195. // function directly.
  3196. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3197. AlwaysInlineAttr::CreateImplicit(
  3198. Context, {}, AttributeCommonInfo::AS_Keyword,
  3199. AlwaysInlineAttr::Keyword_forceinline));
  3200. break;
  3201. }
  3202. case OMPD_threadprivate:
  3203. case OMPD_allocate:
  3204. case OMPD_taskyield:
  3205. case OMPD_barrier:
  3206. case OMPD_taskwait:
  3207. case OMPD_cancellation_point:
  3208. case OMPD_cancel:
  3209. case OMPD_flush:
  3210. case OMPD_declare_reduction:
  3211. case OMPD_declare_mapper:
  3212. case OMPD_declare_simd:
  3213. case OMPD_declare_target:
  3214. case OMPD_end_declare_target:
  3215. case OMPD_requires:
  3216. case OMPD_declare_variant:
  3217. llvm_unreachable("OpenMP Directive is not allowed");
  3218. case OMPD_unknown:
  3219. llvm_unreachable("Unknown OpenMP directive");
  3220. }
  3221. }
  3222. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  3223. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3224. getOpenMPCaptureRegions(CaptureRegions, DKind);
  3225. return CaptureRegions.size();
  3226. }
  3227. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  3228. Expr *CaptureExpr, bool WithInit,
  3229. bool AsExpression) {
  3230. assert(CaptureExpr);
  3231. ASTContext &C = S.getASTContext();
  3232. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  3233. QualType Ty = Init->getType();
  3234. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  3235. if (S.getLangOpts().CPlusPlus) {
  3236. Ty = C.getLValueReferenceType(Ty);
  3237. } else {
  3238. Ty = C.getPointerType(Ty);
  3239. ExprResult Res =
  3240. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  3241. if (!Res.isUsable())
  3242. return nullptr;
  3243. Init = Res.get();
  3244. }
  3245. WithInit = true;
  3246. }
  3247. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  3248. CaptureExpr->getBeginLoc());
  3249. if (!WithInit)
  3250. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  3251. S.CurContext->addHiddenDecl(CED);
  3252. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  3253. return CED;
  3254. }
  3255. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  3256. bool WithInit) {
  3257. OMPCapturedExprDecl *CD;
  3258. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  3259. CD = cast<OMPCapturedExprDecl>(VD);
  3260. else
  3261. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  3262. /*AsExpression=*/false);
  3263. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3264. CaptureExpr->getExprLoc());
  3265. }
  3266. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  3267. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  3268. if (!Ref) {
  3269. OMPCapturedExprDecl *CD = buildCaptureDecl(
  3270. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  3271. /*WithInit=*/true, /*AsExpression=*/true);
  3272. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3273. CaptureExpr->getExprLoc());
  3274. }
  3275. ExprResult Res = Ref;
  3276. if (!S.getLangOpts().CPlusPlus &&
  3277. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  3278. Ref->getType()->isPointerType()) {
  3279. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  3280. if (!Res.isUsable())
  3281. return ExprError();
  3282. }
  3283. return S.DefaultLvalueConversion(Res.get());
  3284. }
  3285. namespace {
  3286. // OpenMP directives parsed in this section are represented as a
  3287. // CapturedStatement with an associated statement. If a syntax error
  3288. // is detected during the parsing of the associated statement, the
  3289. // compiler must abort processing and close the CapturedStatement.
  3290. //
  3291. // Combined directives such as 'target parallel' have more than one
  3292. // nested CapturedStatements. This RAII ensures that we unwind out
  3293. // of all the nested CapturedStatements when an error is found.
  3294. class CaptureRegionUnwinderRAII {
  3295. private:
  3296. Sema &S;
  3297. bool &ErrorFound;
  3298. OpenMPDirectiveKind DKind = OMPD_unknown;
  3299. public:
  3300. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  3301. OpenMPDirectiveKind DKind)
  3302. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  3303. ~CaptureRegionUnwinderRAII() {
  3304. if (ErrorFound) {
  3305. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  3306. while (--ThisCaptureLevel >= 0)
  3307. S.ActOnCapturedRegionError();
  3308. }
  3309. }
  3310. };
  3311. } // namespace
  3312. void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
  3313. // Capture variables captured by reference in lambdas for target-based
  3314. // directives.
  3315. if (!CurContext->isDependentContext() &&
  3316. (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
  3317. isOpenMPTargetDataManagementDirective(
  3318. DSAStack->getCurrentDirective()))) {
  3319. QualType Type = V->getType();
  3320. if (const auto *RD = Type.getCanonicalType()
  3321. .getNonReferenceType()
  3322. ->getAsCXXRecordDecl()) {
  3323. bool SavedForceCaptureByReferenceInTargetExecutable =
  3324. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  3325. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3326. /*V=*/true);
  3327. if (RD->isLambda()) {
  3328. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  3329. FieldDecl *ThisCapture;
  3330. RD->getCaptureFields(Captures, ThisCapture);
  3331. for (const LambdaCapture &LC : RD->captures()) {
  3332. if (LC.getCaptureKind() == LCK_ByRef) {
  3333. VarDecl *VD = LC.getCapturedVar();
  3334. DeclContext *VDC = VD->getDeclContext();
  3335. if (!VDC->Encloses(CurContext))
  3336. continue;
  3337. MarkVariableReferenced(LC.getLocation(), VD);
  3338. } else if (LC.getCaptureKind() == LCK_This) {
  3339. QualType ThisTy = getCurrentThisType();
  3340. if (!ThisTy.isNull() &&
  3341. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  3342. CheckCXXThisCapture(LC.getLocation());
  3343. }
  3344. }
  3345. }
  3346. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3347. SavedForceCaptureByReferenceInTargetExecutable);
  3348. }
  3349. }
  3350. }
  3351. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  3352. ArrayRef<OMPClause *> Clauses) {
  3353. bool ErrorFound = false;
  3354. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  3355. *this, ErrorFound, DSAStack->getCurrentDirective());
  3356. if (!S.isUsable()) {
  3357. ErrorFound = true;
  3358. return StmtError();
  3359. }
  3360. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3361. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  3362. OMPOrderedClause *OC = nullptr;
  3363. OMPScheduleClause *SC = nullptr;
  3364. SmallVector<const OMPLinearClause *, 4> LCs;
  3365. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  3366. // This is required for proper codegen.
  3367. for (OMPClause *Clause : Clauses) {
  3368. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  3369. Clause->getClauseKind() == OMPC_in_reduction) {
  3370. // Capture taskgroup task_reduction descriptors inside the tasking regions
  3371. // with the corresponding in_reduction items.
  3372. auto *IRC = cast<OMPInReductionClause>(Clause);
  3373. for (Expr *E : IRC->taskgroup_descriptors())
  3374. if (E)
  3375. MarkDeclarationsReferencedInExpr(E);
  3376. }
  3377. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  3378. Clause->getClauseKind() == OMPC_copyprivate ||
  3379. (getLangOpts().OpenMPUseTLS &&
  3380. getASTContext().getTargetInfo().isTLSSupported() &&
  3381. Clause->getClauseKind() == OMPC_copyin)) {
  3382. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  3383. // Mark all variables in private list clauses as used in inner region.
  3384. for (Stmt *VarRef : Clause->children()) {
  3385. if (auto *E = cast_or_null<Expr>(VarRef)) {
  3386. MarkDeclarationsReferencedInExpr(E);
  3387. }
  3388. }
  3389. DSAStack->setForceVarCapturing(/*V=*/false);
  3390. } else if (CaptureRegions.size() > 1 ||
  3391. CaptureRegions.back() != OMPD_unknown) {
  3392. if (auto *C = OMPClauseWithPreInit::get(Clause))
  3393. PICs.push_back(C);
  3394. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  3395. if (Expr *E = C->getPostUpdateExpr())
  3396. MarkDeclarationsReferencedInExpr(E);
  3397. }
  3398. }
  3399. if (Clause->getClauseKind() == OMPC_schedule)
  3400. SC = cast<OMPScheduleClause>(Clause);
  3401. else if (Clause->getClauseKind() == OMPC_ordered)
  3402. OC = cast<OMPOrderedClause>(Clause);
  3403. else if (Clause->getClauseKind() == OMPC_linear)
  3404. LCs.push_back(cast<OMPLinearClause>(Clause));
  3405. }
  3406. // OpenMP, 2.7.1 Loop Construct, Restrictions
  3407. // The nonmonotonic modifier cannot be specified if an ordered clause is
  3408. // specified.
  3409. if (SC &&
  3410. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  3411. SC->getSecondScheduleModifier() ==
  3412. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  3413. OC) {
  3414. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  3415. ? SC->getFirstScheduleModifierLoc()
  3416. : SC->getSecondScheduleModifierLoc(),
  3417. diag::err_omp_schedule_nonmonotonic_ordered)
  3418. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3419. ErrorFound = true;
  3420. }
  3421. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  3422. for (const OMPLinearClause *C : LCs) {
  3423. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  3424. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3425. }
  3426. ErrorFound = true;
  3427. }
  3428. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  3429. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  3430. OC->getNumForLoops()) {
  3431. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  3432. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  3433. ErrorFound = true;
  3434. }
  3435. if (ErrorFound) {
  3436. return StmtError();
  3437. }
  3438. StmtResult SR = S;
  3439. unsigned CompletedRegions = 0;
  3440. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  3441. // Mark all variables in private list clauses as used in inner region.
  3442. // Required for proper codegen of combined directives.
  3443. // TODO: add processing for other clauses.
  3444. if (ThisCaptureRegion != OMPD_unknown) {
  3445. for (const clang::OMPClauseWithPreInit *C : PICs) {
  3446. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  3447. // Find the particular capture region for the clause if the
  3448. // directive is a combined one with multiple capture regions.
  3449. // If the directive is not a combined one, the capture region
  3450. // associated with the clause is OMPD_unknown and is generated
  3451. // only once.
  3452. if (CaptureRegion == ThisCaptureRegion ||
  3453. CaptureRegion == OMPD_unknown) {
  3454. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  3455. for (Decl *D : DS->decls())
  3456. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  3457. }
  3458. }
  3459. }
  3460. }
  3461. if (++CompletedRegions == CaptureRegions.size())
  3462. DSAStack->setBodyComplete();
  3463. SR = ActOnCapturedRegionEnd(SR.get());
  3464. }
  3465. return SR;
  3466. }
  3467. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  3468. OpenMPDirectiveKind CancelRegion,
  3469. SourceLocation StartLoc) {
  3470. // CancelRegion is only needed for cancel and cancellation_point.
  3471. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  3472. return false;
  3473. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  3474. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  3475. return false;
  3476. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  3477. << getOpenMPDirectiveName(CancelRegion);
  3478. return true;
  3479. }
  3480. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  3481. OpenMPDirectiveKind CurrentRegion,
  3482. const DeclarationNameInfo &CurrentName,
  3483. OpenMPDirectiveKind CancelRegion,
  3484. SourceLocation StartLoc) {
  3485. if (Stack->getCurScope()) {
  3486. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  3487. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  3488. bool NestingProhibited = false;
  3489. bool CloseNesting = true;
  3490. bool OrphanSeen = false;
  3491. enum {
  3492. NoRecommend,
  3493. ShouldBeInParallelRegion,
  3494. ShouldBeInOrderedRegion,
  3495. ShouldBeInTargetRegion,
  3496. ShouldBeInTeamsRegion
  3497. } Recommend = NoRecommend;
  3498. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  3499. // OpenMP [2.16, Nesting of Regions]
  3500. // OpenMP constructs may not be nested inside a simd region.
  3501. // OpenMP [2.8.1,simd Construct, Restrictions]
  3502. // An ordered construct with the simd clause is the only OpenMP
  3503. // construct that can appear in the simd region.
  3504. // Allowing a SIMD construct nested in another SIMD construct is an
  3505. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  3506. // message.
  3507. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  3508. ? diag::err_omp_prohibited_region_simd
  3509. : diag::warn_omp_nesting_simd);
  3510. return CurrentRegion != OMPD_simd;
  3511. }
  3512. if (ParentRegion == OMPD_atomic) {
  3513. // OpenMP [2.16, Nesting of Regions]
  3514. // OpenMP constructs may not be nested inside an atomic region.
  3515. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  3516. return true;
  3517. }
  3518. if (CurrentRegion == OMPD_section) {
  3519. // OpenMP [2.7.2, sections Construct, Restrictions]
  3520. // Orphaned section directives are prohibited. That is, the section
  3521. // directives must appear within the sections construct and must not be
  3522. // encountered elsewhere in the sections region.
  3523. if (ParentRegion != OMPD_sections &&
  3524. ParentRegion != OMPD_parallel_sections) {
  3525. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  3526. << (ParentRegion != OMPD_unknown)
  3527. << getOpenMPDirectiveName(ParentRegion);
  3528. return true;
  3529. }
  3530. return false;
  3531. }
  3532. // Allow some constructs (except teams and cancellation constructs) to be
  3533. // orphaned (they could be used in functions, called from OpenMP regions
  3534. // with the required preconditions).
  3535. if (ParentRegion == OMPD_unknown &&
  3536. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  3537. CurrentRegion != OMPD_cancellation_point &&
  3538. CurrentRegion != OMPD_cancel)
  3539. return false;
  3540. if (CurrentRegion == OMPD_cancellation_point ||
  3541. CurrentRegion == OMPD_cancel) {
  3542. // OpenMP [2.16, Nesting of Regions]
  3543. // A cancellation point construct for which construct-type-clause is
  3544. // taskgroup must be nested inside a task construct. A cancellation
  3545. // point construct for which construct-type-clause is not taskgroup must
  3546. // be closely nested inside an OpenMP construct that matches the type
  3547. // specified in construct-type-clause.
  3548. // A cancel construct for which construct-type-clause is taskgroup must be
  3549. // nested inside a task construct. A cancel construct for which
  3550. // construct-type-clause is not taskgroup must be closely nested inside an
  3551. // OpenMP construct that matches the type specified in
  3552. // construct-type-clause.
  3553. NestingProhibited =
  3554. !((CancelRegion == OMPD_parallel &&
  3555. (ParentRegion == OMPD_parallel ||
  3556. ParentRegion == OMPD_target_parallel)) ||
  3557. (CancelRegion == OMPD_for &&
  3558. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  3559. ParentRegion == OMPD_target_parallel_for ||
  3560. ParentRegion == OMPD_distribute_parallel_for ||
  3561. ParentRegion == OMPD_teams_distribute_parallel_for ||
  3562. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  3563. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  3564. (CancelRegion == OMPD_sections &&
  3565. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  3566. ParentRegion == OMPD_parallel_sections)));
  3567. OrphanSeen = ParentRegion == OMPD_unknown;
  3568. } else if (CurrentRegion == OMPD_master) {
  3569. // OpenMP [2.16, Nesting of Regions]
  3570. // A master region may not be closely nested inside a worksharing,
  3571. // atomic, or explicit task region.
  3572. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3573. isOpenMPTaskingDirective(ParentRegion);
  3574. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  3575. // OpenMP [2.16, Nesting of Regions]
  3576. // A critical region may not be nested (closely or otherwise) inside a
  3577. // critical region with the same name. Note that this restriction is not
  3578. // sufficient to prevent deadlock.
  3579. SourceLocation PreviousCriticalLoc;
  3580. bool DeadLock = Stack->hasDirective(
  3581. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  3582. const DeclarationNameInfo &DNI,
  3583. SourceLocation Loc) {
  3584. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  3585. PreviousCriticalLoc = Loc;
  3586. return true;
  3587. }
  3588. return false;
  3589. },
  3590. false /* skip top directive */);
  3591. if (DeadLock) {
  3592. SemaRef.Diag(StartLoc,
  3593. diag::err_omp_prohibited_region_critical_same_name)
  3594. << CurrentName.getName();
  3595. if (PreviousCriticalLoc.isValid())
  3596. SemaRef.Diag(PreviousCriticalLoc,
  3597. diag::note_omp_previous_critical_region);
  3598. return true;
  3599. }
  3600. } else if (CurrentRegion == OMPD_barrier) {
  3601. // OpenMP [2.16, Nesting of Regions]
  3602. // A barrier region may not be closely nested inside a worksharing,
  3603. // explicit task, critical, ordered, atomic, or master region.
  3604. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3605. isOpenMPTaskingDirective(ParentRegion) ||
  3606. ParentRegion == OMPD_master ||
  3607. ParentRegion == OMPD_critical ||
  3608. ParentRegion == OMPD_ordered;
  3609. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3610. !isOpenMPParallelDirective(CurrentRegion) &&
  3611. !isOpenMPTeamsDirective(CurrentRegion)) {
  3612. // OpenMP [2.16, Nesting of Regions]
  3613. // A worksharing region may not be closely nested inside a worksharing,
  3614. // explicit task, critical, ordered, atomic, or master region.
  3615. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3616. isOpenMPTaskingDirective(ParentRegion) ||
  3617. ParentRegion == OMPD_master ||
  3618. ParentRegion == OMPD_critical ||
  3619. ParentRegion == OMPD_ordered;
  3620. Recommend = ShouldBeInParallelRegion;
  3621. } else if (CurrentRegion == OMPD_ordered) {
  3622. // OpenMP [2.16, Nesting of Regions]
  3623. // An ordered region may not be closely nested inside a critical,
  3624. // atomic, or explicit task region.
  3625. // An ordered region must be closely nested inside a loop region (or
  3626. // parallel loop region) with an ordered clause.
  3627. // OpenMP [2.8.1,simd Construct, Restrictions]
  3628. // An ordered construct with the simd clause is the only OpenMP construct
  3629. // that can appear in the simd region.
  3630. NestingProhibited = ParentRegion == OMPD_critical ||
  3631. isOpenMPTaskingDirective(ParentRegion) ||
  3632. !(isOpenMPSimdDirective(ParentRegion) ||
  3633. Stack->isParentOrderedRegion());
  3634. Recommend = ShouldBeInOrderedRegion;
  3635. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3636. // OpenMP [2.16, Nesting of Regions]
  3637. // If specified, a teams construct must be contained within a target
  3638. // construct.
  3639. NestingProhibited =
  3640. (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
  3641. (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
  3642. ParentRegion != OMPD_target);
  3643. OrphanSeen = ParentRegion == OMPD_unknown;
  3644. Recommend = ShouldBeInTargetRegion;
  3645. }
  3646. if (!NestingProhibited &&
  3647. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3648. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3649. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3650. // OpenMP [2.16, Nesting of Regions]
  3651. // distribute, parallel, parallel sections, parallel workshare, and the
  3652. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3653. // constructs that can be closely nested in the teams region.
  3654. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3655. !isOpenMPDistributeDirective(CurrentRegion);
  3656. Recommend = ShouldBeInParallelRegion;
  3657. }
  3658. if (!NestingProhibited &&
  3659. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3660. // OpenMP 4.5 [2.17 Nesting of Regions]
  3661. // The region associated with the distribute construct must be strictly
  3662. // nested inside a teams region
  3663. NestingProhibited =
  3664. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3665. Recommend = ShouldBeInTeamsRegion;
  3666. }
  3667. if (!NestingProhibited &&
  3668. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3669. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3670. // OpenMP 4.5 [2.17 Nesting of Regions]
  3671. // If a target, target update, target data, target enter data, or
  3672. // target exit data construct is encountered during execution of a
  3673. // target region, the behavior is unspecified.
  3674. NestingProhibited = Stack->hasDirective(
  3675. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3676. SourceLocation) {
  3677. if (isOpenMPTargetExecutionDirective(K)) {
  3678. OffendingRegion = K;
  3679. return true;
  3680. }
  3681. return false;
  3682. },
  3683. false /* don't skip top directive */);
  3684. CloseNesting = false;
  3685. }
  3686. if (NestingProhibited) {
  3687. if (OrphanSeen) {
  3688. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3689. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3690. } else {
  3691. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3692. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3693. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3694. }
  3695. return true;
  3696. }
  3697. }
  3698. return false;
  3699. }
  3700. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3701. ArrayRef<OMPClause *> Clauses,
  3702. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3703. bool ErrorFound = false;
  3704. unsigned NamedModifiersNumber = 0;
  3705. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3706. OMPD_unknown + 1);
  3707. SmallVector<SourceLocation, 4> NameModifierLoc;
  3708. for (const OMPClause *C : Clauses) {
  3709. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3710. // At most one if clause without a directive-name-modifier can appear on
  3711. // the directive.
  3712. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3713. if (FoundNameModifiers[CurNM]) {
  3714. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3715. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3716. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3717. ErrorFound = true;
  3718. } else if (CurNM != OMPD_unknown) {
  3719. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3720. ++NamedModifiersNumber;
  3721. }
  3722. FoundNameModifiers[CurNM] = IC;
  3723. if (CurNM == OMPD_unknown)
  3724. continue;
  3725. // Check if the specified name modifier is allowed for the current
  3726. // directive.
  3727. // At most one if clause with the particular directive-name-modifier can
  3728. // appear on the directive.
  3729. bool MatchFound = false;
  3730. for (auto NM : AllowedNameModifiers) {
  3731. if (CurNM == NM) {
  3732. MatchFound = true;
  3733. break;
  3734. }
  3735. }
  3736. if (!MatchFound) {
  3737. S.Diag(IC->getNameModifierLoc(),
  3738. diag::err_omp_wrong_if_directive_name_modifier)
  3739. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3740. ErrorFound = true;
  3741. }
  3742. }
  3743. }
  3744. // If any if clause on the directive includes a directive-name-modifier then
  3745. // all if clauses on the directive must include a directive-name-modifier.
  3746. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3747. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3748. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3749. diag::err_omp_no_more_if_clause);
  3750. } else {
  3751. std::string Values;
  3752. std::string Sep(", ");
  3753. unsigned AllowedCnt = 0;
  3754. unsigned TotalAllowedNum =
  3755. AllowedNameModifiers.size() - NamedModifiersNumber;
  3756. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3757. ++Cnt) {
  3758. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3759. if (!FoundNameModifiers[NM]) {
  3760. Values += "'";
  3761. Values += getOpenMPDirectiveName(NM);
  3762. Values += "'";
  3763. if (AllowedCnt + 2 == TotalAllowedNum)
  3764. Values += " or ";
  3765. else if (AllowedCnt + 1 != TotalAllowedNum)
  3766. Values += Sep;
  3767. ++AllowedCnt;
  3768. }
  3769. }
  3770. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3771. diag::err_omp_unnamed_if_clause)
  3772. << (TotalAllowedNum > 1) << Values;
  3773. }
  3774. for (SourceLocation Loc : NameModifierLoc) {
  3775. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3776. }
  3777. ErrorFound = true;
  3778. }
  3779. return ErrorFound;
  3780. }
  3781. static std::pair<ValueDecl *, bool>
  3782. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  3783. SourceRange &ERange, bool AllowArraySection = false) {
  3784. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  3785. RefExpr->containsUnexpandedParameterPack())
  3786. return std::make_pair(nullptr, true);
  3787. // OpenMP [3.1, C/C++]
  3788. // A list item is a variable name.
  3789. // OpenMP [2.9.3.3, Restrictions, p.1]
  3790. // A variable that is part of another variable (as an array or
  3791. // structure element) cannot appear in a private clause.
  3792. RefExpr = RefExpr->IgnoreParens();
  3793. enum {
  3794. NoArrayExpr = -1,
  3795. ArraySubscript = 0,
  3796. OMPArraySection = 1
  3797. } IsArrayExpr = NoArrayExpr;
  3798. if (AllowArraySection) {
  3799. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  3800. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  3801. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3802. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3803. RefExpr = Base;
  3804. IsArrayExpr = ArraySubscript;
  3805. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  3806. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  3807. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  3808. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  3809. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3810. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3811. RefExpr = Base;
  3812. IsArrayExpr = OMPArraySection;
  3813. }
  3814. }
  3815. ELoc = RefExpr->getExprLoc();
  3816. ERange = RefExpr->getSourceRange();
  3817. RefExpr = RefExpr->IgnoreParenImpCasts();
  3818. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3819. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  3820. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  3821. (S.getCurrentThisType().isNull() || !ME ||
  3822. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  3823. !isa<FieldDecl>(ME->getMemberDecl()))) {
  3824. if (IsArrayExpr != NoArrayExpr) {
  3825. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  3826. << ERange;
  3827. } else {
  3828. S.Diag(ELoc,
  3829. AllowArraySection
  3830. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  3831. : diag::err_omp_expected_var_name_member_expr)
  3832. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  3833. }
  3834. return std::make_pair(nullptr, false);
  3835. }
  3836. return std::make_pair(
  3837. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  3838. }
  3839. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  3840. ArrayRef<OMPClause *> Clauses) {
  3841. assert(!S.CurContext->isDependentContext() &&
  3842. "Expected non-dependent context.");
  3843. auto AllocateRange =
  3844. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  3845. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
  3846. DeclToCopy;
  3847. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  3848. return isOpenMPPrivate(C->getClauseKind());
  3849. });
  3850. for (OMPClause *Cl : PrivateRange) {
  3851. MutableArrayRef<Expr *>::iterator I, It, Et;
  3852. if (Cl->getClauseKind() == OMPC_private) {
  3853. auto *PC = cast<OMPPrivateClause>(Cl);
  3854. I = PC->private_copies().begin();
  3855. It = PC->varlist_begin();
  3856. Et = PC->varlist_end();
  3857. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  3858. auto *PC = cast<OMPFirstprivateClause>(Cl);
  3859. I = PC->private_copies().begin();
  3860. It = PC->varlist_begin();
  3861. Et = PC->varlist_end();
  3862. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  3863. auto *PC = cast<OMPLastprivateClause>(Cl);
  3864. I = PC->private_copies().begin();
  3865. It = PC->varlist_begin();
  3866. Et = PC->varlist_end();
  3867. } else if (Cl->getClauseKind() == OMPC_linear) {
  3868. auto *PC = cast<OMPLinearClause>(Cl);
  3869. I = PC->privates().begin();
  3870. It = PC->varlist_begin();
  3871. Et = PC->varlist_end();
  3872. } else if (Cl->getClauseKind() == OMPC_reduction) {
  3873. auto *PC = cast<OMPReductionClause>(Cl);
  3874. I = PC->privates().begin();
  3875. It = PC->varlist_begin();
  3876. Et = PC->varlist_end();
  3877. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  3878. auto *PC = cast<OMPTaskReductionClause>(Cl);
  3879. I = PC->privates().begin();
  3880. It = PC->varlist_begin();
  3881. Et = PC->varlist_end();
  3882. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  3883. auto *PC = cast<OMPInReductionClause>(Cl);
  3884. I = PC->privates().begin();
  3885. It = PC->varlist_begin();
  3886. Et = PC->varlist_end();
  3887. } else {
  3888. llvm_unreachable("Expected private clause.");
  3889. }
  3890. for (Expr *E : llvm::make_range(It, Et)) {
  3891. if (!*I) {
  3892. ++I;
  3893. continue;
  3894. }
  3895. SourceLocation ELoc;
  3896. SourceRange ERange;
  3897. Expr *SimpleRefExpr = E;
  3898. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  3899. /*AllowArraySection=*/true);
  3900. DeclToCopy.try_emplace(Res.first,
  3901. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  3902. ++I;
  3903. }
  3904. }
  3905. for (OMPClause *C : AllocateRange) {
  3906. auto *AC = cast<OMPAllocateClause>(C);
  3907. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  3908. getAllocatorKind(S, Stack, AC->getAllocator());
  3909. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  3910. // For task, taskloop or target directives, allocation requests to memory
  3911. // allocators with the trait access set to thread result in unspecified
  3912. // behavior.
  3913. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  3914. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  3915. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  3916. S.Diag(AC->getAllocator()->getExprLoc(),
  3917. diag::warn_omp_allocate_thread_on_task_target_directive)
  3918. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3919. }
  3920. for (Expr *E : AC->varlists()) {
  3921. SourceLocation ELoc;
  3922. SourceRange ERange;
  3923. Expr *SimpleRefExpr = E;
  3924. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  3925. ValueDecl *VD = Res.first;
  3926. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  3927. if (!isOpenMPPrivate(Data.CKind)) {
  3928. S.Diag(E->getExprLoc(),
  3929. diag::err_omp_expected_private_copy_for_allocate);
  3930. continue;
  3931. }
  3932. VarDecl *PrivateVD = DeclToCopy[VD];
  3933. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  3934. AllocatorKind, AC->getAllocator()))
  3935. continue;
  3936. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  3937. E->getSourceRange());
  3938. }
  3939. }
  3940. }
  3941. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3942. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3943. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3944. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3945. StmtResult Res = StmtError();
  3946. // First check CancelRegion which is then used in checkNestingOfRegions.
  3947. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3948. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3949. StartLoc))
  3950. return StmtError();
  3951. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3952. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3953. bool ErrorFound = false;
  3954. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3955. if (AStmt && !CurContext->isDependentContext()) {
  3956. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3957. // Check default data sharing attributes for referenced variables.
  3958. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3959. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3960. Stmt *S = AStmt;
  3961. while (--ThisCaptureLevel >= 0)
  3962. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3963. DSAChecker.Visit(S);
  3964. if (!isOpenMPTargetDataManagementDirective(Kind) &&
  3965. !isOpenMPTaskingDirective(Kind)) {
  3966. // Visit subcaptures to generate implicit clauses for captured vars.
  3967. auto *CS = cast<CapturedStmt>(AStmt);
  3968. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3969. getOpenMPCaptureRegions(CaptureRegions, Kind);
  3970. // Ignore outer tasking regions for target directives.
  3971. if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
  3972. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  3973. DSAChecker.visitSubCaptures(CS);
  3974. }
  3975. if (DSAChecker.isErrorFound())
  3976. return StmtError();
  3977. // Generate list of implicitly defined firstprivate variables.
  3978. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3979. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3980. DSAChecker.getImplicitFirstprivate().begin(),
  3981. DSAChecker.getImplicitFirstprivate().end());
  3982. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3983. DSAChecker.getImplicitMap().end());
  3984. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3985. for (OMPClause *C : Clauses) {
  3986. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3987. for (Expr *E : IRC->taskgroup_descriptors())
  3988. if (E)
  3989. ImplicitFirstprivates.emplace_back(E);
  3990. }
  3991. }
  3992. if (!ImplicitFirstprivates.empty()) {
  3993. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3994. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3995. SourceLocation())) {
  3996. ClausesWithImplicit.push_back(Implicit);
  3997. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3998. ImplicitFirstprivates.size();
  3999. } else {
  4000. ErrorFound = true;
  4001. }
  4002. }
  4003. if (!ImplicitMaps.empty()) {
  4004. CXXScopeSpec MapperIdScopeSpec;
  4005. DeclarationNameInfo MapperId;
  4006. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  4007. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  4008. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  4009. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  4010. ClausesWithImplicit.emplace_back(Implicit);
  4011. ErrorFound |=
  4012. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  4013. } else {
  4014. ErrorFound = true;
  4015. }
  4016. }
  4017. }
  4018. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  4019. switch (Kind) {
  4020. case OMPD_parallel:
  4021. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  4022. EndLoc);
  4023. AllowedNameModifiers.push_back(OMPD_parallel);
  4024. break;
  4025. case OMPD_simd:
  4026. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4027. VarsWithInheritedDSA);
  4028. break;
  4029. case OMPD_for:
  4030. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4031. VarsWithInheritedDSA);
  4032. break;
  4033. case OMPD_for_simd:
  4034. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4035. EndLoc, VarsWithInheritedDSA);
  4036. break;
  4037. case OMPD_sections:
  4038. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4039. EndLoc);
  4040. break;
  4041. case OMPD_section:
  4042. assert(ClausesWithImplicit.empty() &&
  4043. "No clauses are allowed for 'omp section' directive");
  4044. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  4045. break;
  4046. case OMPD_single:
  4047. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  4048. EndLoc);
  4049. break;
  4050. case OMPD_master:
  4051. assert(ClausesWithImplicit.empty() &&
  4052. "No clauses are allowed for 'omp master' directive");
  4053. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  4054. break;
  4055. case OMPD_critical:
  4056. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  4057. StartLoc, EndLoc);
  4058. break;
  4059. case OMPD_parallel_for:
  4060. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  4061. EndLoc, VarsWithInheritedDSA);
  4062. AllowedNameModifiers.push_back(OMPD_parallel);
  4063. break;
  4064. case OMPD_parallel_for_simd:
  4065. Res = ActOnOpenMPParallelForSimdDirective(
  4066. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4067. AllowedNameModifiers.push_back(OMPD_parallel);
  4068. break;
  4069. case OMPD_parallel_sections:
  4070. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  4071. StartLoc, EndLoc);
  4072. AllowedNameModifiers.push_back(OMPD_parallel);
  4073. break;
  4074. case OMPD_task:
  4075. Res =
  4076. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4077. AllowedNameModifiers.push_back(OMPD_task);
  4078. break;
  4079. case OMPD_taskyield:
  4080. assert(ClausesWithImplicit.empty() &&
  4081. "No clauses are allowed for 'omp taskyield' directive");
  4082. assert(AStmt == nullptr &&
  4083. "No associated statement allowed for 'omp taskyield' directive");
  4084. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  4085. break;
  4086. case OMPD_barrier:
  4087. assert(ClausesWithImplicit.empty() &&
  4088. "No clauses are allowed for 'omp barrier' directive");
  4089. assert(AStmt == nullptr &&
  4090. "No associated statement allowed for 'omp barrier' directive");
  4091. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  4092. break;
  4093. case OMPD_taskwait:
  4094. assert(ClausesWithImplicit.empty() &&
  4095. "No clauses are allowed for 'omp taskwait' directive");
  4096. assert(AStmt == nullptr &&
  4097. "No associated statement allowed for 'omp taskwait' directive");
  4098. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  4099. break;
  4100. case OMPD_taskgroup:
  4101. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  4102. EndLoc);
  4103. break;
  4104. case OMPD_flush:
  4105. assert(AStmt == nullptr &&
  4106. "No associated statement allowed for 'omp flush' directive");
  4107. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  4108. break;
  4109. case OMPD_ordered:
  4110. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  4111. EndLoc);
  4112. break;
  4113. case OMPD_atomic:
  4114. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  4115. EndLoc);
  4116. break;
  4117. case OMPD_teams:
  4118. Res =
  4119. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4120. break;
  4121. case OMPD_target:
  4122. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  4123. EndLoc);
  4124. AllowedNameModifiers.push_back(OMPD_target);
  4125. break;
  4126. case OMPD_target_parallel:
  4127. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  4128. StartLoc, EndLoc);
  4129. AllowedNameModifiers.push_back(OMPD_target);
  4130. AllowedNameModifiers.push_back(OMPD_parallel);
  4131. break;
  4132. case OMPD_target_parallel_for:
  4133. Res = ActOnOpenMPTargetParallelForDirective(
  4134. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4135. AllowedNameModifiers.push_back(OMPD_target);
  4136. AllowedNameModifiers.push_back(OMPD_parallel);
  4137. break;
  4138. case OMPD_cancellation_point:
  4139. assert(ClausesWithImplicit.empty() &&
  4140. "No clauses are allowed for 'omp cancellation point' directive");
  4141. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  4142. "cancellation point' directive");
  4143. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  4144. break;
  4145. case OMPD_cancel:
  4146. assert(AStmt == nullptr &&
  4147. "No associated statement allowed for 'omp cancel' directive");
  4148. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  4149. CancelRegion);
  4150. AllowedNameModifiers.push_back(OMPD_cancel);
  4151. break;
  4152. case OMPD_target_data:
  4153. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  4154. EndLoc);
  4155. AllowedNameModifiers.push_back(OMPD_target_data);
  4156. break;
  4157. case OMPD_target_enter_data:
  4158. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  4159. EndLoc, AStmt);
  4160. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  4161. break;
  4162. case OMPD_target_exit_data:
  4163. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  4164. EndLoc, AStmt);
  4165. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  4166. break;
  4167. case OMPD_taskloop:
  4168. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  4169. EndLoc, VarsWithInheritedDSA);
  4170. AllowedNameModifiers.push_back(OMPD_taskloop);
  4171. break;
  4172. case OMPD_taskloop_simd:
  4173. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4174. EndLoc, VarsWithInheritedDSA);
  4175. AllowedNameModifiers.push_back(OMPD_taskloop);
  4176. break;
  4177. case OMPD_distribute:
  4178. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  4179. EndLoc, VarsWithInheritedDSA);
  4180. break;
  4181. case OMPD_target_update:
  4182. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  4183. EndLoc, AStmt);
  4184. AllowedNameModifiers.push_back(OMPD_target_update);
  4185. break;
  4186. case OMPD_distribute_parallel_for:
  4187. Res = ActOnOpenMPDistributeParallelForDirective(
  4188. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4189. AllowedNameModifiers.push_back(OMPD_parallel);
  4190. break;
  4191. case OMPD_distribute_parallel_for_simd:
  4192. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  4193. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4194. AllowedNameModifiers.push_back(OMPD_parallel);
  4195. break;
  4196. case OMPD_distribute_simd:
  4197. Res = ActOnOpenMPDistributeSimdDirective(
  4198. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4199. break;
  4200. case OMPD_target_parallel_for_simd:
  4201. Res = ActOnOpenMPTargetParallelForSimdDirective(
  4202. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4203. AllowedNameModifiers.push_back(OMPD_target);
  4204. AllowedNameModifiers.push_back(OMPD_parallel);
  4205. break;
  4206. case OMPD_target_simd:
  4207. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4208. EndLoc, VarsWithInheritedDSA);
  4209. AllowedNameModifiers.push_back(OMPD_target);
  4210. break;
  4211. case OMPD_teams_distribute:
  4212. Res = ActOnOpenMPTeamsDistributeDirective(
  4213. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4214. break;
  4215. case OMPD_teams_distribute_simd:
  4216. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  4217. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4218. break;
  4219. case OMPD_teams_distribute_parallel_for_simd:
  4220. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  4221. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4222. AllowedNameModifiers.push_back(OMPD_parallel);
  4223. break;
  4224. case OMPD_teams_distribute_parallel_for:
  4225. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  4226. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4227. AllowedNameModifiers.push_back(OMPD_parallel);
  4228. break;
  4229. case OMPD_target_teams:
  4230. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4231. EndLoc);
  4232. AllowedNameModifiers.push_back(OMPD_target);
  4233. break;
  4234. case OMPD_target_teams_distribute:
  4235. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  4236. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4237. AllowedNameModifiers.push_back(OMPD_target);
  4238. break;
  4239. case OMPD_target_teams_distribute_parallel_for:
  4240. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  4241. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4242. AllowedNameModifiers.push_back(OMPD_target);
  4243. AllowedNameModifiers.push_back(OMPD_parallel);
  4244. break;
  4245. case OMPD_target_teams_distribute_parallel_for_simd:
  4246. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  4247. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4248. AllowedNameModifiers.push_back(OMPD_target);
  4249. AllowedNameModifiers.push_back(OMPD_parallel);
  4250. break;
  4251. case OMPD_target_teams_distribute_simd:
  4252. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  4253. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4254. AllowedNameModifiers.push_back(OMPD_target);
  4255. break;
  4256. case OMPD_declare_target:
  4257. case OMPD_end_declare_target:
  4258. case OMPD_threadprivate:
  4259. case OMPD_allocate:
  4260. case OMPD_declare_reduction:
  4261. case OMPD_declare_mapper:
  4262. case OMPD_declare_simd:
  4263. case OMPD_requires:
  4264. case OMPD_declare_variant:
  4265. llvm_unreachable("OpenMP Directive is not allowed");
  4266. case OMPD_unknown:
  4267. llvm_unreachable("Unknown OpenMP directive");
  4268. }
  4269. ErrorFound = Res.isInvalid() || ErrorFound;
  4270. // Check variables in the clauses if default(none) was specified.
  4271. if (DSAStack->getDefaultDSA() == DSA_none) {
  4272. DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
  4273. for (OMPClause *C : Clauses) {
  4274. switch (C->getClauseKind()) {
  4275. case OMPC_num_threads:
  4276. case OMPC_dist_schedule:
  4277. // Do not analyse if no parent teams directive.
  4278. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
  4279. break;
  4280. continue;
  4281. case OMPC_if:
  4282. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
  4283. cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
  4284. break;
  4285. continue;
  4286. case OMPC_schedule:
  4287. break;
  4288. case OMPC_ordered:
  4289. case OMPC_device:
  4290. case OMPC_num_teams:
  4291. case OMPC_thread_limit:
  4292. case OMPC_priority:
  4293. case OMPC_grainsize:
  4294. case OMPC_num_tasks:
  4295. case OMPC_hint:
  4296. case OMPC_collapse:
  4297. case OMPC_safelen:
  4298. case OMPC_simdlen:
  4299. case OMPC_final:
  4300. case OMPC_default:
  4301. case OMPC_proc_bind:
  4302. case OMPC_private:
  4303. case OMPC_firstprivate:
  4304. case OMPC_lastprivate:
  4305. case OMPC_shared:
  4306. case OMPC_reduction:
  4307. case OMPC_task_reduction:
  4308. case OMPC_in_reduction:
  4309. case OMPC_linear:
  4310. case OMPC_aligned:
  4311. case OMPC_copyin:
  4312. case OMPC_copyprivate:
  4313. case OMPC_nowait:
  4314. case OMPC_untied:
  4315. case OMPC_mergeable:
  4316. case OMPC_allocate:
  4317. case OMPC_read:
  4318. case OMPC_write:
  4319. case OMPC_update:
  4320. case OMPC_capture:
  4321. case OMPC_seq_cst:
  4322. case OMPC_depend:
  4323. case OMPC_threads:
  4324. case OMPC_simd:
  4325. case OMPC_map:
  4326. case OMPC_nogroup:
  4327. case OMPC_defaultmap:
  4328. case OMPC_to:
  4329. case OMPC_from:
  4330. case OMPC_use_device_ptr:
  4331. case OMPC_is_device_ptr:
  4332. continue;
  4333. case OMPC_allocator:
  4334. case OMPC_flush:
  4335. case OMPC_threadprivate:
  4336. case OMPC_uniform:
  4337. case OMPC_unknown:
  4338. case OMPC_unified_address:
  4339. case OMPC_unified_shared_memory:
  4340. case OMPC_reverse_offload:
  4341. case OMPC_dynamic_allocators:
  4342. case OMPC_atomic_default_mem_order:
  4343. case OMPC_device_type:
  4344. case OMPC_match:
  4345. llvm_unreachable("Unexpected clause");
  4346. }
  4347. for (Stmt *CC : C->children()) {
  4348. if (CC)
  4349. DSAChecker.Visit(CC);
  4350. }
  4351. }
  4352. for (auto &P : DSAChecker.getVarsWithInheritedDSA())
  4353. VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
  4354. }
  4355. for (const auto &P : VarsWithInheritedDSA) {
  4356. if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
  4357. continue;
  4358. ErrorFound = true;
  4359. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  4360. << P.first << P.second->getSourceRange();
  4361. Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
  4362. }
  4363. if (!AllowedNameModifiers.empty())
  4364. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  4365. ErrorFound;
  4366. if (ErrorFound)
  4367. return StmtError();
  4368. if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
  4369. Res.getAs<OMPExecutableDirective>()
  4370. ->getStructuredBlock()
  4371. ->setIsOMPStructuredBlock(true);
  4372. }
  4373. if (!CurContext->isDependentContext() &&
  4374. isOpenMPTargetExecutionDirective(Kind) &&
  4375. !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  4376. DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
  4377. DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
  4378. DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
  4379. // Register target to DSA Stack.
  4380. DSAStack->addTargetDirLocation(StartLoc);
  4381. }
  4382. return Res;
  4383. }
  4384. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  4385. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  4386. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  4387. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  4388. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  4389. assert(Aligneds.size() == Alignments.size());
  4390. assert(Linears.size() == LinModifiers.size());
  4391. assert(Linears.size() == Steps.size());
  4392. if (!DG || DG.get().isNull())
  4393. return DeclGroupPtrTy();
  4394. const int SimdId = 0;
  4395. if (!DG.get().isSingleDecl()) {
  4396. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4397. << SimdId;
  4398. return DG;
  4399. }
  4400. Decl *ADecl = DG.get().getSingleDecl();
  4401. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4402. ADecl = FTD->getTemplatedDecl();
  4403. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4404. if (!FD) {
  4405. Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
  4406. return DeclGroupPtrTy();
  4407. }
  4408. // OpenMP [2.8.2, declare simd construct, Description]
  4409. // The parameter of the simdlen clause must be a constant positive integer
  4410. // expression.
  4411. ExprResult SL;
  4412. if (Simdlen)
  4413. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  4414. // OpenMP [2.8.2, declare simd construct, Description]
  4415. // The special this pointer can be used as if was one of the arguments to the
  4416. // function in any of the linear, aligned, or uniform clauses.
  4417. // The uniform clause declares one or more arguments to have an invariant
  4418. // value for all concurrent invocations of the function in the execution of a
  4419. // single SIMD loop.
  4420. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  4421. const Expr *UniformedLinearThis = nullptr;
  4422. for (const Expr *E : Uniforms) {
  4423. E = E->IgnoreParenImpCasts();
  4424. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4425. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  4426. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4427. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4428. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  4429. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  4430. continue;
  4431. }
  4432. if (isa<CXXThisExpr>(E)) {
  4433. UniformedLinearThis = E;
  4434. continue;
  4435. }
  4436. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4437. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4438. }
  4439. // OpenMP [2.8.2, declare simd construct, Description]
  4440. // The aligned clause declares that the object to which each list item points
  4441. // is aligned to the number of bytes expressed in the optional parameter of
  4442. // the aligned clause.
  4443. // The special this pointer can be used as if was one of the arguments to the
  4444. // function in any of the linear, aligned, or uniform clauses.
  4445. // The type of list items appearing in the aligned clause must be array,
  4446. // pointer, reference to array, or reference to pointer.
  4447. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  4448. const Expr *AlignedThis = nullptr;
  4449. for (const Expr *E : Aligneds) {
  4450. E = E->IgnoreParenImpCasts();
  4451. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4452. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4453. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4454. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4455. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4456. ->getCanonicalDecl() == CanonPVD) {
  4457. // OpenMP [2.8.1, simd construct, Restrictions]
  4458. // A list-item cannot appear in more than one aligned clause.
  4459. if (AlignedArgs.count(CanonPVD) > 0) {
  4460. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4461. << 1 << E->getSourceRange();
  4462. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  4463. diag::note_omp_explicit_dsa)
  4464. << getOpenMPClauseName(OMPC_aligned);
  4465. continue;
  4466. }
  4467. AlignedArgs[CanonPVD] = E;
  4468. QualType QTy = PVD->getType()
  4469. .getNonReferenceType()
  4470. .getUnqualifiedType()
  4471. .getCanonicalType();
  4472. const Type *Ty = QTy.getTypePtrOrNull();
  4473. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  4474. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  4475. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  4476. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  4477. }
  4478. continue;
  4479. }
  4480. }
  4481. if (isa<CXXThisExpr>(E)) {
  4482. if (AlignedThis) {
  4483. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4484. << 2 << E->getSourceRange();
  4485. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4486. << getOpenMPClauseName(OMPC_aligned);
  4487. }
  4488. AlignedThis = E;
  4489. continue;
  4490. }
  4491. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4492. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4493. }
  4494. // The optional parameter of the aligned clause, alignment, must be a constant
  4495. // positive integer expression. If no optional parameter is specified,
  4496. // implementation-defined default alignments for SIMD instructions on the
  4497. // target platforms are assumed.
  4498. SmallVector<const Expr *, 4> NewAligns;
  4499. for (Expr *E : Alignments) {
  4500. ExprResult Align;
  4501. if (E)
  4502. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  4503. NewAligns.push_back(Align.get());
  4504. }
  4505. // OpenMP [2.8.2, declare simd construct, Description]
  4506. // The linear clause declares one or more list items to be private to a SIMD
  4507. // lane and to have a linear relationship with respect to the iteration space
  4508. // of a loop.
  4509. // The special this pointer can be used as if was one of the arguments to the
  4510. // function in any of the linear, aligned, or uniform clauses.
  4511. // When a linear-step expression is specified in a linear clause it must be
  4512. // either a constant integer expression or an integer-typed parameter that is
  4513. // specified in a uniform clause on the directive.
  4514. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  4515. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  4516. auto MI = LinModifiers.begin();
  4517. for (const Expr *E : Linears) {
  4518. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  4519. ++MI;
  4520. E = E->IgnoreParenImpCasts();
  4521. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4522. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4523. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4524. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4525. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4526. ->getCanonicalDecl() == CanonPVD) {
  4527. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  4528. // A list-item cannot appear in more than one linear clause.
  4529. if (LinearArgs.count(CanonPVD) > 0) {
  4530. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4531. << getOpenMPClauseName(OMPC_linear)
  4532. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  4533. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  4534. diag::note_omp_explicit_dsa)
  4535. << getOpenMPClauseName(OMPC_linear);
  4536. continue;
  4537. }
  4538. // Each argument can appear in at most one uniform or linear clause.
  4539. if (UniformedArgs.count(CanonPVD) > 0) {
  4540. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4541. << getOpenMPClauseName(OMPC_linear)
  4542. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  4543. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  4544. diag::note_omp_explicit_dsa)
  4545. << getOpenMPClauseName(OMPC_uniform);
  4546. continue;
  4547. }
  4548. LinearArgs[CanonPVD] = E;
  4549. if (E->isValueDependent() || E->isTypeDependent() ||
  4550. E->isInstantiationDependent() ||
  4551. E->containsUnexpandedParameterPack())
  4552. continue;
  4553. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  4554. PVD->getOriginalType());
  4555. continue;
  4556. }
  4557. }
  4558. if (isa<CXXThisExpr>(E)) {
  4559. if (UniformedLinearThis) {
  4560. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4561. << getOpenMPClauseName(OMPC_linear)
  4562. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  4563. << E->getSourceRange();
  4564. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4565. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  4566. : OMPC_linear);
  4567. continue;
  4568. }
  4569. UniformedLinearThis = E;
  4570. if (E->isValueDependent() || E->isTypeDependent() ||
  4571. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4572. continue;
  4573. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  4574. E->getType());
  4575. continue;
  4576. }
  4577. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4578. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4579. }
  4580. Expr *Step = nullptr;
  4581. Expr *NewStep = nullptr;
  4582. SmallVector<Expr *, 4> NewSteps;
  4583. for (Expr *E : Steps) {
  4584. // Skip the same step expression, it was checked already.
  4585. if (Step == E || !E) {
  4586. NewSteps.push_back(E ? NewStep : nullptr);
  4587. continue;
  4588. }
  4589. Step = E;
  4590. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  4591. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4592. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4593. if (UniformedArgs.count(CanonPVD) == 0) {
  4594. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  4595. << Step->getSourceRange();
  4596. } else if (E->isValueDependent() || E->isTypeDependent() ||
  4597. E->isInstantiationDependent() ||
  4598. E->containsUnexpandedParameterPack() ||
  4599. CanonPVD->getType()->hasIntegerRepresentation()) {
  4600. NewSteps.push_back(Step);
  4601. } else {
  4602. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  4603. << Step->getSourceRange();
  4604. }
  4605. continue;
  4606. }
  4607. NewStep = Step;
  4608. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  4609. !Step->isInstantiationDependent() &&
  4610. !Step->containsUnexpandedParameterPack()) {
  4611. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  4612. .get();
  4613. if (NewStep)
  4614. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  4615. }
  4616. NewSteps.push_back(NewStep);
  4617. }
  4618. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  4619. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  4620. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  4621. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  4622. const_cast<Expr **>(Linears.data()), Linears.size(),
  4623. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  4624. NewSteps.data(), NewSteps.size(), SR);
  4625. ADecl->addAttr(NewAttr);
  4626. return DG;
  4627. }
  4628. Optional<std::pair<FunctionDecl *, Expr *>>
  4629. Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
  4630. Expr *VariantRef, SourceRange SR) {
  4631. if (!DG || DG.get().isNull())
  4632. return None;
  4633. const int VariantId = 1;
  4634. // Must be applied only to single decl.
  4635. if (!DG.get().isSingleDecl()) {
  4636. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4637. << VariantId << SR;
  4638. return None;
  4639. }
  4640. Decl *ADecl = DG.get().getSingleDecl();
  4641. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4642. ADecl = FTD->getTemplatedDecl();
  4643. // Decl must be a function.
  4644. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4645. if (!FD) {
  4646. Diag(ADecl->getLocation(), diag::err_omp_function_expected)
  4647. << VariantId << SR;
  4648. return None;
  4649. }
  4650. auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
  4651. return FD->hasAttrs() &&
  4652. (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
  4653. FD->hasAttr<TargetAttr>());
  4654. };
  4655. // OpenMP is not compatible with CPU-specific attributes.
  4656. if (HasMultiVersionAttributes(FD)) {
  4657. Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
  4658. << SR;
  4659. return None;
  4660. }
  4661. // Allow #pragma omp declare variant only if the function is not used.
  4662. if (FD->isUsed(false))
  4663. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
  4664. << FD->getLocation();
  4665. // Check if the function was emitted already.
  4666. const FunctionDecl *Definition;
  4667. if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
  4668. (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
  4669. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
  4670. << FD->getLocation();
  4671. // The VariantRef must point to function.
  4672. if (!VariantRef) {
  4673. Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
  4674. return None;
  4675. }
  4676. // Do not check templates, wait until instantiation.
  4677. if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
  4678. VariantRef->containsUnexpandedParameterPack() ||
  4679. VariantRef->isInstantiationDependent() || FD->isDependentContext())
  4680. return std::make_pair(FD, VariantRef);
  4681. // Convert VariantRef expression to the type of the original function to
  4682. // resolve possible conflicts.
  4683. ExprResult VariantRefCast;
  4684. if (LangOpts.CPlusPlus) {
  4685. QualType FnPtrType;
  4686. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  4687. if (Method && !Method->isStatic()) {
  4688. const Type *ClassType =
  4689. Context.getTypeDeclType(Method->getParent()).getTypePtr();
  4690. FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
  4691. ExprResult ER;
  4692. {
  4693. // Build adrr_of unary op to correctly handle type checks for member
  4694. // functions.
  4695. Sema::TentativeAnalysisScope Trap(*this);
  4696. ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
  4697. VariantRef);
  4698. }
  4699. if (!ER.isUsable()) {
  4700. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4701. << VariantId << VariantRef->getSourceRange();
  4702. return None;
  4703. }
  4704. VariantRef = ER.get();
  4705. } else {
  4706. FnPtrType = Context.getPointerType(FD->getType());
  4707. }
  4708. ImplicitConversionSequence ICS =
  4709. TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
  4710. /*SuppressUserConversions=*/false,
  4711. /*AllowExplicit=*/false,
  4712. /*InOverloadResolution=*/false,
  4713. /*CStyle=*/false,
  4714. /*AllowObjCWritebackConversion=*/false);
  4715. if (ICS.isFailure()) {
  4716. Diag(VariantRef->getExprLoc(),
  4717. diag::err_omp_declare_variant_incompat_types)
  4718. << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
  4719. return None;
  4720. }
  4721. VariantRefCast = PerformImplicitConversion(
  4722. VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
  4723. if (!VariantRefCast.isUsable())
  4724. return None;
  4725. // Drop previously built artificial addr_of unary op for member functions.
  4726. if (Method && !Method->isStatic()) {
  4727. Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
  4728. if (auto *UO = dyn_cast<UnaryOperator>(
  4729. PossibleAddrOfVariantRef->IgnoreImplicit()))
  4730. VariantRefCast = UO->getSubExpr();
  4731. }
  4732. } else {
  4733. VariantRefCast = VariantRef;
  4734. }
  4735. ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
  4736. if (!ER.isUsable() ||
  4737. !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
  4738. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4739. << VariantId << VariantRef->getSourceRange();
  4740. return None;
  4741. }
  4742. // The VariantRef must point to function.
  4743. auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
  4744. if (!DRE) {
  4745. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4746. << VariantId << VariantRef->getSourceRange();
  4747. return None;
  4748. }
  4749. auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
  4750. if (!NewFD) {
  4751. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4752. << VariantId << VariantRef->getSourceRange();
  4753. return None;
  4754. }
  4755. // Check if variant function is not marked with declare variant directive.
  4756. if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
  4757. Diag(VariantRef->getExprLoc(),
  4758. diag::warn_omp_declare_variant_marked_as_declare_variant)
  4759. << VariantRef->getSourceRange();
  4760. SourceRange SR =
  4761. NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
  4762. Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
  4763. return None;
  4764. }
  4765. enum DoesntSupport {
  4766. VirtFuncs = 1,
  4767. Constructors = 3,
  4768. Destructors = 4,
  4769. DeletedFuncs = 5,
  4770. DefaultedFuncs = 6,
  4771. ConstexprFuncs = 7,
  4772. ConstevalFuncs = 8,
  4773. };
  4774. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  4775. if (CXXFD->isVirtual()) {
  4776. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4777. << VirtFuncs;
  4778. return None;
  4779. }
  4780. if (isa<CXXConstructorDecl>(FD)) {
  4781. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4782. << Constructors;
  4783. return None;
  4784. }
  4785. if (isa<CXXDestructorDecl>(FD)) {
  4786. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4787. << Destructors;
  4788. return None;
  4789. }
  4790. }
  4791. if (FD->isDeleted()) {
  4792. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4793. << DeletedFuncs;
  4794. return None;
  4795. }
  4796. if (FD->isDefaulted()) {
  4797. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4798. << DefaultedFuncs;
  4799. return None;
  4800. }
  4801. if (FD->isConstexpr()) {
  4802. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4803. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  4804. return None;
  4805. }
  4806. // Check general compatibility.
  4807. if (areMultiversionVariantFunctionsCompatible(
  4808. FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
  4809. PartialDiagnosticAt(
  4810. SR.getBegin(),
  4811. PDiag(diag::note_omp_declare_variant_specified_here) << SR),
  4812. PartialDiagnosticAt(
  4813. VariantRef->getExprLoc(),
  4814. PDiag(diag::err_omp_declare_variant_doesnt_support)),
  4815. PartialDiagnosticAt(VariantRef->getExprLoc(),
  4816. PDiag(diag::err_omp_declare_variant_diff)
  4817. << FD->getLocation()),
  4818. /*TemplatesSupported=*/true, /*ConstexprSupported=*/false))
  4819. return None;
  4820. return std::make_pair(FD, cast<Expr>(DRE));
  4821. }
  4822. void Sema::ActOnOpenMPDeclareVariantDirective(
  4823. FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
  4824. const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
  4825. if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
  4826. Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
  4827. return;
  4828. Expr *Score = nullptr;
  4829. OMPDeclareVariantAttr::ScoreType ST = OMPDeclareVariantAttr::ScoreUnknown;
  4830. if (Data.CtxScore.isUsable()) {
  4831. ST = OMPDeclareVariantAttr::ScoreSpecified;
  4832. Score = Data.CtxScore.get();
  4833. if (!Score->isTypeDependent() && !Score->isValueDependent() &&
  4834. !Score->isInstantiationDependent() &&
  4835. !Score->containsUnexpandedParameterPack()) {
  4836. llvm::APSInt Result;
  4837. ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
  4838. if (ICE.isInvalid())
  4839. return;
  4840. }
  4841. }
  4842. auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
  4843. Context, VariantRef, Score, Data.CtxSet, ST, Data.Ctx, Data.ImplVendor,
  4844. SR);
  4845. FD->addAttr(NewAttr);
  4846. }
  4847. void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
  4848. FunctionDecl *Func,
  4849. bool MightBeOdrUse) {
  4850. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  4851. if (!Func->isDependentContext() && Func->hasAttrs()) {
  4852. for (OMPDeclareVariantAttr *A :
  4853. Func->specific_attrs<OMPDeclareVariantAttr>()) {
  4854. // TODO: add checks for active OpenMP context where possible.
  4855. Expr *VariantRef = A->getVariantFuncRef();
  4856. auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
  4857. auto *F = cast<FunctionDecl>(DRE->getDecl());
  4858. if (!F->isDefined() && F->isTemplateInstantiation())
  4859. InstantiateFunctionDefinition(Loc, F->getFirstDecl());
  4860. MarkFunctionReferenced(Loc, F, MightBeOdrUse);
  4861. }
  4862. }
  4863. }
  4864. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  4865. Stmt *AStmt,
  4866. SourceLocation StartLoc,
  4867. SourceLocation EndLoc) {
  4868. if (!AStmt)
  4869. return StmtError();
  4870. auto *CS = cast<CapturedStmt>(AStmt);
  4871. // 1.2.2 OpenMP Language Terminology
  4872. // Structured block - An executable statement with a single entry at the
  4873. // top and a single exit at the bottom.
  4874. // The point of exit cannot be a branch out of the structured block.
  4875. // longjmp() and throw() must not violate the entry/exit criteria.
  4876. CS->getCapturedDecl()->setNothrow();
  4877. setFunctionHasBranchProtectedScope();
  4878. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4879. DSAStack->isCancelRegion());
  4880. }
  4881. namespace {
  4882. /// Iteration space of a single for loop.
  4883. struct LoopIterationSpace final {
  4884. /// True if the condition operator is the strict compare operator (<, > or
  4885. /// !=).
  4886. bool IsStrictCompare = false;
  4887. /// Condition of the loop.
  4888. Expr *PreCond = nullptr;
  4889. /// This expression calculates the number of iterations in the loop.
  4890. /// It is always possible to calculate it before starting the loop.
  4891. Expr *NumIterations = nullptr;
  4892. /// The loop counter variable.
  4893. Expr *CounterVar = nullptr;
  4894. /// Private loop counter variable.
  4895. Expr *PrivateCounterVar = nullptr;
  4896. /// This is initializer for the initial value of #CounterVar.
  4897. Expr *CounterInit = nullptr;
  4898. /// This is step for the #CounterVar used to generate its update:
  4899. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4900. Expr *CounterStep = nullptr;
  4901. /// Should step be subtracted?
  4902. bool Subtract = false;
  4903. /// Source range of the loop init.
  4904. SourceRange InitSrcRange;
  4905. /// Source range of the loop condition.
  4906. SourceRange CondSrcRange;
  4907. /// Source range of the loop increment.
  4908. SourceRange IncSrcRange;
  4909. /// Minimum value that can have the loop control variable. Used to support
  4910. /// non-rectangular loops. Applied only for LCV with the non-iterator types,
  4911. /// since only such variables can be used in non-loop invariant expressions.
  4912. Expr *MinValue = nullptr;
  4913. /// Maximum value that can have the loop control variable. Used to support
  4914. /// non-rectangular loops. Applied only for LCV with the non-iterator type,
  4915. /// since only such variables can be used in non-loop invariant expressions.
  4916. Expr *MaxValue = nullptr;
  4917. /// true, if the lower bound depends on the outer loop control var.
  4918. bool IsNonRectangularLB = false;
  4919. /// true, if the upper bound depends on the outer loop control var.
  4920. bool IsNonRectangularUB = false;
  4921. /// Index of the loop this loop depends on and forms non-rectangular loop
  4922. /// nest.
  4923. unsigned LoopDependentIdx = 0;
  4924. /// Final condition for the non-rectangular loop nest support. It is used to
  4925. /// check that the number of iterations for this particular counter must be
  4926. /// finished.
  4927. Expr *FinalCondition = nullptr;
  4928. };
  4929. /// Helper class for checking canonical form of the OpenMP loops and
  4930. /// extracting iteration space of each loop in the loop nest, that will be used
  4931. /// for IR generation.
  4932. class OpenMPIterationSpaceChecker {
  4933. /// Reference to Sema.
  4934. Sema &SemaRef;
  4935. /// Data-sharing stack.
  4936. DSAStackTy &Stack;
  4937. /// A location for diagnostics (when there is no some better location).
  4938. SourceLocation DefaultLoc;
  4939. /// A location for diagnostics (when increment is not compatible).
  4940. SourceLocation ConditionLoc;
  4941. /// A source location for referring to loop init later.
  4942. SourceRange InitSrcRange;
  4943. /// A source location for referring to condition later.
  4944. SourceRange ConditionSrcRange;
  4945. /// A source location for referring to increment later.
  4946. SourceRange IncrementSrcRange;
  4947. /// Loop variable.
  4948. ValueDecl *LCDecl = nullptr;
  4949. /// Reference to loop variable.
  4950. Expr *LCRef = nullptr;
  4951. /// Lower bound (initializer for the var).
  4952. Expr *LB = nullptr;
  4953. /// Upper bound.
  4954. Expr *UB = nullptr;
  4955. /// Loop step (increment).
  4956. Expr *Step = nullptr;
  4957. /// This flag is true when condition is one of:
  4958. /// Var < UB
  4959. /// Var <= UB
  4960. /// UB > Var
  4961. /// UB >= Var
  4962. /// This will have no value when the condition is !=
  4963. llvm::Optional<bool> TestIsLessOp;
  4964. /// This flag is true when condition is strict ( < or > ).
  4965. bool TestIsStrictOp = false;
  4966. /// This flag is true when step is subtracted on each iteration.
  4967. bool SubtractStep = false;
  4968. /// The outer loop counter this loop depends on (if any).
  4969. const ValueDecl *DepDecl = nullptr;
  4970. /// Contains number of loop (starts from 1) on which loop counter init
  4971. /// expression of this loop depends on.
  4972. Optional<unsigned> InitDependOnLC;
  4973. /// Contains number of loop (starts from 1) on which loop counter condition
  4974. /// expression of this loop depends on.
  4975. Optional<unsigned> CondDependOnLC;
  4976. /// Checks if the provide statement depends on the loop counter.
  4977. Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
  4978. /// Original condition required for checking of the exit condition for
  4979. /// non-rectangular loop.
  4980. Expr *Condition = nullptr;
  4981. public:
  4982. OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
  4983. SourceLocation DefaultLoc)
  4984. : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
  4985. ConditionLoc(DefaultLoc) {}
  4986. /// Check init-expr for canonical loop form and save loop counter
  4987. /// variable - #Var and its initialization value - #LB.
  4988. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  4989. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  4990. /// for less/greater and for strict/non-strict comparison.
  4991. bool checkAndSetCond(Expr *S);
  4992. /// Check incr-expr for canonical loop form and return true if it
  4993. /// does not conform, otherwise save loop step (#Step).
  4994. bool checkAndSetInc(Expr *S);
  4995. /// Return the loop counter variable.
  4996. ValueDecl *getLoopDecl() const { return LCDecl; }
  4997. /// Return the reference expression to loop counter variable.
  4998. Expr *getLoopDeclRefExpr() const { return LCRef; }
  4999. /// Source range of the loop init.
  5000. SourceRange getInitSrcRange() const { return InitSrcRange; }
  5001. /// Source range of the loop condition.
  5002. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  5003. /// Source range of the loop increment.
  5004. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  5005. /// True if the step should be subtracted.
  5006. bool shouldSubtractStep() const { return SubtractStep; }
  5007. /// True, if the compare operator is strict (<, > or !=).
  5008. bool isStrictTestOp() const { return TestIsStrictOp; }
  5009. /// Build the expression to calculate the number of iterations.
  5010. Expr *buildNumIterations(
  5011. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5012. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5013. /// Build the precondition expression for the loops.
  5014. Expr *
  5015. buildPreCond(Scope *S, Expr *Cond,
  5016. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5017. /// Build reference expression to the counter be used for codegen.
  5018. DeclRefExpr *
  5019. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5020. DSAStackTy &DSA) const;
  5021. /// Build reference expression to the private counter be used for
  5022. /// codegen.
  5023. Expr *buildPrivateCounterVar() const;
  5024. /// Build initialization of the counter be used for codegen.
  5025. Expr *buildCounterInit() const;
  5026. /// Build step of the counter be used for codegen.
  5027. Expr *buildCounterStep() const;
  5028. /// Build loop data with counter value for depend clauses in ordered
  5029. /// directives.
  5030. Expr *
  5031. buildOrderedLoopData(Scope *S, Expr *Counter,
  5032. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5033. SourceLocation Loc, Expr *Inc = nullptr,
  5034. OverloadedOperatorKind OOK = OO_Amp);
  5035. /// Builds the minimum value for the loop counter.
  5036. std::pair<Expr *, Expr *> buildMinMaxValues(
  5037. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5038. /// Builds final condition for the non-rectangular loops.
  5039. Expr *buildFinalCondition(Scope *S) const;
  5040. /// Return true if any expression is dependent.
  5041. bool dependent() const;
  5042. /// Returns true if the initializer forms non-rectangular loop.
  5043. bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
  5044. /// Returns true if the condition forms non-rectangular loop.
  5045. bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
  5046. /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
  5047. unsigned getLoopDependentIdx() const {
  5048. return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
  5049. }
  5050. private:
  5051. /// Check the right-hand side of an assignment in the increment
  5052. /// expression.
  5053. bool checkAndSetIncRHS(Expr *RHS);
  5054. /// Helper to set loop counter variable and its initializer.
  5055. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
  5056. bool EmitDiags);
  5057. /// Helper to set upper bound.
  5058. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  5059. SourceRange SR, SourceLocation SL);
  5060. /// Helper to set loop increment.
  5061. bool setStep(Expr *NewStep, bool Subtract);
  5062. };
  5063. bool OpenMPIterationSpaceChecker::dependent() const {
  5064. if (!LCDecl) {
  5065. assert(!LB && !UB && !Step);
  5066. return false;
  5067. }
  5068. return LCDecl->getType()->isDependentType() ||
  5069. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  5070. (Step && Step->isValueDependent());
  5071. }
  5072. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  5073. Expr *NewLCRefExpr,
  5074. Expr *NewLB, bool EmitDiags) {
  5075. // State consistency checking to ensure correct usage.
  5076. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  5077. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5078. if (!NewLCDecl || !NewLB)
  5079. return true;
  5080. LCDecl = getCanonicalDecl(NewLCDecl);
  5081. LCRef = NewLCRefExpr;
  5082. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  5083. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5084. if ((Ctor->isCopyOrMoveConstructor() ||
  5085. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5086. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5087. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  5088. LB = NewLB;
  5089. if (EmitDiags)
  5090. InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
  5091. return false;
  5092. }
  5093. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  5094. llvm::Optional<bool> LessOp,
  5095. bool StrictOp, SourceRange SR,
  5096. SourceLocation SL) {
  5097. // State consistency checking to ensure correct usage.
  5098. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  5099. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5100. if (!NewUB)
  5101. return true;
  5102. UB = NewUB;
  5103. if (LessOp)
  5104. TestIsLessOp = LessOp;
  5105. TestIsStrictOp = StrictOp;
  5106. ConditionSrcRange = SR;
  5107. ConditionLoc = SL;
  5108. CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
  5109. return false;
  5110. }
  5111. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  5112. // State consistency checking to ensure correct usage.
  5113. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  5114. if (!NewStep)
  5115. return true;
  5116. if (!NewStep->isValueDependent()) {
  5117. // Check that the step is integer expression.
  5118. SourceLocation StepLoc = NewStep->getBeginLoc();
  5119. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  5120. StepLoc, getExprAsWritten(NewStep));
  5121. if (Val.isInvalid())
  5122. return true;
  5123. NewStep = Val.get();
  5124. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  5125. // If test-expr is of form var relational-op b and relational-op is < or
  5126. // <= then incr-expr must cause var to increase on each iteration of the
  5127. // loop. If test-expr is of form var relational-op b and relational-op is
  5128. // > or >= then incr-expr must cause var to decrease on each iteration of
  5129. // the loop.
  5130. // If test-expr is of form b relational-op var and relational-op is < or
  5131. // <= then incr-expr must cause var to decrease on each iteration of the
  5132. // loop. If test-expr is of form b relational-op var and relational-op is
  5133. // > or >= then incr-expr must cause var to increase on each iteration of
  5134. // the loop.
  5135. llvm::APSInt Result;
  5136. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  5137. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  5138. bool IsConstNeg =
  5139. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  5140. bool IsConstPos =
  5141. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  5142. bool IsConstZero = IsConstant && !Result.getBoolValue();
  5143. // != with increment is treated as <; != with decrement is treated as >
  5144. if (!TestIsLessOp.hasValue())
  5145. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  5146. if (UB && (IsConstZero ||
  5147. (TestIsLessOp.getValue() ?
  5148. (IsConstNeg || (IsUnsigned && Subtract)) :
  5149. (IsConstPos || (IsUnsigned && !Subtract))))) {
  5150. SemaRef.Diag(NewStep->getExprLoc(),
  5151. diag::err_omp_loop_incr_not_compatible)
  5152. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  5153. SemaRef.Diag(ConditionLoc,
  5154. diag::note_omp_loop_cond_requres_compatible_incr)
  5155. << TestIsLessOp.getValue() << ConditionSrcRange;
  5156. return true;
  5157. }
  5158. if (TestIsLessOp.getValue() == Subtract) {
  5159. NewStep =
  5160. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  5161. .get();
  5162. Subtract = !Subtract;
  5163. }
  5164. }
  5165. Step = NewStep;
  5166. SubtractStep = Subtract;
  5167. return false;
  5168. }
  5169. namespace {
  5170. /// Checker for the non-rectangular loops. Checks if the initializer or
  5171. /// condition expression references loop counter variable.
  5172. class LoopCounterRefChecker final
  5173. : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
  5174. Sema &SemaRef;
  5175. DSAStackTy &Stack;
  5176. const ValueDecl *CurLCDecl = nullptr;
  5177. const ValueDecl *DepDecl = nullptr;
  5178. const ValueDecl *PrevDepDecl = nullptr;
  5179. bool IsInitializer = true;
  5180. unsigned BaseLoopId = 0;
  5181. bool checkDecl(const Expr *E, const ValueDecl *VD) {
  5182. if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
  5183. SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
  5184. << (IsInitializer ? 0 : 1);
  5185. return false;
  5186. }
  5187. const auto &&Data = Stack.isLoopControlVariable(VD);
  5188. // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
  5189. // The type of the loop iterator on which we depend may not have a random
  5190. // access iterator type.
  5191. if (Data.first && VD->getType()->isRecordType()) {
  5192. SmallString<128> Name;
  5193. llvm::raw_svector_ostream OS(Name);
  5194. VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5195. /*Qualified=*/true);
  5196. SemaRef.Diag(E->getExprLoc(),
  5197. diag::err_omp_wrong_dependency_iterator_type)
  5198. << OS.str();
  5199. SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
  5200. return false;
  5201. }
  5202. if (Data.first &&
  5203. (DepDecl || (PrevDepDecl &&
  5204. getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
  5205. if (!DepDecl && PrevDepDecl)
  5206. DepDecl = PrevDepDecl;
  5207. SmallString<128> Name;
  5208. llvm::raw_svector_ostream OS(Name);
  5209. DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5210. /*Qualified=*/true);
  5211. SemaRef.Diag(E->getExprLoc(),
  5212. diag::err_omp_invariant_or_linear_dependency)
  5213. << OS.str();
  5214. return false;
  5215. }
  5216. if (Data.first) {
  5217. DepDecl = VD;
  5218. BaseLoopId = Data.first;
  5219. }
  5220. return Data.first;
  5221. }
  5222. public:
  5223. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5224. const ValueDecl *VD = E->getDecl();
  5225. if (isa<VarDecl>(VD))
  5226. return checkDecl(E, VD);
  5227. return false;
  5228. }
  5229. bool VisitMemberExpr(const MemberExpr *E) {
  5230. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  5231. const ValueDecl *VD = E->getMemberDecl();
  5232. if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
  5233. return checkDecl(E, VD);
  5234. }
  5235. return false;
  5236. }
  5237. bool VisitStmt(const Stmt *S) {
  5238. bool Res = false;
  5239. for (const Stmt *Child : S->children())
  5240. Res = (Child && Visit(Child)) || Res;
  5241. return Res;
  5242. }
  5243. explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
  5244. const ValueDecl *CurLCDecl, bool IsInitializer,
  5245. const ValueDecl *PrevDepDecl = nullptr)
  5246. : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
  5247. PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
  5248. unsigned getBaseLoopId() const {
  5249. assert(CurLCDecl && "Expected loop dependency.");
  5250. return BaseLoopId;
  5251. }
  5252. const ValueDecl *getDepDecl() const {
  5253. assert(CurLCDecl && "Expected loop dependency.");
  5254. return DepDecl;
  5255. }
  5256. };
  5257. } // namespace
  5258. Optional<unsigned>
  5259. OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
  5260. bool IsInitializer) {
  5261. // Check for the non-rectangular loops.
  5262. LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
  5263. DepDecl);
  5264. if (LoopStmtChecker.Visit(S)) {
  5265. DepDecl = LoopStmtChecker.getDepDecl();
  5266. return LoopStmtChecker.getBaseLoopId();
  5267. }
  5268. return llvm::None;
  5269. }
  5270. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  5271. // Check init-expr for canonical loop form and save loop counter
  5272. // variable - #Var and its initialization value - #LB.
  5273. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  5274. // var = lb
  5275. // integer-type var = lb
  5276. // random-access-iterator-type var = lb
  5277. // pointer-type var = lb
  5278. //
  5279. if (!S) {
  5280. if (EmitDiags) {
  5281. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  5282. }
  5283. return true;
  5284. }
  5285. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5286. if (!ExprTemp->cleanupsHaveSideEffects())
  5287. S = ExprTemp->getSubExpr();
  5288. InitSrcRange = S->getSourceRange();
  5289. if (Expr *E = dyn_cast<Expr>(S))
  5290. S = E->IgnoreParens();
  5291. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5292. if (BO->getOpcode() == BO_Assign) {
  5293. Expr *LHS = BO->getLHS()->IgnoreParens();
  5294. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5295. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5296. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5297. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5298. EmitDiags);
  5299. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
  5300. }
  5301. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5302. if (ME->isArrow() &&
  5303. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5304. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5305. EmitDiags);
  5306. }
  5307. }
  5308. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  5309. if (DS->isSingleDecl()) {
  5310. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  5311. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  5312. // Accept non-canonical init form here but emit ext. warning.
  5313. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  5314. SemaRef.Diag(S->getBeginLoc(),
  5315. diag::ext_omp_loop_not_canonical_init)
  5316. << S->getSourceRange();
  5317. return setLCDeclAndLB(
  5318. Var,
  5319. buildDeclRefExpr(SemaRef, Var,
  5320. Var->getType().getNonReferenceType(),
  5321. DS->getBeginLoc()),
  5322. Var->getInit(), EmitDiags);
  5323. }
  5324. }
  5325. }
  5326. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5327. if (CE->getOperator() == OO_Equal) {
  5328. Expr *LHS = CE->getArg(0);
  5329. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5330. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5331. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5332. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5333. EmitDiags);
  5334. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
  5335. }
  5336. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5337. if (ME->isArrow() &&
  5338. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5339. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5340. EmitDiags);
  5341. }
  5342. }
  5343. }
  5344. if (dependent() || SemaRef.CurContext->isDependentContext())
  5345. return false;
  5346. if (EmitDiags) {
  5347. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  5348. << S->getSourceRange();
  5349. }
  5350. return true;
  5351. }
  5352. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  5353. /// variable (which may be the loop variable) if possible.
  5354. static const ValueDecl *getInitLCDecl(const Expr *E) {
  5355. if (!E)
  5356. return nullptr;
  5357. E = getExprAsWritten(E);
  5358. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  5359. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5360. if ((Ctor->isCopyOrMoveConstructor() ||
  5361. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5362. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5363. E = CE->getArg(0)->IgnoreParenImpCasts();
  5364. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  5365. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  5366. return getCanonicalDecl(VD);
  5367. }
  5368. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  5369. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5370. return getCanonicalDecl(ME->getMemberDecl());
  5371. return nullptr;
  5372. }
  5373. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  5374. // Check test-expr for canonical form, save upper-bound UB, flags for
  5375. // less/greater and for strict/non-strict comparison.
  5376. // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
  5377. // var relational-op b
  5378. // b relational-op var
  5379. //
  5380. bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
  5381. if (!S) {
  5382. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
  5383. << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
  5384. return true;
  5385. }
  5386. Condition = S;
  5387. S = getExprAsWritten(S);
  5388. SourceLocation CondLoc = S->getBeginLoc();
  5389. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5390. if (BO->isRelationalOp()) {
  5391. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5392. return setUB(BO->getRHS(),
  5393. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  5394. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5395. BO->getSourceRange(), BO->getOperatorLoc());
  5396. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  5397. return setUB(BO->getLHS(),
  5398. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  5399. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5400. BO->getSourceRange(), BO->getOperatorLoc());
  5401. } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
  5402. return setUB(
  5403. getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
  5404. /*LessOp=*/llvm::None,
  5405. /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
  5406. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5407. if (CE->getNumArgs() == 2) {
  5408. auto Op = CE->getOperator();
  5409. switch (Op) {
  5410. case OO_Greater:
  5411. case OO_GreaterEqual:
  5412. case OO_Less:
  5413. case OO_LessEqual:
  5414. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5415. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  5416. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5417. CE->getOperatorLoc());
  5418. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  5419. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  5420. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5421. CE->getOperatorLoc());
  5422. break;
  5423. case OO_ExclaimEqual:
  5424. if (IneqCondIsCanonical)
  5425. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
  5426. : CE->getArg(0),
  5427. /*LessOp=*/llvm::None,
  5428. /*StrictOp=*/true, CE->getSourceRange(),
  5429. CE->getOperatorLoc());
  5430. break;
  5431. default:
  5432. break;
  5433. }
  5434. }
  5435. }
  5436. if (dependent() || SemaRef.CurContext->isDependentContext())
  5437. return false;
  5438. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  5439. << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
  5440. return true;
  5441. }
  5442. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  5443. // RHS of canonical loop form increment can be:
  5444. // var + incr
  5445. // incr + var
  5446. // var - incr
  5447. //
  5448. RHS = RHS->IgnoreParenImpCasts();
  5449. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  5450. if (BO->isAdditiveOp()) {
  5451. bool IsAdd = BO->getOpcode() == BO_Add;
  5452. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5453. return setStep(BO->getRHS(), !IsAdd);
  5454. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  5455. return setStep(BO->getLHS(), /*Subtract=*/false);
  5456. }
  5457. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  5458. bool IsAdd = CE->getOperator() == OO_Plus;
  5459. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  5460. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5461. return setStep(CE->getArg(1), !IsAdd);
  5462. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  5463. return setStep(CE->getArg(0), /*Subtract=*/false);
  5464. }
  5465. }
  5466. if (dependent() || SemaRef.CurContext->isDependentContext())
  5467. return false;
  5468. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5469. << RHS->getSourceRange() << LCDecl;
  5470. return true;
  5471. }
  5472. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  5473. // Check incr-expr for canonical loop form and return true if it
  5474. // does not conform.
  5475. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  5476. // ++var
  5477. // var++
  5478. // --var
  5479. // var--
  5480. // var += incr
  5481. // var -= incr
  5482. // var = var + incr
  5483. // var = incr + var
  5484. // var = var - incr
  5485. //
  5486. if (!S) {
  5487. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  5488. return true;
  5489. }
  5490. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5491. if (!ExprTemp->cleanupsHaveSideEffects())
  5492. S = ExprTemp->getSubExpr();
  5493. IncrementSrcRange = S->getSourceRange();
  5494. S = S->IgnoreParens();
  5495. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  5496. if (UO->isIncrementDecrementOp() &&
  5497. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  5498. return setStep(SemaRef
  5499. .ActOnIntegerConstant(UO->getBeginLoc(),
  5500. (UO->isDecrementOp() ? -1 : 1))
  5501. .get(),
  5502. /*Subtract=*/false);
  5503. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5504. switch (BO->getOpcode()) {
  5505. case BO_AddAssign:
  5506. case BO_SubAssign:
  5507. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5508. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  5509. break;
  5510. case BO_Assign:
  5511. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5512. return checkAndSetIncRHS(BO->getRHS());
  5513. break;
  5514. default:
  5515. break;
  5516. }
  5517. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5518. switch (CE->getOperator()) {
  5519. case OO_PlusPlus:
  5520. case OO_MinusMinus:
  5521. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5522. return setStep(SemaRef
  5523. .ActOnIntegerConstant(
  5524. CE->getBeginLoc(),
  5525. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  5526. .get(),
  5527. /*Subtract=*/false);
  5528. break;
  5529. case OO_PlusEqual:
  5530. case OO_MinusEqual:
  5531. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5532. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  5533. break;
  5534. case OO_Equal:
  5535. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5536. return checkAndSetIncRHS(CE->getArg(1));
  5537. break;
  5538. default:
  5539. break;
  5540. }
  5541. }
  5542. if (dependent() || SemaRef.CurContext->isDependentContext())
  5543. return false;
  5544. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5545. << S->getSourceRange() << LCDecl;
  5546. return true;
  5547. }
  5548. static ExprResult
  5549. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  5550. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5551. if (SemaRef.CurContext->isDependentContext())
  5552. return ExprResult(Capture);
  5553. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  5554. return SemaRef.PerformImplicitConversion(
  5555. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  5556. /*AllowExplicit=*/true);
  5557. auto I = Captures.find(Capture);
  5558. if (I != Captures.end())
  5559. return buildCapture(SemaRef, Capture, I->second);
  5560. DeclRefExpr *Ref = nullptr;
  5561. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  5562. Captures[Capture] = Ref;
  5563. return Res;
  5564. }
  5565. /// Build the expression to calculate the number of iterations.
  5566. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  5567. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5568. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5569. ExprResult Diff;
  5570. QualType VarType = LCDecl->getType().getNonReferenceType();
  5571. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5572. SemaRef.getLangOpts().CPlusPlus) {
  5573. Expr *LBVal = LB;
  5574. Expr *UBVal = UB;
  5575. // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
  5576. // max(LB(MinVal), LB(MaxVal))
  5577. if (InitDependOnLC) {
  5578. const LoopIterationSpace &IS =
  5579. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5580. InitDependOnLC.getValueOr(
  5581. CondDependOnLC.getValueOr(0))];
  5582. if (!IS.MinValue || !IS.MaxValue)
  5583. return nullptr;
  5584. // OuterVar = Min
  5585. ExprResult MinValue =
  5586. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5587. if (!MinValue.isUsable())
  5588. return nullptr;
  5589. ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5590. IS.CounterVar, MinValue.get());
  5591. if (!LBMinVal.isUsable())
  5592. return nullptr;
  5593. // OuterVar = Min, LBVal
  5594. LBMinVal =
  5595. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
  5596. if (!LBMinVal.isUsable())
  5597. return nullptr;
  5598. // (OuterVar = Min, LBVal)
  5599. LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
  5600. if (!LBMinVal.isUsable())
  5601. return nullptr;
  5602. // OuterVar = Max
  5603. ExprResult MaxValue =
  5604. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5605. if (!MaxValue.isUsable())
  5606. return nullptr;
  5607. ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5608. IS.CounterVar, MaxValue.get());
  5609. if (!LBMaxVal.isUsable())
  5610. return nullptr;
  5611. // OuterVar = Max, LBVal
  5612. LBMaxVal =
  5613. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
  5614. if (!LBMaxVal.isUsable())
  5615. return nullptr;
  5616. // (OuterVar = Max, LBVal)
  5617. LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
  5618. if (!LBMaxVal.isUsable())
  5619. return nullptr;
  5620. Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
  5621. Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
  5622. if (!LBMin || !LBMax)
  5623. return nullptr;
  5624. // LB(MinVal) < LB(MaxVal)
  5625. ExprResult MinLessMaxRes =
  5626. SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
  5627. if (!MinLessMaxRes.isUsable())
  5628. return nullptr;
  5629. Expr *MinLessMax =
  5630. tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
  5631. if (!MinLessMax)
  5632. return nullptr;
  5633. if (TestIsLessOp.getValue()) {
  5634. // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
  5635. // LB(MaxVal))
  5636. ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5637. MinLessMax, LBMin, LBMax);
  5638. if (!MinLB.isUsable())
  5639. return nullptr;
  5640. LBVal = MinLB.get();
  5641. } else {
  5642. // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
  5643. // LB(MaxVal))
  5644. ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5645. MinLessMax, LBMax, LBMin);
  5646. if (!MaxLB.isUsable())
  5647. return nullptr;
  5648. LBVal = MaxLB.get();
  5649. }
  5650. }
  5651. // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
  5652. // min(UB(MinVal), UB(MaxVal))
  5653. if (CondDependOnLC) {
  5654. const LoopIterationSpace &IS =
  5655. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5656. InitDependOnLC.getValueOr(
  5657. CondDependOnLC.getValueOr(0))];
  5658. if (!IS.MinValue || !IS.MaxValue)
  5659. return nullptr;
  5660. // OuterVar = Min
  5661. ExprResult MinValue =
  5662. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5663. if (!MinValue.isUsable())
  5664. return nullptr;
  5665. ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5666. IS.CounterVar, MinValue.get());
  5667. if (!UBMinVal.isUsable())
  5668. return nullptr;
  5669. // OuterVar = Min, UBVal
  5670. UBMinVal =
  5671. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
  5672. if (!UBMinVal.isUsable())
  5673. return nullptr;
  5674. // (OuterVar = Min, UBVal)
  5675. UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
  5676. if (!UBMinVal.isUsable())
  5677. return nullptr;
  5678. // OuterVar = Max
  5679. ExprResult MaxValue =
  5680. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5681. if (!MaxValue.isUsable())
  5682. return nullptr;
  5683. ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5684. IS.CounterVar, MaxValue.get());
  5685. if (!UBMaxVal.isUsable())
  5686. return nullptr;
  5687. // OuterVar = Max, UBVal
  5688. UBMaxVal =
  5689. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
  5690. if (!UBMaxVal.isUsable())
  5691. return nullptr;
  5692. // (OuterVar = Max, UBVal)
  5693. UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
  5694. if (!UBMaxVal.isUsable())
  5695. return nullptr;
  5696. Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
  5697. Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
  5698. if (!UBMin || !UBMax)
  5699. return nullptr;
  5700. // UB(MinVal) > UB(MaxVal)
  5701. ExprResult MinGreaterMaxRes =
  5702. SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
  5703. if (!MinGreaterMaxRes.isUsable())
  5704. return nullptr;
  5705. Expr *MinGreaterMax =
  5706. tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
  5707. if (!MinGreaterMax)
  5708. return nullptr;
  5709. if (TestIsLessOp.getValue()) {
  5710. // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
  5711. // UB(MaxVal))
  5712. ExprResult MaxUB = SemaRef.ActOnConditionalOp(
  5713. DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
  5714. if (!MaxUB.isUsable())
  5715. return nullptr;
  5716. UBVal = MaxUB.get();
  5717. } else {
  5718. // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
  5719. // UB(MaxVal))
  5720. ExprResult MinUB = SemaRef.ActOnConditionalOp(
  5721. DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
  5722. if (!MinUB.isUsable())
  5723. return nullptr;
  5724. UBVal = MinUB.get();
  5725. }
  5726. }
  5727. // Upper - Lower
  5728. Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
  5729. Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
  5730. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5731. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5732. if (!Upper || !Lower)
  5733. return nullptr;
  5734. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5735. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  5736. // BuildBinOp already emitted error, this one is to point user to upper
  5737. // and lower bound, and to tell what is passed to 'operator-'.
  5738. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  5739. << Upper->getSourceRange() << Lower->getSourceRange();
  5740. return nullptr;
  5741. }
  5742. }
  5743. if (!Diff.isUsable())
  5744. return nullptr;
  5745. // Upper - Lower [- 1]
  5746. if (TestIsStrictOp)
  5747. Diff = SemaRef.BuildBinOp(
  5748. S, DefaultLoc, BO_Sub, Diff.get(),
  5749. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5750. if (!Diff.isUsable())
  5751. return nullptr;
  5752. // Upper - Lower [- 1] + Step
  5753. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5754. if (!NewStep.isUsable())
  5755. return nullptr;
  5756. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  5757. if (!Diff.isUsable())
  5758. return nullptr;
  5759. // Parentheses (for dumping/debugging purposes only).
  5760. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5761. if (!Diff.isUsable())
  5762. return nullptr;
  5763. // (Upper - Lower [- 1] + Step) / Step
  5764. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5765. if (!Diff.isUsable())
  5766. return nullptr;
  5767. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  5768. QualType Type = Diff.get()->getType();
  5769. ASTContext &C = SemaRef.Context;
  5770. bool UseVarType = VarType->hasIntegerRepresentation() &&
  5771. C.getTypeSize(Type) > C.getTypeSize(VarType);
  5772. if (!Type->isIntegerType() || UseVarType) {
  5773. unsigned NewSize =
  5774. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  5775. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  5776. : Type->hasSignedIntegerRepresentation();
  5777. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  5778. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  5779. Diff = SemaRef.PerformImplicitConversion(
  5780. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  5781. if (!Diff.isUsable())
  5782. return nullptr;
  5783. }
  5784. }
  5785. if (LimitedType) {
  5786. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  5787. if (NewSize != C.getTypeSize(Type)) {
  5788. if (NewSize < C.getTypeSize(Type)) {
  5789. assert(NewSize == 64 && "incorrect loop var size");
  5790. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  5791. << InitSrcRange << ConditionSrcRange;
  5792. }
  5793. QualType NewType = C.getIntTypeForBitwidth(
  5794. NewSize, Type->hasSignedIntegerRepresentation() ||
  5795. C.getTypeSize(Type) < NewSize);
  5796. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  5797. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  5798. Sema::AA_Converting, true);
  5799. if (!Diff.isUsable())
  5800. return nullptr;
  5801. }
  5802. }
  5803. }
  5804. return Diff.get();
  5805. }
  5806. std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
  5807. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5808. // Do not build for iterators, they cannot be used in non-rectangular loop
  5809. // nests.
  5810. if (LCDecl->getType()->isRecordType())
  5811. return std::make_pair(nullptr, nullptr);
  5812. // If we subtract, the min is in the condition, otherwise the min is in the
  5813. // init value.
  5814. Expr *MinExpr = nullptr;
  5815. Expr *MaxExpr = nullptr;
  5816. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  5817. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  5818. bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
  5819. : CondDependOnLC.hasValue();
  5820. bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
  5821. : InitDependOnLC.hasValue();
  5822. Expr *Lower =
  5823. LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5824. Expr *Upper =
  5825. UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5826. if (!Upper || !Lower)
  5827. return std::make_pair(nullptr, nullptr);
  5828. if (TestIsLessOp.getValue())
  5829. MinExpr = Lower;
  5830. else
  5831. MaxExpr = Upper;
  5832. // Build minimum/maximum value based on number of iterations.
  5833. ExprResult Diff;
  5834. QualType VarType = LCDecl->getType().getNonReferenceType();
  5835. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5836. if (!Diff.isUsable())
  5837. return std::make_pair(nullptr, nullptr);
  5838. // Upper - Lower [- 1]
  5839. if (TestIsStrictOp)
  5840. Diff = SemaRef.BuildBinOp(
  5841. S, DefaultLoc, BO_Sub, Diff.get(),
  5842. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5843. if (!Diff.isUsable())
  5844. return std::make_pair(nullptr, nullptr);
  5845. // Upper - Lower [- 1] + Step
  5846. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5847. if (!NewStep.isUsable())
  5848. return std::make_pair(nullptr, nullptr);
  5849. // Parentheses (for dumping/debugging purposes only).
  5850. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5851. if (!Diff.isUsable())
  5852. return std::make_pair(nullptr, nullptr);
  5853. // (Upper - Lower [- 1]) / Step
  5854. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5855. if (!Diff.isUsable())
  5856. return std::make_pair(nullptr, nullptr);
  5857. // ((Upper - Lower [- 1]) / Step) * Step
  5858. // Parentheses (for dumping/debugging purposes only).
  5859. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5860. if (!Diff.isUsable())
  5861. return std::make_pair(nullptr, nullptr);
  5862. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
  5863. if (!Diff.isUsable())
  5864. return std::make_pair(nullptr, nullptr);
  5865. // Convert to the original type or ptrdiff_t, if original type is pointer.
  5866. if (!VarType->isAnyPointerType() &&
  5867. !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
  5868. Diff = SemaRef.PerformImplicitConversion(
  5869. Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
  5870. } else if (VarType->isAnyPointerType() &&
  5871. !SemaRef.Context.hasSameType(
  5872. Diff.get()->getType(),
  5873. SemaRef.Context.getUnsignedPointerDiffType())) {
  5874. Diff = SemaRef.PerformImplicitConversion(
  5875. Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
  5876. Sema::AA_Converting, /*AllowExplicit=*/true);
  5877. }
  5878. if (!Diff.isUsable())
  5879. return std::make_pair(nullptr, nullptr);
  5880. // Parentheses (for dumping/debugging purposes only).
  5881. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5882. if (!Diff.isUsable())
  5883. return std::make_pair(nullptr, nullptr);
  5884. if (TestIsLessOp.getValue()) {
  5885. // MinExpr = Lower;
  5886. // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
  5887. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
  5888. if (!Diff.isUsable())
  5889. return std::make_pair(nullptr, nullptr);
  5890. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5891. if (!Diff.isUsable())
  5892. return std::make_pair(nullptr, nullptr);
  5893. MaxExpr = Diff.get();
  5894. } else {
  5895. // MaxExpr = Upper;
  5896. // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
  5897. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
  5898. if (!Diff.isUsable())
  5899. return std::make_pair(nullptr, nullptr);
  5900. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5901. if (!Diff.isUsable())
  5902. return std::make_pair(nullptr, nullptr);
  5903. MinExpr = Diff.get();
  5904. }
  5905. return std::make_pair(MinExpr, MaxExpr);
  5906. }
  5907. Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
  5908. if (InitDependOnLC || CondDependOnLC)
  5909. return Condition;
  5910. return nullptr;
  5911. }
  5912. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  5913. Scope *S, Expr *Cond,
  5914. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5915. // Do not build a precondition when the condition/initialization is dependent
  5916. // to prevent pessimistic early loop exit.
  5917. // TODO: this can be improved by calculating min/max values but not sure that
  5918. // it will be very effective.
  5919. if (CondDependOnLC || InitDependOnLC)
  5920. return SemaRef.PerformImplicitConversion(
  5921. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
  5922. SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5923. /*AllowExplicit=*/true).get();
  5924. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  5925. Sema::TentativeAnalysisScope Trap(SemaRef);
  5926. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  5927. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  5928. if (!NewLB.isUsable() || !NewUB.isUsable())
  5929. return nullptr;
  5930. ExprResult CondExpr =
  5931. SemaRef.BuildBinOp(S, DefaultLoc,
  5932. TestIsLessOp.getValue() ?
  5933. (TestIsStrictOp ? BO_LT : BO_LE) :
  5934. (TestIsStrictOp ? BO_GT : BO_GE),
  5935. NewLB.get(), NewUB.get());
  5936. if (CondExpr.isUsable()) {
  5937. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  5938. SemaRef.Context.BoolTy))
  5939. CondExpr = SemaRef.PerformImplicitConversion(
  5940. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5941. /*AllowExplicit=*/true);
  5942. }
  5943. // Otherwise use original loop condition and evaluate it in runtime.
  5944. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  5945. }
  5946. /// Build reference expression to the counter be used for codegen.
  5947. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  5948. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5949. DSAStackTy &DSA) const {
  5950. auto *VD = dyn_cast<VarDecl>(LCDecl);
  5951. if (!VD) {
  5952. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  5953. DeclRefExpr *Ref = buildDeclRefExpr(
  5954. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  5955. const DSAStackTy::DSAVarData Data =
  5956. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  5957. // If the loop control decl is explicitly marked as private, do not mark it
  5958. // as captured again.
  5959. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  5960. Captures.insert(std::make_pair(LCRef, Ref));
  5961. return Ref;
  5962. }
  5963. return cast<DeclRefExpr>(LCRef);
  5964. }
  5965. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  5966. if (LCDecl && !LCDecl->isInvalidDecl()) {
  5967. QualType Type = LCDecl->getType().getNonReferenceType();
  5968. VarDecl *PrivateVar = buildVarDecl(
  5969. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  5970. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  5971. isa<VarDecl>(LCDecl)
  5972. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  5973. : nullptr);
  5974. if (PrivateVar->isInvalidDecl())
  5975. return nullptr;
  5976. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  5977. }
  5978. return nullptr;
  5979. }
  5980. /// Build initialization of the counter to be used for codegen.
  5981. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  5982. /// Build step of the counter be used for codegen.
  5983. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  5984. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  5985. Scope *S, Expr *Counter,
  5986. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  5987. Expr *Inc, OverloadedOperatorKind OOK) {
  5988. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  5989. if (!Cnt)
  5990. return nullptr;
  5991. if (Inc) {
  5992. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  5993. "Expected only + or - operations for depend clauses.");
  5994. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  5995. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  5996. if (!Cnt)
  5997. return nullptr;
  5998. }
  5999. ExprResult Diff;
  6000. QualType VarType = LCDecl->getType().getNonReferenceType();
  6001. if (VarType->isIntegerType() || VarType->isPointerType() ||
  6002. SemaRef.getLangOpts().CPlusPlus) {
  6003. // Upper - Lower
  6004. Expr *Upper = TestIsLessOp.getValue()
  6005. ? Cnt
  6006. : tryBuildCapture(SemaRef, UB, Captures).get();
  6007. Expr *Lower = TestIsLessOp.getValue()
  6008. ? tryBuildCapture(SemaRef, LB, Captures).get()
  6009. : Cnt;
  6010. if (!Upper || !Lower)
  6011. return nullptr;
  6012. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  6013. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  6014. // BuildBinOp already emitted error, this one is to point user to upper
  6015. // and lower bound, and to tell what is passed to 'operator-'.
  6016. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  6017. << Upper->getSourceRange() << Lower->getSourceRange();
  6018. return nullptr;
  6019. }
  6020. }
  6021. if (!Diff.isUsable())
  6022. return nullptr;
  6023. // Parentheses (for dumping/debugging purposes only).
  6024. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  6025. if (!Diff.isUsable())
  6026. return nullptr;
  6027. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  6028. if (!NewStep.isUsable())
  6029. return nullptr;
  6030. // (Upper - Lower) / Step
  6031. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  6032. if (!Diff.isUsable())
  6033. return nullptr;
  6034. return Diff.get();
  6035. }
  6036. } // namespace
  6037. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  6038. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  6039. assert(Init && "Expected loop in canonical form.");
  6040. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  6041. if (AssociatedLoops > 0 &&
  6042. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  6043. DSAStack->loopStart();
  6044. OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
  6045. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  6046. if (ValueDecl *D = ISC.getLoopDecl()) {
  6047. auto *VD = dyn_cast<VarDecl>(D);
  6048. DeclRefExpr *PrivateRef = nullptr;
  6049. if (!VD) {
  6050. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  6051. VD = Private;
  6052. } else {
  6053. PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  6054. /*WithInit=*/false);
  6055. VD = cast<VarDecl>(PrivateRef->getDecl());
  6056. }
  6057. }
  6058. DSAStack->addLoopControlVariable(D, VD);
  6059. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  6060. if (LD != D->getCanonicalDecl()) {
  6061. DSAStack->resetPossibleLoopCounter();
  6062. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  6063. MarkDeclarationsReferencedInExpr(
  6064. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  6065. Var->getType().getNonLValueExprType(Context),
  6066. ForLoc, /*RefersToCapture=*/true));
  6067. }
  6068. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  6069. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
  6070. // Referenced in a Construct, C/C++]. The loop iteration variable in the
  6071. // associated for-loop of a simd construct with just one associated
  6072. // for-loop may be listed in a linear clause with a constant-linear-step
  6073. // that is the increment of the associated for-loop. The loop iteration
  6074. // variable(s) in the associated for-loop(s) of a for or parallel for
  6075. // construct may be listed in a private or lastprivate clause.
  6076. DSAStackTy::DSAVarData DVar =
  6077. DSAStack->getTopDSA(D, /*FromParent=*/false);
  6078. // If LoopVarRefExpr is nullptr it means the corresponding loop variable
  6079. // is declared in the loop and it is predetermined as a private.
  6080. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  6081. OpenMPClauseKind PredeterminedCKind =
  6082. isOpenMPSimdDirective(DKind)
  6083. ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
  6084. : OMPC_private;
  6085. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6086. DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
  6087. (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
  6088. DVar.CKind != OMPC_private))) ||
  6089. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  6090. isOpenMPDistributeDirective(DKind)) &&
  6091. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6092. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  6093. (DVar.CKind != OMPC_private || DVar.RefExpr)) {
  6094. Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  6095. << getOpenMPClauseName(DVar.CKind)
  6096. << getOpenMPDirectiveName(DKind)
  6097. << getOpenMPClauseName(PredeterminedCKind);
  6098. if (DVar.RefExpr == nullptr)
  6099. DVar.CKind = PredeterminedCKind;
  6100. reportOriginalDsa(*this, DSAStack, D, DVar,
  6101. /*IsLoopIterVar=*/true);
  6102. } else if (LoopDeclRefExpr) {
  6103. // Make the loop iteration variable private (for worksharing
  6104. // constructs), linear (for simd directives with the only one
  6105. // associated loop) or lastprivate (for simd directives with several
  6106. // collapsed or ordered loops).
  6107. if (DVar.CKind == OMPC_unknown)
  6108. DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
  6109. PrivateRef);
  6110. }
  6111. }
  6112. }
  6113. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  6114. }
  6115. }
  6116. /// Called on a for stmt to check and extract its iteration space
  6117. /// for further processing (such as collapsing).
  6118. static bool checkOpenMPIterationSpace(
  6119. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  6120. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  6121. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  6122. Expr *OrderedLoopCountExpr,
  6123. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6124. llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
  6125. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6126. // OpenMP [2.6, Canonical Loop Form]
  6127. // for (init-expr; test-expr; incr-expr) structured-block
  6128. auto *For = dyn_cast_or_null<ForStmt>(S);
  6129. if (!For) {
  6130. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  6131. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  6132. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  6133. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  6134. if (TotalNestedLoopCount > 1) {
  6135. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  6136. SemaRef.Diag(DSA.getConstructLoc(),
  6137. diag::note_omp_collapse_ordered_expr)
  6138. << 2 << CollapseLoopCountExpr->getSourceRange()
  6139. << OrderedLoopCountExpr->getSourceRange();
  6140. else if (CollapseLoopCountExpr)
  6141. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6142. diag::note_omp_collapse_ordered_expr)
  6143. << 0 << CollapseLoopCountExpr->getSourceRange();
  6144. else
  6145. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6146. diag::note_omp_collapse_ordered_expr)
  6147. << 1 << OrderedLoopCountExpr->getSourceRange();
  6148. }
  6149. return true;
  6150. }
  6151. assert(For->getBody());
  6152. OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
  6153. // Check init.
  6154. Stmt *Init = For->getInit();
  6155. if (ISC.checkAndSetInit(Init))
  6156. return true;
  6157. bool HasErrors = false;
  6158. // Check loop variable's type.
  6159. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  6160. // OpenMP [2.6, Canonical Loop Form]
  6161. // Var is one of the following:
  6162. // A variable of signed or unsigned integer type.
  6163. // For C++, a variable of a random access iterator type.
  6164. // For C, a variable of a pointer type.
  6165. QualType VarType = LCDecl->getType().getNonReferenceType();
  6166. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  6167. !VarType->isPointerType() &&
  6168. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  6169. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  6170. << SemaRef.getLangOpts().CPlusPlus;
  6171. HasErrors = true;
  6172. }
  6173. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  6174. // a Construct
  6175. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  6176. // parallel for construct is (are) private.
  6177. // The loop iteration variable in the associated for-loop of a simd
  6178. // construct with just one associated for-loop is linear with a
  6179. // constant-linear-step that is the increment of the associated for-loop.
  6180. // Exclude loop var from the list of variables with implicitly defined data
  6181. // sharing attributes.
  6182. VarsWithImplicitDSA.erase(LCDecl);
  6183. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  6184. // Check test-expr.
  6185. HasErrors |= ISC.checkAndSetCond(For->getCond());
  6186. // Check incr-expr.
  6187. HasErrors |= ISC.checkAndSetInc(For->getInc());
  6188. }
  6189. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  6190. return HasErrors;
  6191. // Build the loop's iteration space representation.
  6192. ResultIterSpaces[CurrentNestedLoopCount].PreCond =
  6193. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  6194. ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
  6195. ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
  6196. (isOpenMPWorksharingDirective(DKind) ||
  6197. isOpenMPTaskLoopDirective(DKind) ||
  6198. isOpenMPDistributeDirective(DKind)),
  6199. Captures);
  6200. ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
  6201. ISC.buildCounterVar(Captures, DSA);
  6202. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
  6203. ISC.buildPrivateCounterVar();
  6204. ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
  6205. ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
  6206. ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
  6207. ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
  6208. ISC.getConditionSrcRange();
  6209. ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
  6210. ISC.getIncrementSrcRange();
  6211. ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
  6212. ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
  6213. ISC.isStrictTestOp();
  6214. std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
  6215. ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
  6216. ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
  6217. ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
  6218. ISC.buildFinalCondition(DSA.getCurScope());
  6219. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
  6220. ISC.doesInitDependOnLC();
  6221. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
  6222. ISC.doesCondDependOnLC();
  6223. ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
  6224. ISC.getLoopDependentIdx();
  6225. HasErrors |=
  6226. (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
  6227. ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
  6228. ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
  6229. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
  6230. ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
  6231. ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
  6232. if (!HasErrors && DSA.isOrderedRegion()) {
  6233. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  6234. if (CurrentNestedLoopCount <
  6235. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  6236. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  6237. CurrentNestedLoopCount,
  6238. ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
  6239. DSA.getOrderedRegionParam().second->setLoopCounter(
  6240. CurrentNestedLoopCount,
  6241. ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
  6242. }
  6243. }
  6244. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  6245. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  6246. // Erroneous case - clause has some problems.
  6247. continue;
  6248. }
  6249. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  6250. Pair.second.size() <= CurrentNestedLoopCount) {
  6251. // Erroneous case - clause has some problems.
  6252. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  6253. continue;
  6254. }
  6255. Expr *CntValue;
  6256. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  6257. CntValue = ISC.buildOrderedLoopData(
  6258. DSA.getCurScope(),
  6259. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6260. Pair.first->getDependencyLoc());
  6261. else
  6262. CntValue = ISC.buildOrderedLoopData(
  6263. DSA.getCurScope(),
  6264. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6265. Pair.first->getDependencyLoc(),
  6266. Pair.second[CurrentNestedLoopCount].first,
  6267. Pair.second[CurrentNestedLoopCount].second);
  6268. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  6269. }
  6270. }
  6271. return HasErrors;
  6272. }
  6273. /// Build 'VarRef = Start.
  6274. static ExprResult
  6275. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6276. ExprResult Start, bool IsNonRectangularLB,
  6277. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6278. // Build 'VarRef = Start.
  6279. ExprResult NewStart = IsNonRectangularLB
  6280. ? Start.get()
  6281. : tryBuildCapture(SemaRef, Start.get(), Captures);
  6282. if (!NewStart.isUsable())
  6283. return ExprError();
  6284. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  6285. VarRef.get()->getType())) {
  6286. NewStart = SemaRef.PerformImplicitConversion(
  6287. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  6288. /*AllowExplicit=*/true);
  6289. if (!NewStart.isUsable())
  6290. return ExprError();
  6291. }
  6292. ExprResult Init =
  6293. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6294. return Init;
  6295. }
  6296. /// Build 'VarRef = Start + Iter * Step'.
  6297. static ExprResult buildCounterUpdate(
  6298. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6299. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  6300. bool IsNonRectangularLB,
  6301. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  6302. // Add parentheses (for debugging purposes only).
  6303. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  6304. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  6305. !Step.isUsable())
  6306. return ExprError();
  6307. ExprResult NewStep = Step;
  6308. if (Captures)
  6309. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  6310. if (NewStep.isInvalid())
  6311. return ExprError();
  6312. ExprResult Update =
  6313. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  6314. if (!Update.isUsable())
  6315. return ExprError();
  6316. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  6317. // 'VarRef = Start (+|-) Iter * Step'.
  6318. if (!Start.isUsable())
  6319. return ExprError();
  6320. ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
  6321. if (!NewStart.isUsable())
  6322. return ExprError();
  6323. if (Captures && !IsNonRectangularLB)
  6324. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  6325. if (NewStart.isInvalid())
  6326. return ExprError();
  6327. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  6328. ExprResult SavedUpdate = Update;
  6329. ExprResult UpdateVal;
  6330. if (VarRef.get()->getType()->isOverloadableType() ||
  6331. NewStart.get()->getType()->isOverloadableType() ||
  6332. Update.get()->getType()->isOverloadableType()) {
  6333. Sema::TentativeAnalysisScope Trap(SemaRef);
  6334. Update =
  6335. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6336. if (Update.isUsable()) {
  6337. UpdateVal =
  6338. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  6339. VarRef.get(), SavedUpdate.get());
  6340. if (UpdateVal.isUsable()) {
  6341. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  6342. UpdateVal.get());
  6343. }
  6344. }
  6345. }
  6346. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  6347. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  6348. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  6349. NewStart.get(), SavedUpdate.get());
  6350. if (!Update.isUsable())
  6351. return ExprError();
  6352. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  6353. VarRef.get()->getType())) {
  6354. Update = SemaRef.PerformImplicitConversion(
  6355. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  6356. if (!Update.isUsable())
  6357. return ExprError();
  6358. }
  6359. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  6360. }
  6361. return Update;
  6362. }
  6363. /// Convert integer expression \a E to make it have at least \a Bits
  6364. /// bits.
  6365. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  6366. if (E == nullptr)
  6367. return ExprError();
  6368. ASTContext &C = SemaRef.Context;
  6369. QualType OldType = E->getType();
  6370. unsigned HasBits = C.getTypeSize(OldType);
  6371. if (HasBits >= Bits)
  6372. return ExprResult(E);
  6373. // OK to convert to signed, because new type has more bits than old.
  6374. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  6375. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  6376. true);
  6377. }
  6378. /// Check if the given expression \a E is a constant integer that fits
  6379. /// into \a Bits bits.
  6380. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  6381. if (E == nullptr)
  6382. return false;
  6383. llvm::APSInt Result;
  6384. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  6385. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  6386. return false;
  6387. }
  6388. /// Build preinits statement for the given declarations.
  6389. static Stmt *buildPreInits(ASTContext &Context,
  6390. MutableArrayRef<Decl *> PreInits) {
  6391. if (!PreInits.empty()) {
  6392. return new (Context) DeclStmt(
  6393. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  6394. SourceLocation(), SourceLocation());
  6395. }
  6396. return nullptr;
  6397. }
  6398. /// Build preinits statement for the given declarations.
  6399. static Stmt *
  6400. buildPreInits(ASTContext &Context,
  6401. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6402. if (!Captures.empty()) {
  6403. SmallVector<Decl *, 16> PreInits;
  6404. for (const auto &Pair : Captures)
  6405. PreInits.push_back(Pair.second->getDecl());
  6406. return buildPreInits(Context, PreInits);
  6407. }
  6408. return nullptr;
  6409. }
  6410. /// Build postupdate expression for the given list of postupdates expressions.
  6411. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  6412. Expr *PostUpdate = nullptr;
  6413. if (!PostUpdates.empty()) {
  6414. for (Expr *E : PostUpdates) {
  6415. Expr *ConvE = S.BuildCStyleCastExpr(
  6416. E->getExprLoc(),
  6417. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  6418. E->getExprLoc(), E)
  6419. .get();
  6420. PostUpdate = PostUpdate
  6421. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  6422. PostUpdate, ConvE)
  6423. .get()
  6424. : ConvE;
  6425. }
  6426. }
  6427. return PostUpdate;
  6428. }
  6429. /// Called on a for stmt to check itself and nested loops (if any).
  6430. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  6431. /// number of collapsed loops otherwise.
  6432. static unsigned
  6433. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  6434. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  6435. DSAStackTy &DSA,
  6436. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6437. OMPLoopDirective::HelperExprs &Built) {
  6438. unsigned NestedLoopCount = 1;
  6439. if (CollapseLoopCountExpr) {
  6440. // Found 'collapse' clause - calculate collapse number.
  6441. Expr::EvalResult Result;
  6442. if (!CollapseLoopCountExpr->isValueDependent() &&
  6443. CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  6444. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  6445. } else {
  6446. Built.clear(/*Size=*/1);
  6447. return 1;
  6448. }
  6449. }
  6450. unsigned OrderedLoopCount = 1;
  6451. if (OrderedLoopCountExpr) {
  6452. // Found 'ordered' clause - calculate collapse number.
  6453. Expr::EvalResult EVResult;
  6454. if (!OrderedLoopCountExpr->isValueDependent() &&
  6455. OrderedLoopCountExpr->EvaluateAsInt(EVResult,
  6456. SemaRef.getASTContext())) {
  6457. llvm::APSInt Result = EVResult.Val.getInt();
  6458. if (Result.getLimitedValue() < NestedLoopCount) {
  6459. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6460. diag::err_omp_wrong_ordered_loop_count)
  6461. << OrderedLoopCountExpr->getSourceRange();
  6462. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6463. diag::note_collapse_loop_count)
  6464. << CollapseLoopCountExpr->getSourceRange();
  6465. }
  6466. OrderedLoopCount = Result.getLimitedValue();
  6467. } else {
  6468. Built.clear(/*Size=*/1);
  6469. return 1;
  6470. }
  6471. }
  6472. // This is helper routine for loop directives (e.g., 'for', 'simd',
  6473. // 'for simd', etc.).
  6474. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  6475. SmallVector<LoopIterationSpace, 4> IterSpaces(
  6476. std::max(OrderedLoopCount, NestedLoopCount));
  6477. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  6478. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6479. if (checkOpenMPIterationSpace(
  6480. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6481. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6482. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6483. return 0;
  6484. // Move on to the next nested for loop, or to the loop body.
  6485. // OpenMP [2.8.1, simd construct, Restrictions]
  6486. // All loops associated with the construct must be perfectly nested; that
  6487. // is, there must be no intervening code nor any OpenMP directive between
  6488. // any two loops.
  6489. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  6490. }
  6491. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  6492. if (checkOpenMPIterationSpace(
  6493. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6494. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6495. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6496. return 0;
  6497. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  6498. // Handle initialization of captured loop iterator variables.
  6499. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  6500. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  6501. Captures[DRE] = DRE;
  6502. }
  6503. }
  6504. // Move on to the next nested for loop, or to the loop body.
  6505. // OpenMP [2.8.1, simd construct, Restrictions]
  6506. // All loops associated with the construct must be perfectly nested; that
  6507. // is, there must be no intervening code nor any OpenMP directive between
  6508. // any two loops.
  6509. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  6510. }
  6511. Built.clear(/* size */ NestedLoopCount);
  6512. if (SemaRef.CurContext->isDependentContext())
  6513. return NestedLoopCount;
  6514. // An example of what is generated for the following code:
  6515. //
  6516. // #pragma omp simd collapse(2) ordered(2)
  6517. // for (i = 0; i < NI; ++i)
  6518. // for (k = 0; k < NK; ++k)
  6519. // for (j = J0; j < NJ; j+=2) {
  6520. // <loop body>
  6521. // }
  6522. //
  6523. // We generate the code below.
  6524. // Note: the loop body may be outlined in CodeGen.
  6525. // Note: some counters may be C++ classes, operator- is used to find number of
  6526. // iterations and operator+= to calculate counter value.
  6527. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  6528. // or i64 is currently supported).
  6529. //
  6530. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  6531. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  6532. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  6533. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  6534. // // similar updates for vars in clauses (e.g. 'linear')
  6535. // <loop body (using local i and j)>
  6536. // }
  6537. // i = NI; // assign final values of counters
  6538. // j = NJ;
  6539. //
  6540. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  6541. // the iteration counts of the collapsed for loops.
  6542. // Precondition tests if there is at least one iteration (all conditions are
  6543. // true).
  6544. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  6545. Expr *N0 = IterSpaces[0].NumIterations;
  6546. ExprResult LastIteration32 =
  6547. widenIterationCount(/*Bits=*/32,
  6548. SemaRef
  6549. .PerformImplicitConversion(
  6550. N0->IgnoreImpCasts(), N0->getType(),
  6551. Sema::AA_Converting, /*AllowExplicit=*/true)
  6552. .get(),
  6553. SemaRef);
  6554. ExprResult LastIteration64 = widenIterationCount(
  6555. /*Bits=*/64,
  6556. SemaRef
  6557. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  6558. Sema::AA_Converting,
  6559. /*AllowExplicit=*/true)
  6560. .get(),
  6561. SemaRef);
  6562. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  6563. return NestedLoopCount;
  6564. ASTContext &C = SemaRef.Context;
  6565. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  6566. Scope *CurScope = DSA.getCurScope();
  6567. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  6568. if (PreCond.isUsable()) {
  6569. PreCond =
  6570. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  6571. PreCond.get(), IterSpaces[Cnt].PreCond);
  6572. }
  6573. Expr *N = IterSpaces[Cnt].NumIterations;
  6574. SourceLocation Loc = N->getExprLoc();
  6575. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  6576. if (LastIteration32.isUsable())
  6577. LastIteration32 = SemaRef.BuildBinOp(
  6578. CurScope, Loc, BO_Mul, LastIteration32.get(),
  6579. SemaRef
  6580. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6581. Sema::AA_Converting,
  6582. /*AllowExplicit=*/true)
  6583. .get());
  6584. if (LastIteration64.isUsable())
  6585. LastIteration64 = SemaRef.BuildBinOp(
  6586. CurScope, Loc, BO_Mul, LastIteration64.get(),
  6587. SemaRef
  6588. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6589. Sema::AA_Converting,
  6590. /*AllowExplicit=*/true)
  6591. .get());
  6592. }
  6593. // Choose either the 32-bit or 64-bit version.
  6594. ExprResult LastIteration = LastIteration64;
  6595. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  6596. (LastIteration32.isUsable() &&
  6597. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  6598. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  6599. fitsInto(
  6600. /*Bits=*/32,
  6601. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  6602. LastIteration64.get(), SemaRef))))
  6603. LastIteration = LastIteration32;
  6604. QualType VType = LastIteration.get()->getType();
  6605. QualType RealVType = VType;
  6606. QualType StrideVType = VType;
  6607. if (isOpenMPTaskLoopDirective(DKind)) {
  6608. VType =
  6609. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  6610. StrideVType =
  6611. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  6612. }
  6613. if (!LastIteration.isUsable())
  6614. return 0;
  6615. // Save the number of iterations.
  6616. ExprResult NumIterations = LastIteration;
  6617. {
  6618. LastIteration = SemaRef.BuildBinOp(
  6619. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  6620. LastIteration.get(),
  6621. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6622. if (!LastIteration.isUsable())
  6623. return 0;
  6624. }
  6625. // Calculate the last iteration number beforehand instead of doing this on
  6626. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  6627. llvm::APSInt Result;
  6628. bool IsConstant =
  6629. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  6630. ExprResult CalcLastIteration;
  6631. if (!IsConstant) {
  6632. ExprResult SaveRef =
  6633. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  6634. LastIteration = SaveRef;
  6635. // Prepare SaveRef + 1.
  6636. NumIterations = SemaRef.BuildBinOp(
  6637. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  6638. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6639. if (!NumIterations.isUsable())
  6640. return 0;
  6641. }
  6642. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  6643. // Build variables passed into runtime, necessary for worksharing directives.
  6644. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  6645. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6646. isOpenMPDistributeDirective(DKind)) {
  6647. // Lower bound variable, initialized with zero.
  6648. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  6649. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  6650. SemaRef.AddInitializerToDecl(LBDecl,
  6651. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6652. /*DirectInit*/ false);
  6653. // Upper bound variable, initialized with last iteration number.
  6654. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  6655. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  6656. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  6657. /*DirectInit*/ false);
  6658. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  6659. // This will be used to implement clause 'lastprivate'.
  6660. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  6661. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  6662. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  6663. SemaRef.AddInitializerToDecl(ILDecl,
  6664. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6665. /*DirectInit*/ false);
  6666. // Stride variable returned by runtime (we initialize it to 1 by default).
  6667. VarDecl *STDecl =
  6668. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  6669. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  6670. SemaRef.AddInitializerToDecl(STDecl,
  6671. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  6672. /*DirectInit*/ false);
  6673. // Build expression: UB = min(UB, LastIteration)
  6674. // It is necessary for CodeGen of directives with static scheduling.
  6675. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  6676. UB.get(), LastIteration.get());
  6677. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6678. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  6679. LastIteration.get(), UB.get());
  6680. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  6681. CondOp.get());
  6682. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  6683. // If we have a combined directive that combines 'distribute', 'for' or
  6684. // 'simd' we need to be able to access the bounds of the schedule of the
  6685. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  6686. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  6687. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6688. // Lower bound variable, initialized with zero.
  6689. VarDecl *CombLBDecl =
  6690. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  6691. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  6692. SemaRef.AddInitializerToDecl(
  6693. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6694. /*DirectInit*/ false);
  6695. // Upper bound variable, initialized with last iteration number.
  6696. VarDecl *CombUBDecl =
  6697. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  6698. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  6699. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  6700. /*DirectInit*/ false);
  6701. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  6702. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  6703. ExprResult CombCondOp =
  6704. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  6705. LastIteration.get(), CombUB.get());
  6706. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  6707. CombCondOp.get());
  6708. CombEUB =
  6709. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  6710. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  6711. // We expect to have at least 2 more parameters than the 'parallel'
  6712. // directive does - the lower and upper bounds of the previous schedule.
  6713. assert(CD->getNumParams() >= 4 &&
  6714. "Unexpected number of parameters in loop combined directive");
  6715. // Set the proper type for the bounds given what we learned from the
  6716. // enclosed loops.
  6717. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  6718. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  6719. // Previous lower and upper bounds are obtained from the region
  6720. // parameters.
  6721. PrevLB =
  6722. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  6723. PrevUB =
  6724. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  6725. }
  6726. }
  6727. // Build the iteration variable and its initialization before loop.
  6728. ExprResult IV;
  6729. ExprResult Init, CombInit;
  6730. {
  6731. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  6732. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  6733. Expr *RHS =
  6734. (isOpenMPWorksharingDirective(DKind) ||
  6735. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6736. ? LB.get()
  6737. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6738. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  6739. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  6740. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6741. Expr *CombRHS =
  6742. (isOpenMPWorksharingDirective(DKind) ||
  6743. isOpenMPTaskLoopDirective(DKind) ||
  6744. isOpenMPDistributeDirective(DKind))
  6745. ? CombLB.get()
  6746. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6747. CombInit =
  6748. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  6749. CombInit =
  6750. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  6751. }
  6752. }
  6753. bool UseStrictCompare =
  6754. RealVType->hasUnsignedIntegerRepresentation() &&
  6755. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  6756. return LIS.IsStrictCompare;
  6757. });
  6758. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  6759. // unsigned IV)) for worksharing loops.
  6760. SourceLocation CondLoc = AStmt->getBeginLoc();
  6761. Expr *BoundUB = UB.get();
  6762. if (UseStrictCompare) {
  6763. BoundUB =
  6764. SemaRef
  6765. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  6766. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6767. .get();
  6768. BoundUB =
  6769. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  6770. }
  6771. ExprResult Cond =
  6772. (isOpenMPWorksharingDirective(DKind) ||
  6773. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6774. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  6775. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  6776. BoundUB)
  6777. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6778. NumIterations.get());
  6779. ExprResult CombDistCond;
  6780. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6781. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6782. NumIterations.get());
  6783. }
  6784. ExprResult CombCond;
  6785. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6786. Expr *BoundCombUB = CombUB.get();
  6787. if (UseStrictCompare) {
  6788. BoundCombUB =
  6789. SemaRef
  6790. .BuildBinOp(
  6791. CurScope, CondLoc, BO_Add, BoundCombUB,
  6792. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6793. .get();
  6794. BoundCombUB =
  6795. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  6796. .get();
  6797. }
  6798. CombCond =
  6799. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6800. IV.get(), BoundCombUB);
  6801. }
  6802. // Loop increment (IV = IV + 1)
  6803. SourceLocation IncLoc = AStmt->getBeginLoc();
  6804. ExprResult Inc =
  6805. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  6806. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  6807. if (!Inc.isUsable())
  6808. return 0;
  6809. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  6810. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  6811. if (!Inc.isUsable())
  6812. return 0;
  6813. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  6814. // Used for directives with static scheduling.
  6815. // In combined construct, add combined version that use CombLB and CombUB
  6816. // base variables for the update
  6817. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  6818. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6819. isOpenMPDistributeDirective(DKind)) {
  6820. // LB + ST
  6821. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  6822. if (!NextLB.isUsable())
  6823. return 0;
  6824. // LB = LB + ST
  6825. NextLB =
  6826. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  6827. NextLB =
  6828. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  6829. if (!NextLB.isUsable())
  6830. return 0;
  6831. // UB + ST
  6832. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  6833. if (!NextUB.isUsable())
  6834. return 0;
  6835. // UB = UB + ST
  6836. NextUB =
  6837. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  6838. NextUB =
  6839. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  6840. if (!NextUB.isUsable())
  6841. return 0;
  6842. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6843. CombNextLB =
  6844. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  6845. if (!NextLB.isUsable())
  6846. return 0;
  6847. // LB = LB + ST
  6848. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  6849. CombNextLB.get());
  6850. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  6851. /*DiscardedValue*/ false);
  6852. if (!CombNextLB.isUsable())
  6853. return 0;
  6854. // UB + ST
  6855. CombNextUB =
  6856. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  6857. if (!CombNextUB.isUsable())
  6858. return 0;
  6859. // UB = UB + ST
  6860. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  6861. CombNextUB.get());
  6862. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  6863. /*DiscardedValue*/ false);
  6864. if (!CombNextUB.isUsable())
  6865. return 0;
  6866. }
  6867. }
  6868. // Create increment expression for distribute loop when combined in a same
  6869. // directive with for as IV = IV + ST; ensure upper bound expression based
  6870. // on PrevUB instead of NumIterations - used to implement 'for' when found
  6871. // in combination with 'distribute', like in 'distribute parallel for'
  6872. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  6873. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  6874. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6875. DistCond = SemaRef.BuildBinOp(
  6876. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  6877. assert(DistCond.isUsable() && "distribute cond expr was not built");
  6878. DistInc =
  6879. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  6880. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6881. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  6882. DistInc.get());
  6883. DistInc =
  6884. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  6885. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6886. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  6887. // construct
  6888. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  6889. ExprResult IsUBGreater =
  6890. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  6891. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6892. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  6893. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  6894. CondOp.get());
  6895. PrevEUB =
  6896. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  6897. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  6898. // parallel for is in combination with a distribute directive with
  6899. // schedule(static, 1)
  6900. Expr *BoundPrevUB = PrevUB.get();
  6901. if (UseStrictCompare) {
  6902. BoundPrevUB =
  6903. SemaRef
  6904. .BuildBinOp(
  6905. CurScope, CondLoc, BO_Add, BoundPrevUB,
  6906. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6907. .get();
  6908. BoundPrevUB =
  6909. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  6910. .get();
  6911. }
  6912. ParForInDistCond =
  6913. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6914. IV.get(), BoundPrevUB);
  6915. }
  6916. // Build updates and final values of the loop counters.
  6917. bool HasErrors = false;
  6918. Built.Counters.resize(NestedLoopCount);
  6919. Built.Inits.resize(NestedLoopCount);
  6920. Built.Updates.resize(NestedLoopCount);
  6921. Built.Finals.resize(NestedLoopCount);
  6922. Built.DependentCounters.resize(NestedLoopCount);
  6923. Built.DependentInits.resize(NestedLoopCount);
  6924. Built.FinalsConditions.resize(NestedLoopCount);
  6925. {
  6926. // We implement the following algorithm for obtaining the
  6927. // original loop iteration variable values based on the
  6928. // value of the collapsed loop iteration variable IV.
  6929. //
  6930. // Let n+1 be the number of collapsed loops in the nest.
  6931. // Iteration variables (I0, I1, .... In)
  6932. // Iteration counts (N0, N1, ... Nn)
  6933. //
  6934. // Acc = IV;
  6935. //
  6936. // To compute Ik for loop k, 0 <= k <= n, generate:
  6937. // Prod = N(k+1) * N(k+2) * ... * Nn;
  6938. // Ik = Acc / Prod;
  6939. // Acc -= Ik * Prod;
  6940. //
  6941. ExprResult Acc = IV;
  6942. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6943. LoopIterationSpace &IS = IterSpaces[Cnt];
  6944. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  6945. ExprResult Iter;
  6946. // Compute prod
  6947. ExprResult Prod =
  6948. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  6949. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  6950. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  6951. IterSpaces[K].NumIterations);
  6952. // Iter = Acc / Prod
  6953. // If there is at least one more inner loop to avoid
  6954. // multiplication by 1.
  6955. if (Cnt + 1 < NestedLoopCount)
  6956. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  6957. Acc.get(), Prod.get());
  6958. else
  6959. Iter = Acc;
  6960. if (!Iter.isUsable()) {
  6961. HasErrors = true;
  6962. break;
  6963. }
  6964. // Update Acc:
  6965. // Acc -= Iter * Prod
  6966. // Check if there is at least one more inner loop to avoid
  6967. // multiplication by 1.
  6968. if (Cnt + 1 < NestedLoopCount)
  6969. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  6970. Iter.get(), Prod.get());
  6971. else
  6972. Prod = Iter;
  6973. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  6974. Acc.get(), Prod.get());
  6975. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  6976. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  6977. DeclRefExpr *CounterVar = buildDeclRefExpr(
  6978. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  6979. /*RefersToCapture=*/true);
  6980. ExprResult Init =
  6981. buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  6982. IS.CounterInit, IS.IsNonRectangularLB, Captures);
  6983. if (!Init.isUsable()) {
  6984. HasErrors = true;
  6985. break;
  6986. }
  6987. ExprResult Update = buildCounterUpdate(
  6988. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  6989. IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
  6990. if (!Update.isUsable()) {
  6991. HasErrors = true;
  6992. break;
  6993. }
  6994. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  6995. ExprResult Final =
  6996. buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  6997. IS.CounterInit, IS.NumIterations, IS.CounterStep,
  6998. IS.Subtract, IS.IsNonRectangularLB, &Captures);
  6999. if (!Final.isUsable()) {
  7000. HasErrors = true;
  7001. break;
  7002. }
  7003. if (!Update.isUsable() || !Final.isUsable()) {
  7004. HasErrors = true;
  7005. break;
  7006. }
  7007. // Save results
  7008. Built.Counters[Cnt] = IS.CounterVar;
  7009. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  7010. Built.Inits[Cnt] = Init.get();
  7011. Built.Updates[Cnt] = Update.get();
  7012. Built.Finals[Cnt] = Final.get();
  7013. Built.DependentCounters[Cnt] = nullptr;
  7014. Built.DependentInits[Cnt] = nullptr;
  7015. Built.FinalsConditions[Cnt] = nullptr;
  7016. if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
  7017. Built.DependentCounters[Cnt] =
  7018. Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7019. Built.DependentInits[Cnt] =
  7020. Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7021. Built.FinalsConditions[Cnt] = IS.FinalCondition;
  7022. }
  7023. }
  7024. }
  7025. if (HasErrors)
  7026. return 0;
  7027. // Save results
  7028. Built.IterationVarRef = IV.get();
  7029. Built.LastIteration = LastIteration.get();
  7030. Built.NumIterations = NumIterations.get();
  7031. Built.CalcLastIteration = SemaRef
  7032. .ActOnFinishFullExpr(CalcLastIteration.get(),
  7033. /*DiscardedValue=*/false)
  7034. .get();
  7035. Built.PreCond = PreCond.get();
  7036. Built.PreInits = buildPreInits(C, Captures);
  7037. Built.Cond = Cond.get();
  7038. Built.Init = Init.get();
  7039. Built.Inc = Inc.get();
  7040. Built.LB = LB.get();
  7041. Built.UB = UB.get();
  7042. Built.IL = IL.get();
  7043. Built.ST = ST.get();
  7044. Built.EUB = EUB.get();
  7045. Built.NLB = NextLB.get();
  7046. Built.NUB = NextUB.get();
  7047. Built.PrevLB = PrevLB.get();
  7048. Built.PrevUB = PrevUB.get();
  7049. Built.DistInc = DistInc.get();
  7050. Built.PrevEUB = PrevEUB.get();
  7051. Built.DistCombinedFields.LB = CombLB.get();
  7052. Built.DistCombinedFields.UB = CombUB.get();
  7053. Built.DistCombinedFields.EUB = CombEUB.get();
  7054. Built.DistCombinedFields.Init = CombInit.get();
  7055. Built.DistCombinedFields.Cond = CombCond.get();
  7056. Built.DistCombinedFields.NLB = CombNextLB.get();
  7057. Built.DistCombinedFields.NUB = CombNextUB.get();
  7058. Built.DistCombinedFields.DistCond = CombDistCond.get();
  7059. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  7060. return NestedLoopCount;
  7061. }
  7062. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7063. auto CollapseClauses =
  7064. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  7065. if (CollapseClauses.begin() != CollapseClauses.end())
  7066. return (*CollapseClauses.begin())->getNumForLoops();
  7067. return nullptr;
  7068. }
  7069. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7070. auto OrderedClauses =
  7071. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  7072. if (OrderedClauses.begin() != OrderedClauses.end())
  7073. return (*OrderedClauses.begin())->getNumForLoops();
  7074. return nullptr;
  7075. }
  7076. static bool checkSimdlenSafelenSpecified(Sema &S,
  7077. const ArrayRef<OMPClause *> Clauses) {
  7078. const OMPSafelenClause *Safelen = nullptr;
  7079. const OMPSimdlenClause *Simdlen = nullptr;
  7080. for (const OMPClause *Clause : Clauses) {
  7081. if (Clause->getClauseKind() == OMPC_safelen)
  7082. Safelen = cast<OMPSafelenClause>(Clause);
  7083. else if (Clause->getClauseKind() == OMPC_simdlen)
  7084. Simdlen = cast<OMPSimdlenClause>(Clause);
  7085. if (Safelen && Simdlen)
  7086. break;
  7087. }
  7088. if (Simdlen && Safelen) {
  7089. const Expr *SimdlenLength = Simdlen->getSimdlen();
  7090. const Expr *SafelenLength = Safelen->getSafelen();
  7091. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  7092. SimdlenLength->isInstantiationDependent() ||
  7093. SimdlenLength->containsUnexpandedParameterPack())
  7094. return false;
  7095. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  7096. SafelenLength->isInstantiationDependent() ||
  7097. SafelenLength->containsUnexpandedParameterPack())
  7098. return false;
  7099. Expr::EvalResult SimdlenResult, SafelenResult;
  7100. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  7101. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  7102. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  7103. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  7104. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  7105. // If both simdlen and safelen clauses are specified, the value of the
  7106. // simdlen parameter must be less than or equal to the value of the safelen
  7107. // parameter.
  7108. if (SimdlenRes > SafelenRes) {
  7109. S.Diag(SimdlenLength->getExprLoc(),
  7110. diag::err_omp_wrong_simdlen_safelen_values)
  7111. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  7112. return true;
  7113. }
  7114. }
  7115. return false;
  7116. }
  7117. StmtResult
  7118. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7119. SourceLocation StartLoc, SourceLocation EndLoc,
  7120. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7121. if (!AStmt)
  7122. return StmtError();
  7123. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7124. OMPLoopDirective::HelperExprs B;
  7125. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7126. // define the nested loops number.
  7127. unsigned NestedLoopCount = checkOpenMPLoop(
  7128. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7129. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7130. if (NestedLoopCount == 0)
  7131. return StmtError();
  7132. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7133. "omp simd loop exprs were not built");
  7134. if (!CurContext->isDependentContext()) {
  7135. // Finalize the clauses that need pre-built expressions for CodeGen.
  7136. for (OMPClause *C : Clauses) {
  7137. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7138. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7139. B.NumIterations, *this, CurScope,
  7140. DSAStack))
  7141. return StmtError();
  7142. }
  7143. }
  7144. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7145. return StmtError();
  7146. setFunctionHasBranchProtectedScope();
  7147. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7148. Clauses, AStmt, B);
  7149. }
  7150. StmtResult
  7151. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7152. SourceLocation StartLoc, SourceLocation EndLoc,
  7153. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7154. if (!AStmt)
  7155. return StmtError();
  7156. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7157. OMPLoopDirective::HelperExprs B;
  7158. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7159. // define the nested loops number.
  7160. unsigned NestedLoopCount = checkOpenMPLoop(
  7161. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7162. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7163. if (NestedLoopCount == 0)
  7164. return StmtError();
  7165. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7166. "omp for loop exprs were not built");
  7167. if (!CurContext->isDependentContext()) {
  7168. // Finalize the clauses that need pre-built expressions for CodeGen.
  7169. for (OMPClause *C : Clauses) {
  7170. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7171. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7172. B.NumIterations, *this, CurScope,
  7173. DSAStack))
  7174. return StmtError();
  7175. }
  7176. }
  7177. setFunctionHasBranchProtectedScope();
  7178. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7179. Clauses, AStmt, B, DSAStack->isCancelRegion());
  7180. }
  7181. StmtResult Sema::ActOnOpenMPForSimdDirective(
  7182. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7183. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7184. if (!AStmt)
  7185. return StmtError();
  7186. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7187. OMPLoopDirective::HelperExprs B;
  7188. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7189. // define the nested loops number.
  7190. unsigned NestedLoopCount =
  7191. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  7192. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7193. VarsWithImplicitDSA, B);
  7194. if (NestedLoopCount == 0)
  7195. return StmtError();
  7196. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7197. "omp for simd loop exprs were not built");
  7198. if (!CurContext->isDependentContext()) {
  7199. // Finalize the clauses that need pre-built expressions for CodeGen.
  7200. for (OMPClause *C : Clauses) {
  7201. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7202. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7203. B.NumIterations, *this, CurScope,
  7204. DSAStack))
  7205. return StmtError();
  7206. }
  7207. }
  7208. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7209. return StmtError();
  7210. setFunctionHasBranchProtectedScope();
  7211. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7212. Clauses, AStmt, B);
  7213. }
  7214. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7215. Stmt *AStmt,
  7216. SourceLocation StartLoc,
  7217. SourceLocation EndLoc) {
  7218. if (!AStmt)
  7219. return StmtError();
  7220. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7221. auto BaseStmt = AStmt;
  7222. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7223. BaseStmt = CS->getCapturedStmt();
  7224. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7225. auto S = C->children();
  7226. if (S.begin() == S.end())
  7227. return StmtError();
  7228. // All associated statements must be '#pragma omp section' except for
  7229. // the first one.
  7230. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7231. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7232. if (SectionStmt)
  7233. Diag(SectionStmt->getBeginLoc(),
  7234. diag::err_omp_sections_substmt_not_section);
  7235. return StmtError();
  7236. }
  7237. cast<OMPSectionDirective>(SectionStmt)
  7238. ->setHasCancel(DSAStack->isCancelRegion());
  7239. }
  7240. } else {
  7241. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  7242. return StmtError();
  7243. }
  7244. setFunctionHasBranchProtectedScope();
  7245. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7246. DSAStack->isCancelRegion());
  7247. }
  7248. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  7249. SourceLocation StartLoc,
  7250. SourceLocation EndLoc) {
  7251. if (!AStmt)
  7252. return StmtError();
  7253. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7254. setFunctionHasBranchProtectedScope();
  7255. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  7256. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  7257. DSAStack->isCancelRegion());
  7258. }
  7259. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  7260. Stmt *AStmt,
  7261. SourceLocation StartLoc,
  7262. SourceLocation EndLoc) {
  7263. if (!AStmt)
  7264. return StmtError();
  7265. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7266. setFunctionHasBranchProtectedScope();
  7267. // OpenMP [2.7.3, single Construct, Restrictions]
  7268. // The copyprivate clause must not be used with the nowait clause.
  7269. const OMPClause *Nowait = nullptr;
  7270. const OMPClause *Copyprivate = nullptr;
  7271. for (const OMPClause *Clause : Clauses) {
  7272. if (Clause->getClauseKind() == OMPC_nowait)
  7273. Nowait = Clause;
  7274. else if (Clause->getClauseKind() == OMPC_copyprivate)
  7275. Copyprivate = Clause;
  7276. if (Copyprivate && Nowait) {
  7277. Diag(Copyprivate->getBeginLoc(),
  7278. diag::err_omp_single_copyprivate_with_nowait);
  7279. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  7280. return StmtError();
  7281. }
  7282. }
  7283. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7284. }
  7285. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  7286. SourceLocation StartLoc,
  7287. SourceLocation EndLoc) {
  7288. if (!AStmt)
  7289. return StmtError();
  7290. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7291. setFunctionHasBranchProtectedScope();
  7292. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  7293. }
  7294. StmtResult Sema::ActOnOpenMPCriticalDirective(
  7295. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  7296. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  7297. if (!AStmt)
  7298. return StmtError();
  7299. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7300. bool ErrorFound = false;
  7301. llvm::APSInt Hint;
  7302. SourceLocation HintLoc;
  7303. bool DependentHint = false;
  7304. for (const OMPClause *C : Clauses) {
  7305. if (C->getClauseKind() == OMPC_hint) {
  7306. if (!DirName.getName()) {
  7307. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  7308. ErrorFound = true;
  7309. }
  7310. Expr *E = cast<OMPHintClause>(C)->getHint();
  7311. if (E->isTypeDependent() || E->isValueDependent() ||
  7312. E->isInstantiationDependent()) {
  7313. DependentHint = true;
  7314. } else {
  7315. Hint = E->EvaluateKnownConstInt(Context);
  7316. HintLoc = C->getBeginLoc();
  7317. }
  7318. }
  7319. }
  7320. if (ErrorFound)
  7321. return StmtError();
  7322. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  7323. if (Pair.first && DirName.getName() && !DependentHint) {
  7324. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  7325. Diag(StartLoc, diag::err_omp_critical_with_hint);
  7326. if (HintLoc.isValid())
  7327. Diag(HintLoc, diag::note_omp_critical_hint_here)
  7328. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  7329. else
  7330. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  7331. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  7332. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  7333. << 1
  7334. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  7335. /*Radix=*/10, /*Signed=*/false);
  7336. } else {
  7337. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  7338. }
  7339. }
  7340. }
  7341. setFunctionHasBranchProtectedScope();
  7342. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  7343. Clauses, AStmt);
  7344. if (!Pair.first && DirName.getName() && !DependentHint)
  7345. DSAStack->addCriticalWithHint(Dir, Hint);
  7346. return Dir;
  7347. }
  7348. StmtResult Sema::ActOnOpenMPParallelForDirective(
  7349. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7350. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7351. if (!AStmt)
  7352. return StmtError();
  7353. auto *CS = cast<CapturedStmt>(AStmt);
  7354. // 1.2.2 OpenMP Language Terminology
  7355. // Structured block - An executable statement with a single entry at the
  7356. // top and a single exit at the bottom.
  7357. // The point of exit cannot be a branch out of the structured block.
  7358. // longjmp() and throw() must not violate the entry/exit criteria.
  7359. CS->getCapturedDecl()->setNothrow();
  7360. OMPLoopDirective::HelperExprs B;
  7361. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7362. // define the nested loops number.
  7363. unsigned NestedLoopCount =
  7364. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  7365. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7366. VarsWithImplicitDSA, B);
  7367. if (NestedLoopCount == 0)
  7368. return StmtError();
  7369. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7370. "omp parallel for loop exprs were not built");
  7371. if (!CurContext->isDependentContext()) {
  7372. // Finalize the clauses that need pre-built expressions for CodeGen.
  7373. for (OMPClause *C : Clauses) {
  7374. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7375. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7376. B.NumIterations, *this, CurScope,
  7377. DSAStack))
  7378. return StmtError();
  7379. }
  7380. }
  7381. setFunctionHasBranchProtectedScope();
  7382. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  7383. NestedLoopCount, Clauses, AStmt, B,
  7384. DSAStack->isCancelRegion());
  7385. }
  7386. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  7387. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7388. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7389. if (!AStmt)
  7390. return StmtError();
  7391. auto *CS = cast<CapturedStmt>(AStmt);
  7392. // 1.2.2 OpenMP Language Terminology
  7393. // Structured block - An executable statement with a single entry at the
  7394. // top and a single exit at the bottom.
  7395. // The point of exit cannot be a branch out of the structured block.
  7396. // longjmp() and throw() must not violate the entry/exit criteria.
  7397. CS->getCapturedDecl()->setNothrow();
  7398. OMPLoopDirective::HelperExprs B;
  7399. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7400. // define the nested loops number.
  7401. unsigned NestedLoopCount =
  7402. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7403. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7404. VarsWithImplicitDSA, B);
  7405. if (NestedLoopCount == 0)
  7406. return StmtError();
  7407. if (!CurContext->isDependentContext()) {
  7408. // Finalize the clauses that need pre-built expressions for CodeGen.
  7409. for (OMPClause *C : Clauses) {
  7410. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7411. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7412. B.NumIterations, *this, CurScope,
  7413. DSAStack))
  7414. return StmtError();
  7415. }
  7416. }
  7417. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7418. return StmtError();
  7419. setFunctionHasBranchProtectedScope();
  7420. return OMPParallelForSimdDirective::Create(
  7421. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7422. }
  7423. StmtResult
  7424. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7425. Stmt *AStmt, SourceLocation StartLoc,
  7426. SourceLocation EndLoc) {
  7427. if (!AStmt)
  7428. return StmtError();
  7429. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7430. auto BaseStmt = AStmt;
  7431. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7432. BaseStmt = CS->getCapturedStmt();
  7433. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7434. auto S = C->children();
  7435. if (S.begin() == S.end())
  7436. return StmtError();
  7437. // All associated statements must be '#pragma omp section' except for
  7438. // the first one.
  7439. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7440. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7441. if (SectionStmt)
  7442. Diag(SectionStmt->getBeginLoc(),
  7443. diag::err_omp_parallel_sections_substmt_not_section);
  7444. return StmtError();
  7445. }
  7446. cast<OMPSectionDirective>(SectionStmt)
  7447. ->setHasCancel(DSAStack->isCancelRegion());
  7448. }
  7449. } else {
  7450. Diag(AStmt->getBeginLoc(),
  7451. diag::err_omp_parallel_sections_not_compound_stmt);
  7452. return StmtError();
  7453. }
  7454. setFunctionHasBranchProtectedScope();
  7455. return OMPParallelSectionsDirective::Create(
  7456. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  7457. }
  7458. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  7459. Stmt *AStmt, SourceLocation StartLoc,
  7460. SourceLocation EndLoc) {
  7461. if (!AStmt)
  7462. return StmtError();
  7463. auto *CS = cast<CapturedStmt>(AStmt);
  7464. // 1.2.2 OpenMP Language Terminology
  7465. // Structured block - An executable statement with a single entry at the
  7466. // top and a single exit at the bottom.
  7467. // The point of exit cannot be a branch out of the structured block.
  7468. // longjmp() and throw() must not violate the entry/exit criteria.
  7469. CS->getCapturedDecl()->setNothrow();
  7470. setFunctionHasBranchProtectedScope();
  7471. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7472. DSAStack->isCancelRegion());
  7473. }
  7474. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  7475. SourceLocation EndLoc) {
  7476. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  7477. }
  7478. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  7479. SourceLocation EndLoc) {
  7480. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  7481. }
  7482. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  7483. SourceLocation EndLoc) {
  7484. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  7485. }
  7486. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  7487. Stmt *AStmt,
  7488. SourceLocation StartLoc,
  7489. SourceLocation EndLoc) {
  7490. if (!AStmt)
  7491. return StmtError();
  7492. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7493. setFunctionHasBranchProtectedScope();
  7494. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7495. AStmt,
  7496. DSAStack->getTaskgroupReductionRef());
  7497. }
  7498. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  7499. SourceLocation StartLoc,
  7500. SourceLocation EndLoc) {
  7501. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  7502. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  7503. }
  7504. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  7505. Stmt *AStmt,
  7506. SourceLocation StartLoc,
  7507. SourceLocation EndLoc) {
  7508. const OMPClause *DependFound = nullptr;
  7509. const OMPClause *DependSourceClause = nullptr;
  7510. const OMPClause *DependSinkClause = nullptr;
  7511. bool ErrorFound = false;
  7512. const OMPThreadsClause *TC = nullptr;
  7513. const OMPSIMDClause *SC = nullptr;
  7514. for (const OMPClause *C : Clauses) {
  7515. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  7516. DependFound = C;
  7517. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  7518. if (DependSourceClause) {
  7519. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  7520. << getOpenMPDirectiveName(OMPD_ordered)
  7521. << getOpenMPClauseName(OMPC_depend) << 2;
  7522. ErrorFound = true;
  7523. } else {
  7524. DependSourceClause = C;
  7525. }
  7526. if (DependSinkClause) {
  7527. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7528. << 0;
  7529. ErrorFound = true;
  7530. }
  7531. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  7532. if (DependSourceClause) {
  7533. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7534. << 1;
  7535. ErrorFound = true;
  7536. }
  7537. DependSinkClause = C;
  7538. }
  7539. } else if (C->getClauseKind() == OMPC_threads) {
  7540. TC = cast<OMPThreadsClause>(C);
  7541. } else if (C->getClauseKind() == OMPC_simd) {
  7542. SC = cast<OMPSIMDClause>(C);
  7543. }
  7544. }
  7545. if (!ErrorFound && !SC &&
  7546. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  7547. // OpenMP [2.8.1,simd Construct, Restrictions]
  7548. // An ordered construct with the simd clause is the only OpenMP construct
  7549. // that can appear in the simd region.
  7550. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  7551. ErrorFound = true;
  7552. } else if (DependFound && (TC || SC)) {
  7553. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  7554. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  7555. ErrorFound = true;
  7556. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  7557. Diag(DependFound->getBeginLoc(),
  7558. diag::err_omp_ordered_directive_without_param);
  7559. ErrorFound = true;
  7560. } else if (TC || Clauses.empty()) {
  7561. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  7562. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  7563. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  7564. << (TC != nullptr);
  7565. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  7566. ErrorFound = true;
  7567. }
  7568. }
  7569. if ((!AStmt && !DependFound) || ErrorFound)
  7570. return StmtError();
  7571. if (AStmt) {
  7572. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7573. setFunctionHasBranchProtectedScope();
  7574. }
  7575. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7576. }
  7577. namespace {
  7578. /// Helper class for checking expression in 'omp atomic [update]'
  7579. /// construct.
  7580. class OpenMPAtomicUpdateChecker {
  7581. /// Error results for atomic update expressions.
  7582. enum ExprAnalysisErrorCode {
  7583. /// A statement is not an expression statement.
  7584. NotAnExpression,
  7585. /// Expression is not builtin binary or unary operation.
  7586. NotABinaryOrUnaryExpression,
  7587. /// Unary operation is not post-/pre- increment/decrement operation.
  7588. NotAnUnaryIncDecExpression,
  7589. /// An expression is not of scalar type.
  7590. NotAScalarType,
  7591. /// A binary operation is not an assignment operation.
  7592. NotAnAssignmentOp,
  7593. /// RHS part of the binary operation is not a binary expression.
  7594. NotABinaryExpression,
  7595. /// RHS part is not additive/multiplicative/shift/biwise binary
  7596. /// expression.
  7597. NotABinaryOperator,
  7598. /// RHS binary operation does not have reference to the updated LHS
  7599. /// part.
  7600. NotAnUpdateExpression,
  7601. /// No errors is found.
  7602. NoError
  7603. };
  7604. /// Reference to Sema.
  7605. Sema &SemaRef;
  7606. /// A location for note diagnostics (when error is found).
  7607. SourceLocation NoteLoc;
  7608. /// 'x' lvalue part of the source atomic expression.
  7609. Expr *X;
  7610. /// 'expr' rvalue part of the source atomic expression.
  7611. Expr *E;
  7612. /// Helper expression of the form
  7613. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7614. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7615. Expr *UpdateExpr;
  7616. /// Is 'x' a LHS in a RHS part of full update expression. It is
  7617. /// important for non-associative operations.
  7618. bool IsXLHSInRHSPart;
  7619. BinaryOperatorKind Op;
  7620. SourceLocation OpLoc;
  7621. /// true if the source expression is a postfix unary operation, false
  7622. /// if it is a prefix unary operation.
  7623. bool IsPostfixUpdate;
  7624. public:
  7625. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  7626. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  7627. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  7628. /// Check specified statement that it is suitable for 'atomic update'
  7629. /// constructs and extract 'x', 'expr' and Operation from the original
  7630. /// expression. If DiagId and NoteId == 0, then only check is performed
  7631. /// without error notification.
  7632. /// \param DiagId Diagnostic which should be emitted if error is found.
  7633. /// \param NoteId Diagnostic note for the main error message.
  7634. /// \return true if statement is not an update expression, false otherwise.
  7635. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  7636. /// Return the 'x' lvalue part of the source atomic expression.
  7637. Expr *getX() const { return X; }
  7638. /// Return the 'expr' rvalue part of the source atomic expression.
  7639. Expr *getExpr() const { return E; }
  7640. /// Return the update expression used in calculation of the updated
  7641. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7642. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7643. Expr *getUpdateExpr() const { return UpdateExpr; }
  7644. /// Return true if 'x' is LHS in RHS part of full update expression,
  7645. /// false otherwise.
  7646. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  7647. /// true if the source expression is a postfix unary operation, false
  7648. /// if it is a prefix unary operation.
  7649. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  7650. private:
  7651. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  7652. unsigned NoteId = 0);
  7653. };
  7654. } // namespace
  7655. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  7656. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  7657. ExprAnalysisErrorCode ErrorFound = NoError;
  7658. SourceLocation ErrorLoc, NoteLoc;
  7659. SourceRange ErrorRange, NoteRange;
  7660. // Allowed constructs are:
  7661. // x = x binop expr;
  7662. // x = expr binop x;
  7663. if (AtomicBinOp->getOpcode() == BO_Assign) {
  7664. X = AtomicBinOp->getLHS();
  7665. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  7666. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  7667. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  7668. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  7669. AtomicInnerBinOp->isBitwiseOp()) {
  7670. Op = AtomicInnerBinOp->getOpcode();
  7671. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  7672. Expr *LHS = AtomicInnerBinOp->getLHS();
  7673. Expr *RHS = AtomicInnerBinOp->getRHS();
  7674. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  7675. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  7676. /*Canonical=*/true);
  7677. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  7678. /*Canonical=*/true);
  7679. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  7680. /*Canonical=*/true);
  7681. if (XId == LHSId) {
  7682. E = RHS;
  7683. IsXLHSInRHSPart = true;
  7684. } else if (XId == RHSId) {
  7685. E = LHS;
  7686. IsXLHSInRHSPart = false;
  7687. } else {
  7688. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7689. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7690. NoteLoc = X->getExprLoc();
  7691. NoteRange = X->getSourceRange();
  7692. ErrorFound = NotAnUpdateExpression;
  7693. }
  7694. } else {
  7695. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7696. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7697. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  7698. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7699. ErrorFound = NotABinaryOperator;
  7700. }
  7701. } else {
  7702. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  7703. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  7704. ErrorFound = NotABinaryExpression;
  7705. }
  7706. } else {
  7707. ErrorLoc = AtomicBinOp->getExprLoc();
  7708. ErrorRange = AtomicBinOp->getSourceRange();
  7709. NoteLoc = AtomicBinOp->getOperatorLoc();
  7710. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7711. ErrorFound = NotAnAssignmentOp;
  7712. }
  7713. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7714. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7715. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7716. return true;
  7717. }
  7718. if (SemaRef.CurContext->isDependentContext())
  7719. E = X = UpdateExpr = nullptr;
  7720. return ErrorFound != NoError;
  7721. }
  7722. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  7723. unsigned NoteId) {
  7724. ExprAnalysisErrorCode ErrorFound = NoError;
  7725. SourceLocation ErrorLoc, NoteLoc;
  7726. SourceRange ErrorRange, NoteRange;
  7727. // Allowed constructs are:
  7728. // x++;
  7729. // x--;
  7730. // ++x;
  7731. // --x;
  7732. // x binop= expr;
  7733. // x = x binop expr;
  7734. // x = expr binop x;
  7735. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  7736. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  7737. if (AtomicBody->getType()->isScalarType() ||
  7738. AtomicBody->isInstantiationDependent()) {
  7739. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  7740. AtomicBody->IgnoreParenImpCasts())) {
  7741. // Check for Compound Assignment Operation
  7742. Op = BinaryOperator::getOpForCompoundAssignment(
  7743. AtomicCompAssignOp->getOpcode());
  7744. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  7745. E = AtomicCompAssignOp->getRHS();
  7746. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  7747. IsXLHSInRHSPart = true;
  7748. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  7749. AtomicBody->IgnoreParenImpCasts())) {
  7750. // Check for Binary Operation
  7751. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  7752. return true;
  7753. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  7754. AtomicBody->IgnoreParenImpCasts())) {
  7755. // Check for Unary Operation
  7756. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  7757. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  7758. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  7759. OpLoc = AtomicUnaryOp->getOperatorLoc();
  7760. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  7761. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  7762. IsXLHSInRHSPart = true;
  7763. } else {
  7764. ErrorFound = NotAnUnaryIncDecExpression;
  7765. ErrorLoc = AtomicUnaryOp->getExprLoc();
  7766. ErrorRange = AtomicUnaryOp->getSourceRange();
  7767. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  7768. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7769. }
  7770. } else if (!AtomicBody->isInstantiationDependent()) {
  7771. ErrorFound = NotABinaryOrUnaryExpression;
  7772. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  7773. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  7774. }
  7775. } else {
  7776. ErrorFound = NotAScalarType;
  7777. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  7778. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7779. }
  7780. } else {
  7781. ErrorFound = NotAnExpression;
  7782. NoteLoc = ErrorLoc = S->getBeginLoc();
  7783. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7784. }
  7785. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7786. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7787. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7788. return true;
  7789. }
  7790. if (SemaRef.CurContext->isDependentContext())
  7791. E = X = UpdateExpr = nullptr;
  7792. if (ErrorFound == NoError && E && X) {
  7793. // Build an update expression of form 'OpaqueValueExpr(x) binop
  7794. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  7795. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  7796. auto *OVEX = new (SemaRef.getASTContext())
  7797. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  7798. auto *OVEExpr = new (SemaRef.getASTContext())
  7799. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  7800. ExprResult Update =
  7801. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  7802. IsXLHSInRHSPart ? OVEExpr : OVEX);
  7803. if (Update.isInvalid())
  7804. return true;
  7805. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  7806. Sema::AA_Casting);
  7807. if (Update.isInvalid())
  7808. return true;
  7809. UpdateExpr = Update.get();
  7810. }
  7811. return ErrorFound != NoError;
  7812. }
  7813. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  7814. Stmt *AStmt,
  7815. SourceLocation StartLoc,
  7816. SourceLocation EndLoc) {
  7817. if (!AStmt)
  7818. return StmtError();
  7819. auto *CS = cast<CapturedStmt>(AStmt);
  7820. // 1.2.2 OpenMP Language Terminology
  7821. // Structured block - An executable statement with a single entry at the
  7822. // top and a single exit at the bottom.
  7823. // The point of exit cannot be a branch out of the structured block.
  7824. // longjmp() and throw() must not violate the entry/exit criteria.
  7825. OpenMPClauseKind AtomicKind = OMPC_unknown;
  7826. SourceLocation AtomicKindLoc;
  7827. for (const OMPClause *C : Clauses) {
  7828. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  7829. C->getClauseKind() == OMPC_update ||
  7830. C->getClauseKind() == OMPC_capture) {
  7831. if (AtomicKind != OMPC_unknown) {
  7832. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  7833. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  7834. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  7835. << getOpenMPClauseName(AtomicKind);
  7836. } else {
  7837. AtomicKind = C->getClauseKind();
  7838. AtomicKindLoc = C->getBeginLoc();
  7839. }
  7840. }
  7841. }
  7842. Stmt *Body = CS->getCapturedStmt();
  7843. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  7844. Body = EWC->getSubExpr();
  7845. Expr *X = nullptr;
  7846. Expr *V = nullptr;
  7847. Expr *E = nullptr;
  7848. Expr *UE = nullptr;
  7849. bool IsXLHSInRHSPart = false;
  7850. bool IsPostfixUpdate = false;
  7851. // OpenMP [2.12.6, atomic Construct]
  7852. // In the next expressions:
  7853. // * x and v (as applicable) are both l-value expressions with scalar type.
  7854. // * During the execution of an atomic region, multiple syntactic
  7855. // occurrences of x must designate the same storage location.
  7856. // * Neither of v and expr (as applicable) may access the storage location
  7857. // designated by x.
  7858. // * Neither of x and expr (as applicable) may access the storage location
  7859. // designated by v.
  7860. // * expr is an expression with scalar type.
  7861. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  7862. // * binop, binop=, ++, and -- are not overloaded operators.
  7863. // * The expression x binop expr must be numerically equivalent to x binop
  7864. // (expr). This requirement is satisfied if the operators in expr have
  7865. // precedence greater than binop, or by using parentheses around expr or
  7866. // subexpressions of expr.
  7867. // * The expression expr binop x must be numerically equivalent to (expr)
  7868. // binop x. This requirement is satisfied if the operators in expr have
  7869. // precedence equal to or greater than binop, or by using parentheses around
  7870. // expr or subexpressions of expr.
  7871. // * For forms that allow multiple occurrences of x, the number of times
  7872. // that x is evaluated is unspecified.
  7873. if (AtomicKind == OMPC_read) {
  7874. enum {
  7875. NotAnExpression,
  7876. NotAnAssignmentOp,
  7877. NotAScalarType,
  7878. NotAnLValue,
  7879. NoError
  7880. } ErrorFound = NoError;
  7881. SourceLocation ErrorLoc, NoteLoc;
  7882. SourceRange ErrorRange, NoteRange;
  7883. // If clause is read:
  7884. // v = x;
  7885. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7886. const auto *AtomicBinOp =
  7887. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7888. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7889. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  7890. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  7891. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7892. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  7893. if (!X->isLValue() || !V->isLValue()) {
  7894. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  7895. ErrorFound = NotAnLValue;
  7896. ErrorLoc = AtomicBinOp->getExprLoc();
  7897. ErrorRange = AtomicBinOp->getSourceRange();
  7898. NoteLoc = NotLValueExpr->getExprLoc();
  7899. NoteRange = NotLValueExpr->getSourceRange();
  7900. }
  7901. } else if (!X->isInstantiationDependent() ||
  7902. !V->isInstantiationDependent()) {
  7903. const Expr *NotScalarExpr =
  7904. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7905. ? V
  7906. : X;
  7907. ErrorFound = NotAScalarType;
  7908. ErrorLoc = AtomicBinOp->getExprLoc();
  7909. ErrorRange = AtomicBinOp->getSourceRange();
  7910. NoteLoc = NotScalarExpr->getExprLoc();
  7911. NoteRange = NotScalarExpr->getSourceRange();
  7912. }
  7913. } else if (!AtomicBody->isInstantiationDependent()) {
  7914. ErrorFound = NotAnAssignmentOp;
  7915. ErrorLoc = AtomicBody->getExprLoc();
  7916. ErrorRange = AtomicBody->getSourceRange();
  7917. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7918. : AtomicBody->getExprLoc();
  7919. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7920. : AtomicBody->getSourceRange();
  7921. }
  7922. } else {
  7923. ErrorFound = NotAnExpression;
  7924. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7925. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7926. }
  7927. if (ErrorFound != NoError) {
  7928. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  7929. << ErrorRange;
  7930. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  7931. << NoteRange;
  7932. return StmtError();
  7933. }
  7934. if (CurContext->isDependentContext())
  7935. V = X = nullptr;
  7936. } else if (AtomicKind == OMPC_write) {
  7937. enum {
  7938. NotAnExpression,
  7939. NotAnAssignmentOp,
  7940. NotAScalarType,
  7941. NotAnLValue,
  7942. NoError
  7943. } ErrorFound = NoError;
  7944. SourceLocation ErrorLoc, NoteLoc;
  7945. SourceRange ErrorRange, NoteRange;
  7946. // If clause is write:
  7947. // x = expr;
  7948. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7949. const auto *AtomicBinOp =
  7950. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7951. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7952. X = AtomicBinOp->getLHS();
  7953. E = AtomicBinOp->getRHS();
  7954. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7955. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  7956. if (!X->isLValue()) {
  7957. ErrorFound = NotAnLValue;
  7958. ErrorLoc = AtomicBinOp->getExprLoc();
  7959. ErrorRange = AtomicBinOp->getSourceRange();
  7960. NoteLoc = X->getExprLoc();
  7961. NoteRange = X->getSourceRange();
  7962. }
  7963. } else if (!X->isInstantiationDependent() ||
  7964. !E->isInstantiationDependent()) {
  7965. const Expr *NotScalarExpr =
  7966. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7967. ? E
  7968. : X;
  7969. ErrorFound = NotAScalarType;
  7970. ErrorLoc = AtomicBinOp->getExprLoc();
  7971. ErrorRange = AtomicBinOp->getSourceRange();
  7972. NoteLoc = NotScalarExpr->getExprLoc();
  7973. NoteRange = NotScalarExpr->getSourceRange();
  7974. }
  7975. } else if (!AtomicBody->isInstantiationDependent()) {
  7976. ErrorFound = NotAnAssignmentOp;
  7977. ErrorLoc = AtomicBody->getExprLoc();
  7978. ErrorRange = AtomicBody->getSourceRange();
  7979. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7980. : AtomicBody->getExprLoc();
  7981. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7982. : AtomicBody->getSourceRange();
  7983. }
  7984. } else {
  7985. ErrorFound = NotAnExpression;
  7986. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7987. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7988. }
  7989. if (ErrorFound != NoError) {
  7990. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  7991. << ErrorRange;
  7992. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  7993. << NoteRange;
  7994. return StmtError();
  7995. }
  7996. if (CurContext->isDependentContext())
  7997. E = X = nullptr;
  7998. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  7999. // If clause is update:
  8000. // x++;
  8001. // x--;
  8002. // ++x;
  8003. // --x;
  8004. // x binop= expr;
  8005. // x = x binop expr;
  8006. // x = expr binop x;
  8007. OpenMPAtomicUpdateChecker Checker(*this);
  8008. if (Checker.checkStatement(
  8009. Body, (AtomicKind == OMPC_update)
  8010. ? diag::err_omp_atomic_update_not_expression_statement
  8011. : diag::err_omp_atomic_not_expression_statement,
  8012. diag::note_omp_atomic_update))
  8013. return StmtError();
  8014. if (!CurContext->isDependentContext()) {
  8015. E = Checker.getExpr();
  8016. X = Checker.getX();
  8017. UE = Checker.getUpdateExpr();
  8018. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8019. }
  8020. } else if (AtomicKind == OMPC_capture) {
  8021. enum {
  8022. NotAnAssignmentOp,
  8023. NotACompoundStatement,
  8024. NotTwoSubstatements,
  8025. NotASpecificExpression,
  8026. NoError
  8027. } ErrorFound = NoError;
  8028. SourceLocation ErrorLoc, NoteLoc;
  8029. SourceRange ErrorRange, NoteRange;
  8030. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  8031. // If clause is a capture:
  8032. // v = x++;
  8033. // v = x--;
  8034. // v = ++x;
  8035. // v = --x;
  8036. // v = x binop= expr;
  8037. // v = x = x binop expr;
  8038. // v = x = expr binop x;
  8039. const auto *AtomicBinOp =
  8040. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  8041. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  8042. V = AtomicBinOp->getLHS();
  8043. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  8044. OpenMPAtomicUpdateChecker Checker(*this);
  8045. if (Checker.checkStatement(
  8046. Body, diag::err_omp_atomic_capture_not_expression_statement,
  8047. diag::note_omp_atomic_update))
  8048. return StmtError();
  8049. E = Checker.getExpr();
  8050. X = Checker.getX();
  8051. UE = Checker.getUpdateExpr();
  8052. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8053. IsPostfixUpdate = Checker.isPostfixUpdate();
  8054. } else if (!AtomicBody->isInstantiationDependent()) {
  8055. ErrorLoc = AtomicBody->getExprLoc();
  8056. ErrorRange = AtomicBody->getSourceRange();
  8057. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  8058. : AtomicBody->getExprLoc();
  8059. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  8060. : AtomicBody->getSourceRange();
  8061. ErrorFound = NotAnAssignmentOp;
  8062. }
  8063. if (ErrorFound != NoError) {
  8064. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  8065. << ErrorRange;
  8066. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8067. return StmtError();
  8068. }
  8069. if (CurContext->isDependentContext())
  8070. UE = V = E = X = nullptr;
  8071. } else {
  8072. // If clause is a capture:
  8073. // { v = x; x = expr; }
  8074. // { v = x; x++; }
  8075. // { v = x; x--; }
  8076. // { v = x; ++x; }
  8077. // { v = x; --x; }
  8078. // { v = x; x binop= expr; }
  8079. // { v = x; x = x binop expr; }
  8080. // { v = x; x = expr binop x; }
  8081. // { x++; v = x; }
  8082. // { x--; v = x; }
  8083. // { ++x; v = x; }
  8084. // { --x; v = x; }
  8085. // { x binop= expr; v = x; }
  8086. // { x = x binop expr; v = x; }
  8087. // { x = expr binop x; v = x; }
  8088. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  8089. // Check that this is { expr1; expr2; }
  8090. if (CS->size() == 2) {
  8091. Stmt *First = CS->body_front();
  8092. Stmt *Second = CS->body_back();
  8093. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  8094. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  8095. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  8096. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  8097. // Need to find what subexpression is 'v' and what is 'x'.
  8098. OpenMPAtomicUpdateChecker Checker(*this);
  8099. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  8100. BinaryOperator *BinOp = nullptr;
  8101. if (IsUpdateExprFound) {
  8102. BinOp = dyn_cast<BinaryOperator>(First);
  8103. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8104. }
  8105. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8106. // { v = x; x++; }
  8107. // { v = x; x--; }
  8108. // { v = x; ++x; }
  8109. // { v = x; --x; }
  8110. // { v = x; x binop= expr; }
  8111. // { v = x; x = x binop expr; }
  8112. // { v = x; x = expr binop x; }
  8113. // Check that the first expression has form v = x.
  8114. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8115. llvm::FoldingSetNodeID XId, PossibleXId;
  8116. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8117. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8118. IsUpdateExprFound = XId == PossibleXId;
  8119. if (IsUpdateExprFound) {
  8120. V = BinOp->getLHS();
  8121. X = Checker.getX();
  8122. E = Checker.getExpr();
  8123. UE = Checker.getUpdateExpr();
  8124. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8125. IsPostfixUpdate = true;
  8126. }
  8127. }
  8128. if (!IsUpdateExprFound) {
  8129. IsUpdateExprFound = !Checker.checkStatement(First);
  8130. BinOp = nullptr;
  8131. if (IsUpdateExprFound) {
  8132. BinOp = dyn_cast<BinaryOperator>(Second);
  8133. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8134. }
  8135. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8136. // { x++; v = x; }
  8137. // { x--; v = x; }
  8138. // { ++x; v = x; }
  8139. // { --x; v = x; }
  8140. // { x binop= expr; v = x; }
  8141. // { x = x binop expr; v = x; }
  8142. // { x = expr binop x; v = x; }
  8143. // Check that the second expression has form v = x.
  8144. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8145. llvm::FoldingSetNodeID XId, PossibleXId;
  8146. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8147. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8148. IsUpdateExprFound = XId == PossibleXId;
  8149. if (IsUpdateExprFound) {
  8150. V = BinOp->getLHS();
  8151. X = Checker.getX();
  8152. E = Checker.getExpr();
  8153. UE = Checker.getUpdateExpr();
  8154. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8155. IsPostfixUpdate = false;
  8156. }
  8157. }
  8158. }
  8159. if (!IsUpdateExprFound) {
  8160. // { v = x; x = expr; }
  8161. auto *FirstExpr = dyn_cast<Expr>(First);
  8162. auto *SecondExpr = dyn_cast<Expr>(Second);
  8163. if (!FirstExpr || !SecondExpr ||
  8164. !(FirstExpr->isInstantiationDependent() ||
  8165. SecondExpr->isInstantiationDependent())) {
  8166. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  8167. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  8168. ErrorFound = NotAnAssignmentOp;
  8169. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  8170. : First->getBeginLoc();
  8171. NoteRange = ErrorRange = FirstBinOp
  8172. ? FirstBinOp->getSourceRange()
  8173. : SourceRange(ErrorLoc, ErrorLoc);
  8174. } else {
  8175. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  8176. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  8177. ErrorFound = NotAnAssignmentOp;
  8178. NoteLoc = ErrorLoc = SecondBinOp
  8179. ? SecondBinOp->getOperatorLoc()
  8180. : Second->getBeginLoc();
  8181. NoteRange = ErrorRange =
  8182. SecondBinOp ? SecondBinOp->getSourceRange()
  8183. : SourceRange(ErrorLoc, ErrorLoc);
  8184. } else {
  8185. Expr *PossibleXRHSInFirst =
  8186. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  8187. Expr *PossibleXLHSInSecond =
  8188. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  8189. llvm::FoldingSetNodeID X1Id, X2Id;
  8190. PossibleXRHSInFirst->Profile(X1Id, Context,
  8191. /*Canonical=*/true);
  8192. PossibleXLHSInSecond->Profile(X2Id, Context,
  8193. /*Canonical=*/true);
  8194. IsUpdateExprFound = X1Id == X2Id;
  8195. if (IsUpdateExprFound) {
  8196. V = FirstBinOp->getLHS();
  8197. X = SecondBinOp->getLHS();
  8198. E = SecondBinOp->getRHS();
  8199. UE = nullptr;
  8200. IsXLHSInRHSPart = false;
  8201. IsPostfixUpdate = true;
  8202. } else {
  8203. ErrorFound = NotASpecificExpression;
  8204. ErrorLoc = FirstBinOp->getExprLoc();
  8205. ErrorRange = FirstBinOp->getSourceRange();
  8206. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  8207. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  8208. }
  8209. }
  8210. }
  8211. }
  8212. }
  8213. } else {
  8214. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8215. NoteRange = ErrorRange =
  8216. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8217. ErrorFound = NotTwoSubstatements;
  8218. }
  8219. } else {
  8220. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8221. NoteRange = ErrorRange =
  8222. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8223. ErrorFound = NotACompoundStatement;
  8224. }
  8225. if (ErrorFound != NoError) {
  8226. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  8227. << ErrorRange;
  8228. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8229. return StmtError();
  8230. }
  8231. if (CurContext->isDependentContext())
  8232. UE = V = E = X = nullptr;
  8233. }
  8234. }
  8235. setFunctionHasBranchProtectedScope();
  8236. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  8237. X, V, E, UE, IsXLHSInRHSPart,
  8238. IsPostfixUpdate);
  8239. }
  8240. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  8241. Stmt *AStmt,
  8242. SourceLocation StartLoc,
  8243. SourceLocation EndLoc) {
  8244. if (!AStmt)
  8245. return StmtError();
  8246. auto *CS = cast<CapturedStmt>(AStmt);
  8247. // 1.2.2 OpenMP Language Terminology
  8248. // Structured block - An executable statement with a single entry at the
  8249. // top and a single exit at the bottom.
  8250. // The point of exit cannot be a branch out of the structured block.
  8251. // longjmp() and throw() must not violate the entry/exit criteria.
  8252. CS->getCapturedDecl()->setNothrow();
  8253. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  8254. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8255. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8256. // 1.2.2 OpenMP Language Terminology
  8257. // Structured block - An executable statement with a single entry at the
  8258. // top and a single exit at the bottom.
  8259. // The point of exit cannot be a branch out of the structured block.
  8260. // longjmp() and throw() must not violate the entry/exit criteria.
  8261. CS->getCapturedDecl()->setNothrow();
  8262. }
  8263. // OpenMP [2.16, Nesting of Regions]
  8264. // If specified, a teams construct must be contained within a target
  8265. // construct. That target construct must contain no statements or directives
  8266. // outside of the teams construct.
  8267. if (DSAStack->hasInnerTeamsRegion()) {
  8268. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  8269. bool OMPTeamsFound = true;
  8270. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  8271. auto I = CS->body_begin();
  8272. while (I != CS->body_end()) {
  8273. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  8274. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  8275. OMPTeamsFound) {
  8276. OMPTeamsFound = false;
  8277. break;
  8278. }
  8279. ++I;
  8280. }
  8281. assert(I != CS->body_end() && "Not found statement");
  8282. S = *I;
  8283. } else {
  8284. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  8285. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  8286. }
  8287. if (!OMPTeamsFound) {
  8288. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  8289. Diag(DSAStack->getInnerTeamsRegionLoc(),
  8290. diag::note_omp_nested_teams_construct_here);
  8291. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  8292. << isa<OMPExecutableDirective>(S);
  8293. return StmtError();
  8294. }
  8295. }
  8296. setFunctionHasBranchProtectedScope();
  8297. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8298. }
  8299. StmtResult
  8300. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  8301. Stmt *AStmt, SourceLocation StartLoc,
  8302. SourceLocation EndLoc) {
  8303. if (!AStmt)
  8304. return StmtError();
  8305. auto *CS = cast<CapturedStmt>(AStmt);
  8306. // 1.2.2 OpenMP Language Terminology
  8307. // Structured block - An executable statement with a single entry at the
  8308. // top and a single exit at the bottom.
  8309. // The point of exit cannot be a branch out of the structured block.
  8310. // longjmp() and throw() must not violate the entry/exit criteria.
  8311. CS->getCapturedDecl()->setNothrow();
  8312. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  8313. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8314. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8315. // 1.2.2 OpenMP Language Terminology
  8316. // Structured block - An executable statement with a single entry at the
  8317. // top and a single exit at the bottom.
  8318. // The point of exit cannot be a branch out of the structured block.
  8319. // longjmp() and throw() must not violate the entry/exit criteria.
  8320. CS->getCapturedDecl()->setNothrow();
  8321. }
  8322. setFunctionHasBranchProtectedScope();
  8323. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8324. AStmt);
  8325. }
  8326. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  8327. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8328. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8329. if (!AStmt)
  8330. return StmtError();
  8331. auto *CS = cast<CapturedStmt>(AStmt);
  8332. // 1.2.2 OpenMP Language Terminology
  8333. // Structured block - An executable statement with a single entry at the
  8334. // top and a single exit at the bottom.
  8335. // The point of exit cannot be a branch out of the structured block.
  8336. // longjmp() and throw() must not violate the entry/exit criteria.
  8337. CS->getCapturedDecl()->setNothrow();
  8338. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8339. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8340. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8341. // 1.2.2 OpenMP Language Terminology
  8342. // Structured block - An executable statement with a single entry at the
  8343. // top and a single exit at the bottom.
  8344. // The point of exit cannot be a branch out of the structured block.
  8345. // longjmp() and throw() must not violate the entry/exit criteria.
  8346. CS->getCapturedDecl()->setNothrow();
  8347. }
  8348. OMPLoopDirective::HelperExprs B;
  8349. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8350. // define the nested loops number.
  8351. unsigned NestedLoopCount =
  8352. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  8353. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8354. VarsWithImplicitDSA, B);
  8355. if (NestedLoopCount == 0)
  8356. return StmtError();
  8357. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8358. "omp target parallel for loop exprs were not built");
  8359. if (!CurContext->isDependentContext()) {
  8360. // Finalize the clauses that need pre-built expressions for CodeGen.
  8361. for (OMPClause *C : Clauses) {
  8362. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8363. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8364. B.NumIterations, *this, CurScope,
  8365. DSAStack))
  8366. return StmtError();
  8367. }
  8368. }
  8369. setFunctionHasBranchProtectedScope();
  8370. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  8371. NestedLoopCount, Clauses, AStmt,
  8372. B, DSAStack->isCancelRegion());
  8373. }
  8374. /// Check for existence of a map clause in the list of clauses.
  8375. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  8376. const OpenMPClauseKind K) {
  8377. return llvm::any_of(
  8378. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  8379. }
  8380. template <typename... Params>
  8381. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  8382. const Params... ClauseTypes) {
  8383. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  8384. }
  8385. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  8386. Stmt *AStmt,
  8387. SourceLocation StartLoc,
  8388. SourceLocation EndLoc) {
  8389. if (!AStmt)
  8390. return StmtError();
  8391. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8392. // OpenMP [2.10.1, Restrictions, p. 97]
  8393. // At least one map clause must appear on the directive.
  8394. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  8395. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8396. << "'map' or 'use_device_ptr'"
  8397. << getOpenMPDirectiveName(OMPD_target_data);
  8398. return StmtError();
  8399. }
  8400. setFunctionHasBranchProtectedScope();
  8401. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8402. AStmt);
  8403. }
  8404. StmtResult
  8405. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  8406. SourceLocation StartLoc,
  8407. SourceLocation EndLoc, Stmt *AStmt) {
  8408. if (!AStmt)
  8409. return StmtError();
  8410. auto *CS = cast<CapturedStmt>(AStmt);
  8411. // 1.2.2 OpenMP Language Terminology
  8412. // Structured block - An executable statement with a single entry at the
  8413. // top and a single exit at the bottom.
  8414. // The point of exit cannot be a branch out of the structured block.
  8415. // longjmp() and throw() must not violate the entry/exit criteria.
  8416. CS->getCapturedDecl()->setNothrow();
  8417. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  8418. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8419. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8420. // 1.2.2 OpenMP Language Terminology
  8421. // Structured block - An executable statement with a single entry at the
  8422. // top and a single exit at the bottom.
  8423. // The point of exit cannot be a branch out of the structured block.
  8424. // longjmp() and throw() must not violate the entry/exit criteria.
  8425. CS->getCapturedDecl()->setNothrow();
  8426. }
  8427. // OpenMP [2.10.2, Restrictions, p. 99]
  8428. // At least one map clause must appear on the directive.
  8429. if (!hasClauses(Clauses, OMPC_map)) {
  8430. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8431. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  8432. return StmtError();
  8433. }
  8434. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8435. AStmt);
  8436. }
  8437. StmtResult
  8438. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  8439. SourceLocation StartLoc,
  8440. SourceLocation EndLoc, Stmt *AStmt) {
  8441. if (!AStmt)
  8442. return StmtError();
  8443. auto *CS = cast<CapturedStmt>(AStmt);
  8444. // 1.2.2 OpenMP Language Terminology
  8445. // Structured block - An executable statement with a single entry at the
  8446. // top and a single exit at the bottom.
  8447. // The point of exit cannot be a branch out of the structured block.
  8448. // longjmp() and throw() must not violate the entry/exit criteria.
  8449. CS->getCapturedDecl()->setNothrow();
  8450. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  8451. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8452. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8453. // 1.2.2 OpenMP Language Terminology
  8454. // Structured block - An executable statement with a single entry at the
  8455. // top and a single exit at the bottom.
  8456. // The point of exit cannot be a branch out of the structured block.
  8457. // longjmp() and throw() must not violate the entry/exit criteria.
  8458. CS->getCapturedDecl()->setNothrow();
  8459. }
  8460. // OpenMP [2.10.3, Restrictions, p. 102]
  8461. // At least one map clause must appear on the directive.
  8462. if (!hasClauses(Clauses, OMPC_map)) {
  8463. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8464. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  8465. return StmtError();
  8466. }
  8467. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8468. AStmt);
  8469. }
  8470. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  8471. SourceLocation StartLoc,
  8472. SourceLocation EndLoc,
  8473. Stmt *AStmt) {
  8474. if (!AStmt)
  8475. return StmtError();
  8476. auto *CS = cast<CapturedStmt>(AStmt);
  8477. // 1.2.2 OpenMP Language Terminology
  8478. // Structured block - An executable statement with a single entry at the
  8479. // top and a single exit at the bottom.
  8480. // The point of exit cannot be a branch out of the structured block.
  8481. // longjmp() and throw() must not violate the entry/exit criteria.
  8482. CS->getCapturedDecl()->setNothrow();
  8483. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  8484. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8485. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8486. // 1.2.2 OpenMP Language Terminology
  8487. // Structured block - An executable statement with a single entry at the
  8488. // top and a single exit at the bottom.
  8489. // The point of exit cannot be a branch out of the structured block.
  8490. // longjmp() and throw() must not violate the entry/exit criteria.
  8491. CS->getCapturedDecl()->setNothrow();
  8492. }
  8493. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  8494. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  8495. return StmtError();
  8496. }
  8497. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8498. AStmt);
  8499. }
  8500. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  8501. Stmt *AStmt, SourceLocation StartLoc,
  8502. SourceLocation EndLoc) {
  8503. if (!AStmt)
  8504. return StmtError();
  8505. auto *CS = cast<CapturedStmt>(AStmt);
  8506. // 1.2.2 OpenMP Language Terminology
  8507. // Structured block - An executable statement with a single entry at the
  8508. // top and a single exit at the bottom.
  8509. // The point of exit cannot be a branch out of the structured block.
  8510. // longjmp() and throw() must not violate the entry/exit criteria.
  8511. CS->getCapturedDecl()->setNothrow();
  8512. setFunctionHasBranchProtectedScope();
  8513. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8514. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8515. }
  8516. StmtResult
  8517. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  8518. SourceLocation EndLoc,
  8519. OpenMPDirectiveKind CancelRegion) {
  8520. if (DSAStack->isParentNowaitRegion()) {
  8521. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  8522. return StmtError();
  8523. }
  8524. if (DSAStack->isParentOrderedRegion()) {
  8525. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  8526. return StmtError();
  8527. }
  8528. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  8529. CancelRegion);
  8530. }
  8531. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  8532. SourceLocation StartLoc,
  8533. SourceLocation EndLoc,
  8534. OpenMPDirectiveKind CancelRegion) {
  8535. if (DSAStack->isParentNowaitRegion()) {
  8536. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  8537. return StmtError();
  8538. }
  8539. if (DSAStack->isParentOrderedRegion()) {
  8540. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  8541. return StmtError();
  8542. }
  8543. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  8544. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8545. CancelRegion);
  8546. }
  8547. static bool checkGrainsizeNumTasksClauses(Sema &S,
  8548. ArrayRef<OMPClause *> Clauses) {
  8549. const OMPClause *PrevClause = nullptr;
  8550. bool ErrorFound = false;
  8551. for (const OMPClause *C : Clauses) {
  8552. if (C->getClauseKind() == OMPC_grainsize ||
  8553. C->getClauseKind() == OMPC_num_tasks) {
  8554. if (!PrevClause)
  8555. PrevClause = C;
  8556. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  8557. S.Diag(C->getBeginLoc(),
  8558. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  8559. << getOpenMPClauseName(C->getClauseKind())
  8560. << getOpenMPClauseName(PrevClause->getClauseKind());
  8561. S.Diag(PrevClause->getBeginLoc(),
  8562. diag::note_omp_previous_grainsize_num_tasks)
  8563. << getOpenMPClauseName(PrevClause->getClauseKind());
  8564. ErrorFound = true;
  8565. }
  8566. }
  8567. }
  8568. return ErrorFound;
  8569. }
  8570. static bool checkReductionClauseWithNogroup(Sema &S,
  8571. ArrayRef<OMPClause *> Clauses) {
  8572. const OMPClause *ReductionClause = nullptr;
  8573. const OMPClause *NogroupClause = nullptr;
  8574. for (const OMPClause *C : Clauses) {
  8575. if (C->getClauseKind() == OMPC_reduction) {
  8576. ReductionClause = C;
  8577. if (NogroupClause)
  8578. break;
  8579. continue;
  8580. }
  8581. if (C->getClauseKind() == OMPC_nogroup) {
  8582. NogroupClause = C;
  8583. if (ReductionClause)
  8584. break;
  8585. continue;
  8586. }
  8587. }
  8588. if (ReductionClause && NogroupClause) {
  8589. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  8590. << SourceRange(NogroupClause->getBeginLoc(),
  8591. NogroupClause->getEndLoc());
  8592. return true;
  8593. }
  8594. return false;
  8595. }
  8596. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  8597. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8598. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8599. if (!AStmt)
  8600. return StmtError();
  8601. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8602. OMPLoopDirective::HelperExprs B;
  8603. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8604. // define the nested loops number.
  8605. unsigned NestedLoopCount =
  8606. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  8607. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8608. VarsWithImplicitDSA, B);
  8609. if (NestedLoopCount == 0)
  8610. return StmtError();
  8611. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8612. "omp for loop exprs were not built");
  8613. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8614. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8615. // not appear on the same taskloop directive.
  8616. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8617. return StmtError();
  8618. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8619. // If a reduction clause is present on the taskloop directive, the nogroup
  8620. // clause must not be specified.
  8621. if (checkReductionClauseWithNogroup(*this, Clauses))
  8622. return StmtError();
  8623. setFunctionHasBranchProtectedScope();
  8624. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  8625. NestedLoopCount, Clauses, AStmt, B);
  8626. }
  8627. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  8628. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8629. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8630. if (!AStmt)
  8631. return StmtError();
  8632. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8633. OMPLoopDirective::HelperExprs B;
  8634. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8635. // define the nested loops number.
  8636. unsigned NestedLoopCount =
  8637. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  8638. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8639. VarsWithImplicitDSA, B);
  8640. if (NestedLoopCount == 0)
  8641. return StmtError();
  8642. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8643. "omp for loop exprs were not built");
  8644. if (!CurContext->isDependentContext()) {
  8645. // Finalize the clauses that need pre-built expressions for CodeGen.
  8646. for (OMPClause *C : Clauses) {
  8647. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8648. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8649. B.NumIterations, *this, CurScope,
  8650. DSAStack))
  8651. return StmtError();
  8652. }
  8653. }
  8654. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8655. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8656. // not appear on the same taskloop directive.
  8657. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8658. return StmtError();
  8659. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8660. // If a reduction clause is present on the taskloop directive, the nogroup
  8661. // clause must not be specified.
  8662. if (checkReductionClauseWithNogroup(*this, Clauses))
  8663. return StmtError();
  8664. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8665. return StmtError();
  8666. setFunctionHasBranchProtectedScope();
  8667. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  8668. NestedLoopCount, Clauses, AStmt, B);
  8669. }
  8670. StmtResult Sema::ActOnOpenMPDistributeDirective(
  8671. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8672. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8673. if (!AStmt)
  8674. return StmtError();
  8675. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8676. OMPLoopDirective::HelperExprs B;
  8677. // In presence of clause 'collapse' with number of loops, it will
  8678. // define the nested loops number.
  8679. unsigned NestedLoopCount =
  8680. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  8681. nullptr /*ordered not a clause on distribute*/, AStmt,
  8682. *this, *DSAStack, VarsWithImplicitDSA, B);
  8683. if (NestedLoopCount == 0)
  8684. return StmtError();
  8685. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8686. "omp for loop exprs were not built");
  8687. setFunctionHasBranchProtectedScope();
  8688. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  8689. NestedLoopCount, Clauses, AStmt, B);
  8690. }
  8691. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  8692. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8693. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8694. if (!AStmt)
  8695. return StmtError();
  8696. auto *CS = cast<CapturedStmt>(AStmt);
  8697. // 1.2.2 OpenMP Language Terminology
  8698. // Structured block - An executable statement with a single entry at the
  8699. // top and a single exit at the bottom.
  8700. // The point of exit cannot be a branch out of the structured block.
  8701. // longjmp() and throw() must not violate the entry/exit criteria.
  8702. CS->getCapturedDecl()->setNothrow();
  8703. for (int ThisCaptureLevel =
  8704. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  8705. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8706. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8707. // 1.2.2 OpenMP Language Terminology
  8708. // Structured block - An executable statement with a single entry at the
  8709. // top and a single exit at the bottom.
  8710. // The point of exit cannot be a branch out of the structured block.
  8711. // longjmp() and throw() must not violate the entry/exit criteria.
  8712. CS->getCapturedDecl()->setNothrow();
  8713. }
  8714. OMPLoopDirective::HelperExprs B;
  8715. // In presence of clause 'collapse' with number of loops, it will
  8716. // define the nested loops number.
  8717. unsigned NestedLoopCount = checkOpenMPLoop(
  8718. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  8719. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8720. VarsWithImplicitDSA, B);
  8721. if (NestedLoopCount == 0)
  8722. return StmtError();
  8723. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8724. "omp for loop exprs were not built");
  8725. setFunctionHasBranchProtectedScope();
  8726. return OMPDistributeParallelForDirective::Create(
  8727. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  8728. DSAStack->isCancelRegion());
  8729. }
  8730. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  8731. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8732. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8733. if (!AStmt)
  8734. return StmtError();
  8735. auto *CS = cast<CapturedStmt>(AStmt);
  8736. // 1.2.2 OpenMP Language Terminology
  8737. // Structured block - An executable statement with a single entry at the
  8738. // top and a single exit at the bottom.
  8739. // The point of exit cannot be a branch out of the structured block.
  8740. // longjmp() and throw() must not violate the entry/exit criteria.
  8741. CS->getCapturedDecl()->setNothrow();
  8742. for (int ThisCaptureLevel =
  8743. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  8744. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8745. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8746. // 1.2.2 OpenMP Language Terminology
  8747. // Structured block - An executable statement with a single entry at the
  8748. // top and a single exit at the bottom.
  8749. // The point of exit cannot be a branch out of the structured block.
  8750. // longjmp() and throw() must not violate the entry/exit criteria.
  8751. CS->getCapturedDecl()->setNothrow();
  8752. }
  8753. OMPLoopDirective::HelperExprs B;
  8754. // In presence of clause 'collapse' with number of loops, it will
  8755. // define the nested loops number.
  8756. unsigned NestedLoopCount = checkOpenMPLoop(
  8757. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8758. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8759. VarsWithImplicitDSA, B);
  8760. if (NestedLoopCount == 0)
  8761. return StmtError();
  8762. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8763. "omp for loop exprs were not built");
  8764. if (!CurContext->isDependentContext()) {
  8765. // Finalize the clauses that need pre-built expressions for CodeGen.
  8766. for (OMPClause *C : Clauses) {
  8767. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8768. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8769. B.NumIterations, *this, CurScope,
  8770. DSAStack))
  8771. return StmtError();
  8772. }
  8773. }
  8774. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8775. return StmtError();
  8776. setFunctionHasBranchProtectedScope();
  8777. return OMPDistributeParallelForSimdDirective::Create(
  8778. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8779. }
  8780. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  8781. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8782. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8783. if (!AStmt)
  8784. return StmtError();
  8785. auto *CS = cast<CapturedStmt>(AStmt);
  8786. // 1.2.2 OpenMP Language Terminology
  8787. // Structured block - An executable statement with a single entry at the
  8788. // top and a single exit at the bottom.
  8789. // The point of exit cannot be a branch out of the structured block.
  8790. // longjmp() and throw() must not violate the entry/exit criteria.
  8791. CS->getCapturedDecl()->setNothrow();
  8792. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  8793. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8794. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8795. // 1.2.2 OpenMP Language Terminology
  8796. // Structured block - An executable statement with a single entry at the
  8797. // top and a single exit at the bottom.
  8798. // The point of exit cannot be a branch out of the structured block.
  8799. // longjmp() and throw() must not violate the entry/exit criteria.
  8800. CS->getCapturedDecl()->setNothrow();
  8801. }
  8802. OMPLoopDirective::HelperExprs B;
  8803. // In presence of clause 'collapse' with number of loops, it will
  8804. // define the nested loops number.
  8805. unsigned NestedLoopCount =
  8806. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  8807. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8808. *DSAStack, VarsWithImplicitDSA, B);
  8809. if (NestedLoopCount == 0)
  8810. return StmtError();
  8811. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8812. "omp for loop exprs were not built");
  8813. if (!CurContext->isDependentContext()) {
  8814. // Finalize the clauses that need pre-built expressions for CodeGen.
  8815. for (OMPClause *C : Clauses) {
  8816. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8817. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8818. B.NumIterations, *this, CurScope,
  8819. DSAStack))
  8820. return StmtError();
  8821. }
  8822. }
  8823. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8824. return StmtError();
  8825. setFunctionHasBranchProtectedScope();
  8826. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  8827. NestedLoopCount, Clauses, AStmt, B);
  8828. }
  8829. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  8830. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8831. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8832. if (!AStmt)
  8833. return StmtError();
  8834. auto *CS = cast<CapturedStmt>(AStmt);
  8835. // 1.2.2 OpenMP Language Terminology
  8836. // Structured block - An executable statement with a single entry at the
  8837. // top and a single exit at the bottom.
  8838. // The point of exit cannot be a branch out of the structured block.
  8839. // longjmp() and throw() must not violate the entry/exit criteria.
  8840. CS->getCapturedDecl()->setNothrow();
  8841. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  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_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8856. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8857. VarsWithImplicitDSA, B);
  8858. if (NestedLoopCount == 0)
  8859. return StmtError();
  8860. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8861. "omp target parallel for simd loop exprs were not built");
  8862. if (!CurContext->isDependentContext()) {
  8863. // Finalize the clauses that need pre-built expressions for CodeGen.
  8864. for (OMPClause *C : Clauses) {
  8865. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8866. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8867. B.NumIterations, *this, CurScope,
  8868. DSAStack))
  8869. return StmtError();
  8870. }
  8871. }
  8872. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8873. return StmtError();
  8874. setFunctionHasBranchProtectedScope();
  8875. return OMPTargetParallelForSimdDirective::Create(
  8876. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8877. }
  8878. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  8879. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8880. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8881. if (!AStmt)
  8882. return StmtError();
  8883. auto *CS = cast<CapturedStmt>(AStmt);
  8884. // 1.2.2 OpenMP Language Terminology
  8885. // Structured block - An executable statement with a single entry at the
  8886. // top and a single exit at the bottom.
  8887. // The point of exit cannot be a branch out of the structured block.
  8888. // longjmp() and throw() must not violate the entry/exit criteria.
  8889. CS->getCapturedDecl()->setNothrow();
  8890. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  8891. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8892. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8893. // 1.2.2 OpenMP Language Terminology
  8894. // Structured block - An executable statement with a single entry at the
  8895. // top and a single exit at the bottom.
  8896. // The point of exit cannot be a branch out of the structured block.
  8897. // longjmp() and throw() must not violate the entry/exit criteria.
  8898. CS->getCapturedDecl()->setNothrow();
  8899. }
  8900. OMPLoopDirective::HelperExprs B;
  8901. // In presence of clause 'collapse' with number of loops, it will define the
  8902. // nested loops number.
  8903. unsigned NestedLoopCount =
  8904. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  8905. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8906. VarsWithImplicitDSA, B);
  8907. if (NestedLoopCount == 0)
  8908. return StmtError();
  8909. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8910. "omp target simd loop exprs were not built");
  8911. if (!CurContext->isDependentContext()) {
  8912. // Finalize the clauses that need pre-built expressions for CodeGen.
  8913. for (OMPClause *C : Clauses) {
  8914. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8915. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8916. B.NumIterations, *this, CurScope,
  8917. DSAStack))
  8918. return StmtError();
  8919. }
  8920. }
  8921. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8922. return StmtError();
  8923. setFunctionHasBranchProtectedScope();
  8924. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  8925. NestedLoopCount, Clauses, AStmt, B);
  8926. }
  8927. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  8928. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8929. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8930. if (!AStmt)
  8931. return StmtError();
  8932. auto *CS = cast<CapturedStmt>(AStmt);
  8933. // 1.2.2 OpenMP Language Terminology
  8934. // Structured block - An executable statement with a single entry at the
  8935. // top and a single exit at the bottom.
  8936. // The point of exit cannot be a branch out of the structured block.
  8937. // longjmp() and throw() must not violate the entry/exit criteria.
  8938. CS->getCapturedDecl()->setNothrow();
  8939. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  8940. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8941. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  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. }
  8949. OMPLoopDirective::HelperExprs B;
  8950. // In presence of clause 'collapse' with number of loops, it will
  8951. // define the nested loops number.
  8952. unsigned NestedLoopCount =
  8953. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  8954. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8955. *DSAStack, VarsWithImplicitDSA, B);
  8956. if (NestedLoopCount == 0)
  8957. return StmtError();
  8958. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8959. "omp teams distribute loop exprs were not built");
  8960. setFunctionHasBranchProtectedScope();
  8961. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8962. return OMPTeamsDistributeDirective::Create(
  8963. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8964. }
  8965. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  8966. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8967. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8968. if (!AStmt)
  8969. return StmtError();
  8970. auto *CS = cast<CapturedStmt>(AStmt);
  8971. // 1.2.2 OpenMP Language Terminology
  8972. // Structured block - An executable statement with a single entry at the
  8973. // top and a single exit at the bottom.
  8974. // The point of exit cannot be a branch out of the structured block.
  8975. // longjmp() and throw() must not violate the entry/exit criteria.
  8976. CS->getCapturedDecl()->setNothrow();
  8977. for (int ThisCaptureLevel =
  8978. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  8979. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8980. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8981. // 1.2.2 OpenMP Language Terminology
  8982. // Structured block - An executable statement with a single entry at the
  8983. // top and a single exit at the bottom.
  8984. // The point of exit cannot be a branch out of the structured block.
  8985. // longjmp() and throw() must not violate the entry/exit criteria.
  8986. CS->getCapturedDecl()->setNothrow();
  8987. }
  8988. OMPLoopDirective::HelperExprs B;
  8989. // In presence of clause 'collapse' with number of loops, it will
  8990. // define the nested loops number.
  8991. unsigned NestedLoopCount = checkOpenMPLoop(
  8992. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  8993. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8994. VarsWithImplicitDSA, B);
  8995. if (NestedLoopCount == 0)
  8996. return StmtError();
  8997. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8998. "omp teams distribute simd loop exprs were not built");
  8999. if (!CurContext->isDependentContext()) {
  9000. // Finalize the clauses that need pre-built expressions for CodeGen.
  9001. for (OMPClause *C : Clauses) {
  9002. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9003. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9004. B.NumIterations, *this, CurScope,
  9005. DSAStack))
  9006. return StmtError();
  9007. }
  9008. }
  9009. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9010. return StmtError();
  9011. setFunctionHasBranchProtectedScope();
  9012. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9013. return OMPTeamsDistributeSimdDirective::Create(
  9014. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9015. }
  9016. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  9017. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9018. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9019. if (!AStmt)
  9020. return StmtError();
  9021. auto *CS = cast<CapturedStmt>(AStmt);
  9022. // 1.2.2 OpenMP Language Terminology
  9023. // Structured block - An executable statement with a single entry at the
  9024. // top and a single exit at the bottom.
  9025. // The point of exit cannot be a branch out of the structured block.
  9026. // longjmp() and throw() must not violate the entry/exit criteria.
  9027. CS->getCapturedDecl()->setNothrow();
  9028. for (int ThisCaptureLevel =
  9029. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  9030. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9031. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9032. // 1.2.2 OpenMP Language Terminology
  9033. // Structured block - An executable statement with a single entry at the
  9034. // top and a single exit at the bottom.
  9035. // The point of exit cannot be a branch out of the structured block.
  9036. // longjmp() and throw() must not violate the entry/exit criteria.
  9037. CS->getCapturedDecl()->setNothrow();
  9038. }
  9039. OMPLoopDirective::HelperExprs B;
  9040. // In presence of clause 'collapse' with number of loops, it will
  9041. // define the nested loops number.
  9042. unsigned NestedLoopCount = checkOpenMPLoop(
  9043. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  9044. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9045. VarsWithImplicitDSA, B);
  9046. if (NestedLoopCount == 0)
  9047. return StmtError();
  9048. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9049. "omp for loop exprs were not built");
  9050. if (!CurContext->isDependentContext()) {
  9051. // Finalize the clauses that need pre-built expressions for CodeGen.
  9052. for (OMPClause *C : Clauses) {
  9053. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9054. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9055. B.NumIterations, *this, CurScope,
  9056. DSAStack))
  9057. return StmtError();
  9058. }
  9059. }
  9060. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9061. return StmtError();
  9062. setFunctionHasBranchProtectedScope();
  9063. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9064. return OMPTeamsDistributeParallelForSimdDirective::Create(
  9065. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9066. }
  9067. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  9068. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9069. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9070. if (!AStmt)
  9071. return StmtError();
  9072. auto *CS = cast<CapturedStmt>(AStmt);
  9073. // 1.2.2 OpenMP Language Terminology
  9074. // Structured block - An executable statement with a single entry at the
  9075. // top and a single exit at the bottom.
  9076. // The point of exit cannot be a branch out of the structured block.
  9077. // longjmp() and throw() must not violate the entry/exit criteria.
  9078. CS->getCapturedDecl()->setNothrow();
  9079. for (int ThisCaptureLevel =
  9080. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  9081. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9082. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9083. // 1.2.2 OpenMP Language Terminology
  9084. // Structured block - An executable statement with a single entry at the
  9085. // top and a single exit at the bottom.
  9086. // The point of exit cannot be a branch out of the structured block.
  9087. // longjmp() and throw() must not violate the entry/exit criteria.
  9088. CS->getCapturedDecl()->setNothrow();
  9089. }
  9090. OMPLoopDirective::HelperExprs B;
  9091. // In presence of clause 'collapse' with number of loops, it will
  9092. // define the nested loops number.
  9093. unsigned NestedLoopCount = checkOpenMPLoop(
  9094. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9095. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9096. VarsWithImplicitDSA, B);
  9097. if (NestedLoopCount == 0)
  9098. return StmtError();
  9099. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9100. "omp for loop exprs were not built");
  9101. setFunctionHasBranchProtectedScope();
  9102. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9103. return OMPTeamsDistributeParallelForDirective::Create(
  9104. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9105. DSAStack->isCancelRegion());
  9106. }
  9107. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  9108. Stmt *AStmt,
  9109. SourceLocation StartLoc,
  9110. SourceLocation EndLoc) {
  9111. if (!AStmt)
  9112. return StmtError();
  9113. auto *CS = cast<CapturedStmt>(AStmt);
  9114. // 1.2.2 OpenMP Language Terminology
  9115. // Structured block - An executable statement with a single entry at the
  9116. // top and a single exit at the bottom.
  9117. // The point of exit cannot be a branch out of the structured block.
  9118. // longjmp() and throw() must not violate the entry/exit criteria.
  9119. CS->getCapturedDecl()->setNothrow();
  9120. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  9121. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9122. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9123. // 1.2.2 OpenMP Language Terminology
  9124. // Structured block - An executable statement with a single entry at the
  9125. // top and a single exit at the bottom.
  9126. // The point of exit cannot be a branch out of the structured block.
  9127. // longjmp() and throw() must not violate the entry/exit criteria.
  9128. CS->getCapturedDecl()->setNothrow();
  9129. }
  9130. setFunctionHasBranchProtectedScope();
  9131. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  9132. AStmt);
  9133. }
  9134. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  9135. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9136. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9137. if (!AStmt)
  9138. return StmtError();
  9139. auto *CS = cast<CapturedStmt>(AStmt);
  9140. // 1.2.2 OpenMP Language Terminology
  9141. // Structured block - An executable statement with a single entry at the
  9142. // top and a single exit at the bottom.
  9143. // The point of exit cannot be a branch out of the structured block.
  9144. // longjmp() and throw() must not violate the entry/exit criteria.
  9145. CS->getCapturedDecl()->setNothrow();
  9146. for (int ThisCaptureLevel =
  9147. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  9148. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9149. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9150. // 1.2.2 OpenMP Language Terminology
  9151. // Structured block - An executable statement with a single entry at the
  9152. // top and a single exit at the bottom.
  9153. // The point of exit cannot be a branch out of the structured block.
  9154. // longjmp() and throw() must not violate the entry/exit criteria.
  9155. CS->getCapturedDecl()->setNothrow();
  9156. }
  9157. OMPLoopDirective::HelperExprs B;
  9158. // In presence of clause 'collapse' with number of loops, it will
  9159. // define the nested loops number.
  9160. unsigned NestedLoopCount = checkOpenMPLoop(
  9161. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  9162. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9163. VarsWithImplicitDSA, B);
  9164. if (NestedLoopCount == 0)
  9165. return StmtError();
  9166. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9167. "omp target teams distribute loop exprs were not built");
  9168. setFunctionHasBranchProtectedScope();
  9169. return OMPTargetTeamsDistributeDirective::Create(
  9170. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9171. }
  9172. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  9173. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9174. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9175. if (!AStmt)
  9176. return StmtError();
  9177. auto *CS = cast<CapturedStmt>(AStmt);
  9178. // 1.2.2 OpenMP Language Terminology
  9179. // Structured block - An executable statement with a single entry at the
  9180. // top and a single exit at the bottom.
  9181. // The point of exit cannot be a branch out of the structured block.
  9182. // longjmp() and throw() must not violate the entry/exit criteria.
  9183. CS->getCapturedDecl()->setNothrow();
  9184. for (int ThisCaptureLevel =
  9185. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  9186. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9187. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9188. // 1.2.2 OpenMP Language Terminology
  9189. // Structured block - An executable statement with a single entry at the
  9190. // top and a single exit at the bottom.
  9191. // The point of exit cannot be a branch out of the structured block.
  9192. // longjmp() and throw() must not violate the entry/exit criteria.
  9193. CS->getCapturedDecl()->setNothrow();
  9194. }
  9195. OMPLoopDirective::HelperExprs B;
  9196. // In presence of clause 'collapse' with number of loops, it will
  9197. // define the nested loops number.
  9198. unsigned NestedLoopCount = checkOpenMPLoop(
  9199. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9200. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9201. VarsWithImplicitDSA, B);
  9202. if (NestedLoopCount == 0)
  9203. return StmtError();
  9204. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9205. "omp target teams distribute parallel for loop exprs were not built");
  9206. if (!CurContext->isDependentContext()) {
  9207. // Finalize the clauses that need pre-built expressions for CodeGen.
  9208. for (OMPClause *C : Clauses) {
  9209. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9210. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9211. B.NumIterations, *this, CurScope,
  9212. DSAStack))
  9213. return StmtError();
  9214. }
  9215. }
  9216. setFunctionHasBranchProtectedScope();
  9217. return OMPTargetTeamsDistributeParallelForDirective::Create(
  9218. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9219. DSAStack->isCancelRegion());
  9220. }
  9221. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  9222. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9223. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9224. if (!AStmt)
  9225. return StmtError();
  9226. auto *CS = cast<CapturedStmt>(AStmt);
  9227. // 1.2.2 OpenMP Language Terminology
  9228. // Structured block - An executable statement with a single entry at the
  9229. // top and a single exit at the bottom.
  9230. // The point of exit cannot be a branch out of the structured block.
  9231. // longjmp() and throw() must not violate the entry/exit criteria.
  9232. CS->getCapturedDecl()->setNothrow();
  9233. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  9234. OMPD_target_teams_distribute_parallel_for_simd);
  9235. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9236. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9237. // 1.2.2 OpenMP Language Terminology
  9238. // Structured block - An executable statement with a single entry at the
  9239. // top and a single exit at the bottom.
  9240. // The point of exit cannot be a branch out of the structured block.
  9241. // longjmp() and throw() must not violate the entry/exit criteria.
  9242. CS->getCapturedDecl()->setNothrow();
  9243. }
  9244. OMPLoopDirective::HelperExprs B;
  9245. // In presence of clause 'collapse' with number of loops, it will
  9246. // define the nested loops number.
  9247. unsigned NestedLoopCount =
  9248. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  9249. getCollapseNumberExpr(Clauses),
  9250. nullptr /*ordered not a clause on distribute*/, CS, *this,
  9251. *DSAStack, VarsWithImplicitDSA, B);
  9252. if (NestedLoopCount == 0)
  9253. return StmtError();
  9254. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9255. "omp target teams distribute parallel for simd loop exprs were not "
  9256. "built");
  9257. if (!CurContext->isDependentContext()) {
  9258. // Finalize the clauses that need pre-built expressions for CodeGen.
  9259. for (OMPClause *C : Clauses) {
  9260. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9261. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9262. B.NumIterations, *this, CurScope,
  9263. DSAStack))
  9264. return StmtError();
  9265. }
  9266. }
  9267. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9268. return StmtError();
  9269. setFunctionHasBranchProtectedScope();
  9270. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  9271. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9272. }
  9273. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  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_target_teams_distribute_simd);
  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_target_teams_distribute_simd, 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 target teams distribute simd loop exprs were not built");
  9307. if (!CurContext->isDependentContext()) {
  9308. // Finalize the clauses that need pre-built expressions for CodeGen.
  9309. for (OMPClause *C : Clauses) {
  9310. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9311. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9312. B.NumIterations, *this, CurScope,
  9313. DSAStack))
  9314. return StmtError();
  9315. }
  9316. }
  9317. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9318. return StmtError();
  9319. setFunctionHasBranchProtectedScope();
  9320. return OMPTargetTeamsDistributeSimdDirective::Create(
  9321. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9322. }
  9323. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  9324. SourceLocation StartLoc,
  9325. SourceLocation LParenLoc,
  9326. SourceLocation EndLoc) {
  9327. OMPClause *Res = nullptr;
  9328. switch (Kind) {
  9329. case OMPC_final:
  9330. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  9331. break;
  9332. case OMPC_num_threads:
  9333. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9334. break;
  9335. case OMPC_safelen:
  9336. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9337. break;
  9338. case OMPC_simdlen:
  9339. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9340. break;
  9341. case OMPC_allocator:
  9342. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  9343. break;
  9344. case OMPC_collapse:
  9345. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  9346. break;
  9347. case OMPC_ordered:
  9348. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  9349. break;
  9350. case OMPC_device:
  9351. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  9352. break;
  9353. case OMPC_num_teams:
  9354. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9355. break;
  9356. case OMPC_thread_limit:
  9357. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  9358. break;
  9359. case OMPC_priority:
  9360. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  9361. break;
  9362. case OMPC_grainsize:
  9363. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  9364. break;
  9365. case OMPC_num_tasks:
  9366. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  9367. break;
  9368. case OMPC_hint:
  9369. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  9370. break;
  9371. case OMPC_if:
  9372. case OMPC_default:
  9373. case OMPC_proc_bind:
  9374. case OMPC_schedule:
  9375. case OMPC_private:
  9376. case OMPC_firstprivate:
  9377. case OMPC_lastprivate:
  9378. case OMPC_shared:
  9379. case OMPC_reduction:
  9380. case OMPC_task_reduction:
  9381. case OMPC_in_reduction:
  9382. case OMPC_linear:
  9383. case OMPC_aligned:
  9384. case OMPC_copyin:
  9385. case OMPC_copyprivate:
  9386. case OMPC_nowait:
  9387. case OMPC_untied:
  9388. case OMPC_mergeable:
  9389. case OMPC_threadprivate:
  9390. case OMPC_allocate:
  9391. case OMPC_flush:
  9392. case OMPC_read:
  9393. case OMPC_write:
  9394. case OMPC_update:
  9395. case OMPC_capture:
  9396. case OMPC_seq_cst:
  9397. case OMPC_depend:
  9398. case OMPC_threads:
  9399. case OMPC_simd:
  9400. case OMPC_map:
  9401. case OMPC_nogroup:
  9402. case OMPC_dist_schedule:
  9403. case OMPC_defaultmap:
  9404. case OMPC_unknown:
  9405. case OMPC_uniform:
  9406. case OMPC_to:
  9407. case OMPC_from:
  9408. case OMPC_use_device_ptr:
  9409. case OMPC_is_device_ptr:
  9410. case OMPC_unified_address:
  9411. case OMPC_unified_shared_memory:
  9412. case OMPC_reverse_offload:
  9413. case OMPC_dynamic_allocators:
  9414. case OMPC_atomic_default_mem_order:
  9415. case OMPC_device_type:
  9416. case OMPC_match:
  9417. llvm_unreachable("Clause is not allowed.");
  9418. }
  9419. return Res;
  9420. }
  9421. // An OpenMP directive such as 'target parallel' has two captured regions:
  9422. // for the 'target' and 'parallel' respectively. This function returns
  9423. // the region in which to capture expressions associated with a clause.
  9424. // A return value of OMPD_unknown signifies that the expression should not
  9425. // be captured.
  9426. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  9427. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  9428. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  9429. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  9430. switch (CKind) {
  9431. case OMPC_if:
  9432. switch (DKind) {
  9433. case OMPD_target_parallel:
  9434. case OMPD_target_parallel_for:
  9435. case OMPD_target_parallel_for_simd:
  9436. // If this clause applies to the nested 'parallel' region, capture within
  9437. // the 'target' region, otherwise do not capture.
  9438. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9439. CaptureRegion = OMPD_target;
  9440. break;
  9441. case OMPD_target_teams_distribute_parallel_for:
  9442. case OMPD_target_teams_distribute_parallel_for_simd:
  9443. // If this clause applies to the nested 'parallel' region, capture within
  9444. // the 'teams' region, otherwise do not capture.
  9445. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9446. CaptureRegion = OMPD_teams;
  9447. break;
  9448. case OMPD_teams_distribute_parallel_for:
  9449. case OMPD_teams_distribute_parallel_for_simd:
  9450. CaptureRegion = OMPD_teams;
  9451. break;
  9452. case OMPD_target_update:
  9453. case OMPD_target_enter_data:
  9454. case OMPD_target_exit_data:
  9455. CaptureRegion = OMPD_task;
  9456. break;
  9457. case OMPD_cancel:
  9458. case OMPD_parallel:
  9459. case OMPD_parallel_sections:
  9460. case OMPD_parallel_for:
  9461. case OMPD_parallel_for_simd:
  9462. case OMPD_target:
  9463. case OMPD_target_simd:
  9464. case OMPD_target_teams:
  9465. case OMPD_target_teams_distribute:
  9466. case OMPD_target_teams_distribute_simd:
  9467. case OMPD_distribute_parallel_for:
  9468. case OMPD_distribute_parallel_for_simd:
  9469. case OMPD_task:
  9470. case OMPD_taskloop:
  9471. case OMPD_taskloop_simd:
  9472. case OMPD_target_data:
  9473. // Do not capture if-clause expressions.
  9474. break;
  9475. case OMPD_threadprivate:
  9476. case OMPD_allocate:
  9477. case OMPD_taskyield:
  9478. case OMPD_barrier:
  9479. case OMPD_taskwait:
  9480. case OMPD_cancellation_point:
  9481. case OMPD_flush:
  9482. case OMPD_declare_reduction:
  9483. case OMPD_declare_mapper:
  9484. case OMPD_declare_simd:
  9485. case OMPD_declare_variant:
  9486. case OMPD_declare_target:
  9487. case OMPD_end_declare_target:
  9488. case OMPD_teams:
  9489. case OMPD_simd:
  9490. case OMPD_for:
  9491. case OMPD_for_simd:
  9492. case OMPD_sections:
  9493. case OMPD_section:
  9494. case OMPD_single:
  9495. case OMPD_master:
  9496. case OMPD_critical:
  9497. case OMPD_taskgroup:
  9498. case OMPD_distribute:
  9499. case OMPD_ordered:
  9500. case OMPD_atomic:
  9501. case OMPD_distribute_simd:
  9502. case OMPD_teams_distribute:
  9503. case OMPD_teams_distribute_simd:
  9504. case OMPD_requires:
  9505. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  9506. case OMPD_unknown:
  9507. llvm_unreachable("Unknown OpenMP directive");
  9508. }
  9509. break;
  9510. case OMPC_num_threads:
  9511. switch (DKind) {
  9512. case OMPD_target_parallel:
  9513. case OMPD_target_parallel_for:
  9514. case OMPD_target_parallel_for_simd:
  9515. CaptureRegion = OMPD_target;
  9516. break;
  9517. case OMPD_teams_distribute_parallel_for:
  9518. case OMPD_teams_distribute_parallel_for_simd:
  9519. case OMPD_target_teams_distribute_parallel_for:
  9520. case OMPD_target_teams_distribute_parallel_for_simd:
  9521. CaptureRegion = OMPD_teams;
  9522. break;
  9523. case OMPD_parallel:
  9524. case OMPD_parallel_sections:
  9525. case OMPD_parallel_for:
  9526. case OMPD_parallel_for_simd:
  9527. case OMPD_distribute_parallel_for:
  9528. case OMPD_distribute_parallel_for_simd:
  9529. // Do not capture num_threads-clause expressions.
  9530. break;
  9531. case OMPD_target_data:
  9532. case OMPD_target_enter_data:
  9533. case OMPD_target_exit_data:
  9534. case OMPD_target_update:
  9535. case OMPD_target:
  9536. case OMPD_target_simd:
  9537. case OMPD_target_teams:
  9538. case OMPD_target_teams_distribute:
  9539. case OMPD_target_teams_distribute_simd:
  9540. case OMPD_cancel:
  9541. case OMPD_task:
  9542. case OMPD_taskloop:
  9543. case OMPD_taskloop_simd:
  9544. case OMPD_threadprivate:
  9545. case OMPD_allocate:
  9546. case OMPD_taskyield:
  9547. case OMPD_barrier:
  9548. case OMPD_taskwait:
  9549. case OMPD_cancellation_point:
  9550. case OMPD_flush:
  9551. case OMPD_declare_reduction:
  9552. case OMPD_declare_mapper:
  9553. case OMPD_declare_simd:
  9554. case OMPD_declare_variant:
  9555. case OMPD_declare_target:
  9556. case OMPD_end_declare_target:
  9557. case OMPD_teams:
  9558. case OMPD_simd:
  9559. case OMPD_for:
  9560. case OMPD_for_simd:
  9561. case OMPD_sections:
  9562. case OMPD_section:
  9563. case OMPD_single:
  9564. case OMPD_master:
  9565. case OMPD_critical:
  9566. case OMPD_taskgroup:
  9567. case OMPD_distribute:
  9568. case OMPD_ordered:
  9569. case OMPD_atomic:
  9570. case OMPD_distribute_simd:
  9571. case OMPD_teams_distribute:
  9572. case OMPD_teams_distribute_simd:
  9573. case OMPD_requires:
  9574. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  9575. case OMPD_unknown:
  9576. llvm_unreachable("Unknown OpenMP directive");
  9577. }
  9578. break;
  9579. case OMPC_num_teams:
  9580. switch (DKind) {
  9581. case OMPD_target_teams:
  9582. case OMPD_target_teams_distribute:
  9583. case OMPD_target_teams_distribute_simd:
  9584. case OMPD_target_teams_distribute_parallel_for:
  9585. case OMPD_target_teams_distribute_parallel_for_simd:
  9586. CaptureRegion = OMPD_target;
  9587. break;
  9588. case OMPD_teams_distribute_parallel_for:
  9589. case OMPD_teams_distribute_parallel_for_simd:
  9590. case OMPD_teams:
  9591. case OMPD_teams_distribute:
  9592. case OMPD_teams_distribute_simd:
  9593. // Do not capture num_teams-clause expressions.
  9594. break;
  9595. case OMPD_distribute_parallel_for:
  9596. case OMPD_distribute_parallel_for_simd:
  9597. case OMPD_task:
  9598. case OMPD_taskloop:
  9599. case OMPD_taskloop_simd:
  9600. case OMPD_target_data:
  9601. case OMPD_target_enter_data:
  9602. case OMPD_target_exit_data:
  9603. case OMPD_target_update:
  9604. case OMPD_cancel:
  9605. case OMPD_parallel:
  9606. case OMPD_parallel_sections:
  9607. case OMPD_parallel_for:
  9608. case OMPD_parallel_for_simd:
  9609. case OMPD_target:
  9610. case OMPD_target_simd:
  9611. case OMPD_target_parallel:
  9612. case OMPD_target_parallel_for:
  9613. case OMPD_target_parallel_for_simd:
  9614. case OMPD_threadprivate:
  9615. case OMPD_allocate:
  9616. case OMPD_taskyield:
  9617. case OMPD_barrier:
  9618. case OMPD_taskwait:
  9619. case OMPD_cancellation_point:
  9620. case OMPD_flush:
  9621. case OMPD_declare_reduction:
  9622. case OMPD_declare_mapper:
  9623. case OMPD_declare_simd:
  9624. case OMPD_declare_variant:
  9625. case OMPD_declare_target:
  9626. case OMPD_end_declare_target:
  9627. case OMPD_simd:
  9628. case OMPD_for:
  9629. case OMPD_for_simd:
  9630. case OMPD_sections:
  9631. case OMPD_section:
  9632. case OMPD_single:
  9633. case OMPD_master:
  9634. case OMPD_critical:
  9635. case OMPD_taskgroup:
  9636. case OMPD_distribute:
  9637. case OMPD_ordered:
  9638. case OMPD_atomic:
  9639. case OMPD_distribute_simd:
  9640. case OMPD_requires:
  9641. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9642. case OMPD_unknown:
  9643. llvm_unreachable("Unknown OpenMP directive");
  9644. }
  9645. break;
  9646. case OMPC_thread_limit:
  9647. switch (DKind) {
  9648. case OMPD_target_teams:
  9649. case OMPD_target_teams_distribute:
  9650. case OMPD_target_teams_distribute_simd:
  9651. case OMPD_target_teams_distribute_parallel_for:
  9652. case OMPD_target_teams_distribute_parallel_for_simd:
  9653. CaptureRegion = OMPD_target;
  9654. break;
  9655. case OMPD_teams_distribute_parallel_for:
  9656. case OMPD_teams_distribute_parallel_for_simd:
  9657. case OMPD_teams:
  9658. case OMPD_teams_distribute:
  9659. case OMPD_teams_distribute_simd:
  9660. // Do not capture thread_limit-clause expressions.
  9661. break;
  9662. case OMPD_distribute_parallel_for:
  9663. case OMPD_distribute_parallel_for_simd:
  9664. case OMPD_task:
  9665. case OMPD_taskloop:
  9666. case OMPD_taskloop_simd:
  9667. case OMPD_target_data:
  9668. case OMPD_target_enter_data:
  9669. case OMPD_target_exit_data:
  9670. case OMPD_target_update:
  9671. case OMPD_cancel:
  9672. case OMPD_parallel:
  9673. case OMPD_parallel_sections:
  9674. case OMPD_parallel_for:
  9675. case OMPD_parallel_for_simd:
  9676. case OMPD_target:
  9677. case OMPD_target_simd:
  9678. case OMPD_target_parallel:
  9679. case OMPD_target_parallel_for:
  9680. case OMPD_target_parallel_for_simd:
  9681. case OMPD_threadprivate:
  9682. case OMPD_allocate:
  9683. case OMPD_taskyield:
  9684. case OMPD_barrier:
  9685. case OMPD_taskwait:
  9686. case OMPD_cancellation_point:
  9687. case OMPD_flush:
  9688. case OMPD_declare_reduction:
  9689. case OMPD_declare_mapper:
  9690. case OMPD_declare_simd:
  9691. case OMPD_declare_variant:
  9692. case OMPD_declare_target:
  9693. case OMPD_end_declare_target:
  9694. case OMPD_simd:
  9695. case OMPD_for:
  9696. case OMPD_for_simd:
  9697. case OMPD_sections:
  9698. case OMPD_section:
  9699. case OMPD_single:
  9700. case OMPD_master:
  9701. case OMPD_critical:
  9702. case OMPD_taskgroup:
  9703. case OMPD_distribute:
  9704. case OMPD_ordered:
  9705. case OMPD_atomic:
  9706. case OMPD_distribute_simd:
  9707. case OMPD_requires:
  9708. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  9709. case OMPD_unknown:
  9710. llvm_unreachable("Unknown OpenMP directive");
  9711. }
  9712. break;
  9713. case OMPC_schedule:
  9714. switch (DKind) {
  9715. case OMPD_parallel_for:
  9716. case OMPD_parallel_for_simd:
  9717. case OMPD_distribute_parallel_for:
  9718. case OMPD_distribute_parallel_for_simd:
  9719. case OMPD_teams_distribute_parallel_for:
  9720. case OMPD_teams_distribute_parallel_for_simd:
  9721. case OMPD_target_parallel_for:
  9722. case OMPD_target_parallel_for_simd:
  9723. case OMPD_target_teams_distribute_parallel_for:
  9724. case OMPD_target_teams_distribute_parallel_for_simd:
  9725. CaptureRegion = OMPD_parallel;
  9726. break;
  9727. case OMPD_for:
  9728. case OMPD_for_simd:
  9729. // Do not capture schedule-clause expressions.
  9730. break;
  9731. case OMPD_task:
  9732. case OMPD_taskloop:
  9733. case OMPD_taskloop_simd:
  9734. case OMPD_target_data:
  9735. case OMPD_target_enter_data:
  9736. case OMPD_target_exit_data:
  9737. case OMPD_target_update:
  9738. case OMPD_teams:
  9739. case OMPD_teams_distribute:
  9740. case OMPD_teams_distribute_simd:
  9741. case OMPD_target_teams_distribute:
  9742. case OMPD_target_teams_distribute_simd:
  9743. case OMPD_target:
  9744. case OMPD_target_simd:
  9745. case OMPD_target_parallel:
  9746. case OMPD_cancel:
  9747. case OMPD_parallel:
  9748. case OMPD_parallel_sections:
  9749. case OMPD_threadprivate:
  9750. case OMPD_allocate:
  9751. case OMPD_taskyield:
  9752. case OMPD_barrier:
  9753. case OMPD_taskwait:
  9754. case OMPD_cancellation_point:
  9755. case OMPD_flush:
  9756. case OMPD_declare_reduction:
  9757. case OMPD_declare_mapper:
  9758. case OMPD_declare_simd:
  9759. case OMPD_declare_variant:
  9760. case OMPD_declare_target:
  9761. case OMPD_end_declare_target:
  9762. case OMPD_simd:
  9763. case OMPD_sections:
  9764. case OMPD_section:
  9765. case OMPD_single:
  9766. case OMPD_master:
  9767. case OMPD_critical:
  9768. case OMPD_taskgroup:
  9769. case OMPD_distribute:
  9770. case OMPD_ordered:
  9771. case OMPD_atomic:
  9772. case OMPD_distribute_simd:
  9773. case OMPD_target_teams:
  9774. case OMPD_requires:
  9775. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9776. case OMPD_unknown:
  9777. llvm_unreachable("Unknown OpenMP directive");
  9778. }
  9779. break;
  9780. case OMPC_dist_schedule:
  9781. switch (DKind) {
  9782. case OMPD_teams_distribute_parallel_for:
  9783. case OMPD_teams_distribute_parallel_for_simd:
  9784. case OMPD_teams_distribute:
  9785. case OMPD_teams_distribute_simd:
  9786. case OMPD_target_teams_distribute_parallel_for:
  9787. case OMPD_target_teams_distribute_parallel_for_simd:
  9788. case OMPD_target_teams_distribute:
  9789. case OMPD_target_teams_distribute_simd:
  9790. CaptureRegion = OMPD_teams;
  9791. break;
  9792. case OMPD_distribute_parallel_for:
  9793. case OMPD_distribute_parallel_for_simd:
  9794. case OMPD_distribute:
  9795. case OMPD_distribute_simd:
  9796. // Do not capture thread_limit-clause expressions.
  9797. break;
  9798. case OMPD_parallel_for:
  9799. case OMPD_parallel_for_simd:
  9800. case OMPD_target_parallel_for_simd:
  9801. case OMPD_target_parallel_for:
  9802. case OMPD_task:
  9803. case OMPD_taskloop:
  9804. case OMPD_taskloop_simd:
  9805. case OMPD_target_data:
  9806. case OMPD_target_enter_data:
  9807. case OMPD_target_exit_data:
  9808. case OMPD_target_update:
  9809. case OMPD_teams:
  9810. case OMPD_target:
  9811. case OMPD_target_simd:
  9812. case OMPD_target_parallel:
  9813. case OMPD_cancel:
  9814. case OMPD_parallel:
  9815. case OMPD_parallel_sections:
  9816. case OMPD_threadprivate:
  9817. case OMPD_allocate:
  9818. case OMPD_taskyield:
  9819. case OMPD_barrier:
  9820. case OMPD_taskwait:
  9821. case OMPD_cancellation_point:
  9822. case OMPD_flush:
  9823. case OMPD_declare_reduction:
  9824. case OMPD_declare_mapper:
  9825. case OMPD_declare_simd:
  9826. case OMPD_declare_variant:
  9827. case OMPD_declare_target:
  9828. case OMPD_end_declare_target:
  9829. case OMPD_simd:
  9830. case OMPD_for:
  9831. case OMPD_for_simd:
  9832. case OMPD_sections:
  9833. case OMPD_section:
  9834. case OMPD_single:
  9835. case OMPD_master:
  9836. case OMPD_critical:
  9837. case OMPD_taskgroup:
  9838. case OMPD_ordered:
  9839. case OMPD_atomic:
  9840. case OMPD_target_teams:
  9841. case OMPD_requires:
  9842. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9843. case OMPD_unknown:
  9844. llvm_unreachable("Unknown OpenMP directive");
  9845. }
  9846. break;
  9847. case OMPC_device:
  9848. switch (DKind) {
  9849. case OMPD_target_update:
  9850. case OMPD_target_enter_data:
  9851. case OMPD_target_exit_data:
  9852. case OMPD_target:
  9853. case OMPD_target_simd:
  9854. case OMPD_target_teams:
  9855. case OMPD_target_parallel:
  9856. case OMPD_target_teams_distribute:
  9857. case OMPD_target_teams_distribute_simd:
  9858. case OMPD_target_parallel_for:
  9859. case OMPD_target_parallel_for_simd:
  9860. case OMPD_target_teams_distribute_parallel_for:
  9861. case OMPD_target_teams_distribute_parallel_for_simd:
  9862. CaptureRegion = OMPD_task;
  9863. break;
  9864. case OMPD_target_data:
  9865. // Do not capture device-clause expressions.
  9866. break;
  9867. case OMPD_teams_distribute_parallel_for:
  9868. case OMPD_teams_distribute_parallel_for_simd:
  9869. case OMPD_teams:
  9870. case OMPD_teams_distribute:
  9871. case OMPD_teams_distribute_simd:
  9872. case OMPD_distribute_parallel_for:
  9873. case OMPD_distribute_parallel_for_simd:
  9874. case OMPD_task:
  9875. case OMPD_taskloop:
  9876. case OMPD_taskloop_simd:
  9877. case OMPD_cancel:
  9878. case OMPD_parallel:
  9879. case OMPD_parallel_sections:
  9880. case OMPD_parallel_for:
  9881. case OMPD_parallel_for_simd:
  9882. case OMPD_threadprivate:
  9883. case OMPD_allocate:
  9884. case OMPD_taskyield:
  9885. case OMPD_barrier:
  9886. case OMPD_taskwait:
  9887. case OMPD_cancellation_point:
  9888. case OMPD_flush:
  9889. case OMPD_declare_reduction:
  9890. case OMPD_declare_mapper:
  9891. case OMPD_declare_simd:
  9892. case OMPD_declare_variant:
  9893. case OMPD_declare_target:
  9894. case OMPD_end_declare_target:
  9895. case OMPD_simd:
  9896. case OMPD_for:
  9897. case OMPD_for_simd:
  9898. case OMPD_sections:
  9899. case OMPD_section:
  9900. case OMPD_single:
  9901. case OMPD_master:
  9902. case OMPD_critical:
  9903. case OMPD_taskgroup:
  9904. case OMPD_distribute:
  9905. case OMPD_ordered:
  9906. case OMPD_atomic:
  9907. case OMPD_distribute_simd:
  9908. case OMPD_requires:
  9909. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9910. case OMPD_unknown:
  9911. llvm_unreachable("Unknown OpenMP directive");
  9912. }
  9913. break;
  9914. case OMPC_firstprivate:
  9915. case OMPC_lastprivate:
  9916. case OMPC_reduction:
  9917. case OMPC_task_reduction:
  9918. case OMPC_in_reduction:
  9919. case OMPC_linear:
  9920. case OMPC_default:
  9921. case OMPC_proc_bind:
  9922. case OMPC_final:
  9923. case OMPC_safelen:
  9924. case OMPC_simdlen:
  9925. case OMPC_allocator:
  9926. case OMPC_collapse:
  9927. case OMPC_private:
  9928. case OMPC_shared:
  9929. case OMPC_aligned:
  9930. case OMPC_copyin:
  9931. case OMPC_copyprivate:
  9932. case OMPC_ordered:
  9933. case OMPC_nowait:
  9934. case OMPC_untied:
  9935. case OMPC_mergeable:
  9936. case OMPC_threadprivate:
  9937. case OMPC_allocate:
  9938. case OMPC_flush:
  9939. case OMPC_read:
  9940. case OMPC_write:
  9941. case OMPC_update:
  9942. case OMPC_capture:
  9943. case OMPC_seq_cst:
  9944. case OMPC_depend:
  9945. case OMPC_threads:
  9946. case OMPC_simd:
  9947. case OMPC_map:
  9948. case OMPC_priority:
  9949. case OMPC_grainsize:
  9950. case OMPC_nogroup:
  9951. case OMPC_num_tasks:
  9952. case OMPC_hint:
  9953. case OMPC_defaultmap:
  9954. case OMPC_unknown:
  9955. case OMPC_uniform:
  9956. case OMPC_to:
  9957. case OMPC_from:
  9958. case OMPC_use_device_ptr:
  9959. case OMPC_is_device_ptr:
  9960. case OMPC_unified_address:
  9961. case OMPC_unified_shared_memory:
  9962. case OMPC_reverse_offload:
  9963. case OMPC_dynamic_allocators:
  9964. case OMPC_atomic_default_mem_order:
  9965. case OMPC_device_type:
  9966. case OMPC_match:
  9967. llvm_unreachable("Unexpected OpenMP clause.");
  9968. }
  9969. return CaptureRegion;
  9970. }
  9971. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  9972. Expr *Condition, SourceLocation StartLoc,
  9973. SourceLocation LParenLoc,
  9974. SourceLocation NameModifierLoc,
  9975. SourceLocation ColonLoc,
  9976. SourceLocation EndLoc) {
  9977. Expr *ValExpr = Condition;
  9978. Stmt *HelperValStmt = nullptr;
  9979. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  9980. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  9981. !Condition->isInstantiationDependent() &&
  9982. !Condition->containsUnexpandedParameterPack()) {
  9983. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  9984. if (Val.isInvalid())
  9985. return nullptr;
  9986. ValExpr = Val.get();
  9987. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  9988. CaptureRegion =
  9989. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  9990. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  9991. ValExpr = MakeFullExpr(ValExpr).get();
  9992. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  9993. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  9994. HelperValStmt = buildPreInits(Context, Captures);
  9995. }
  9996. }
  9997. return new (Context)
  9998. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  9999. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  10000. }
  10001. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  10002. SourceLocation StartLoc,
  10003. SourceLocation LParenLoc,
  10004. SourceLocation EndLoc) {
  10005. Expr *ValExpr = Condition;
  10006. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  10007. !Condition->isInstantiationDependent() &&
  10008. !Condition->containsUnexpandedParameterPack()) {
  10009. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  10010. if (Val.isInvalid())
  10011. return nullptr;
  10012. ValExpr = MakeFullExpr(Val.get()).get();
  10013. }
  10014. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  10015. }
  10016. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  10017. Expr *Op) {
  10018. if (!Op)
  10019. return ExprError();
  10020. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  10021. public:
  10022. IntConvertDiagnoser()
  10023. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  10024. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10025. QualType T) override {
  10026. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  10027. }
  10028. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  10029. QualType T) override {
  10030. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  10031. }
  10032. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  10033. QualType T,
  10034. QualType ConvTy) override {
  10035. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  10036. }
  10037. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  10038. QualType ConvTy) override {
  10039. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10040. << ConvTy->isEnumeralType() << ConvTy;
  10041. }
  10042. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  10043. QualType T) override {
  10044. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  10045. }
  10046. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  10047. QualType ConvTy) override {
  10048. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10049. << ConvTy->isEnumeralType() << ConvTy;
  10050. }
  10051. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  10052. QualType) override {
  10053. llvm_unreachable("conversion functions are permitted");
  10054. }
  10055. } ConvertDiagnoser;
  10056. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  10057. }
  10058. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  10059. OpenMPClauseKind CKind,
  10060. bool StrictlyPositive) {
  10061. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  10062. !ValExpr->isInstantiationDependent()) {
  10063. SourceLocation Loc = ValExpr->getExprLoc();
  10064. ExprResult Value =
  10065. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  10066. if (Value.isInvalid())
  10067. return false;
  10068. ValExpr = Value.get();
  10069. // The expression must evaluate to a non-negative integer value.
  10070. llvm::APSInt Result;
  10071. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  10072. Result.isSigned() &&
  10073. !((!StrictlyPositive && Result.isNonNegative()) ||
  10074. (StrictlyPositive && Result.isStrictlyPositive()))) {
  10075. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  10076. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10077. << ValExpr->getSourceRange();
  10078. return false;
  10079. }
  10080. }
  10081. return true;
  10082. }
  10083. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  10084. SourceLocation StartLoc,
  10085. SourceLocation LParenLoc,
  10086. SourceLocation EndLoc) {
  10087. Expr *ValExpr = NumThreads;
  10088. Stmt *HelperValStmt = nullptr;
  10089. // OpenMP [2.5, Restrictions]
  10090. // The num_threads expression must evaluate to a positive integer value.
  10091. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  10092. /*StrictlyPositive=*/true))
  10093. return nullptr;
  10094. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10095. OpenMPDirectiveKind CaptureRegion =
  10096. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  10097. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10098. ValExpr = MakeFullExpr(ValExpr).get();
  10099. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10100. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10101. HelperValStmt = buildPreInits(Context, Captures);
  10102. }
  10103. return new (Context) OMPNumThreadsClause(
  10104. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  10105. }
  10106. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  10107. OpenMPClauseKind CKind,
  10108. bool StrictlyPositive) {
  10109. if (!E)
  10110. return ExprError();
  10111. if (E->isValueDependent() || E->isTypeDependent() ||
  10112. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  10113. return E;
  10114. llvm::APSInt Result;
  10115. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  10116. if (ICE.isInvalid())
  10117. return ExprError();
  10118. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  10119. (!StrictlyPositive && !Result.isNonNegative())) {
  10120. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  10121. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10122. << E->getSourceRange();
  10123. return ExprError();
  10124. }
  10125. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  10126. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  10127. << E->getSourceRange();
  10128. return ExprError();
  10129. }
  10130. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  10131. DSAStack->setAssociatedLoops(Result.getExtValue());
  10132. else if (CKind == OMPC_ordered)
  10133. DSAStack->setAssociatedLoops(Result.getExtValue());
  10134. return ICE;
  10135. }
  10136. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  10137. SourceLocation LParenLoc,
  10138. SourceLocation EndLoc) {
  10139. // OpenMP [2.8.1, simd construct, Description]
  10140. // The parameter of the safelen clause must be a constant
  10141. // positive integer expression.
  10142. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  10143. if (Safelen.isInvalid())
  10144. return nullptr;
  10145. return new (Context)
  10146. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  10147. }
  10148. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  10149. SourceLocation LParenLoc,
  10150. SourceLocation EndLoc) {
  10151. // OpenMP [2.8.1, simd construct, Description]
  10152. // The parameter of the simdlen clause must be a constant
  10153. // positive integer expression.
  10154. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  10155. if (Simdlen.isInvalid())
  10156. return nullptr;
  10157. return new (Context)
  10158. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  10159. }
  10160. /// Tries to find omp_allocator_handle_t type.
  10161. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  10162. DSAStackTy *Stack) {
  10163. QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
  10164. if (!OMPAllocatorHandleT.isNull())
  10165. return true;
  10166. // Build the predefined allocator expressions.
  10167. bool ErrorFound = false;
  10168. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  10169. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  10170. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  10171. StringRef Allocator =
  10172. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  10173. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  10174. auto *VD = dyn_cast_or_null<ValueDecl>(
  10175. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  10176. if (!VD) {
  10177. ErrorFound = true;
  10178. break;
  10179. }
  10180. QualType AllocatorType =
  10181. VD->getType().getNonLValueExprType(S.getASTContext());
  10182. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  10183. if (!Res.isUsable()) {
  10184. ErrorFound = true;
  10185. break;
  10186. }
  10187. if (OMPAllocatorHandleT.isNull())
  10188. OMPAllocatorHandleT = AllocatorType;
  10189. if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
  10190. ErrorFound = true;
  10191. break;
  10192. }
  10193. Stack->setAllocator(AllocatorKind, Res.get());
  10194. }
  10195. if (ErrorFound) {
  10196. S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
  10197. return false;
  10198. }
  10199. OMPAllocatorHandleT.addConst();
  10200. Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
  10201. return true;
  10202. }
  10203. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  10204. SourceLocation LParenLoc,
  10205. SourceLocation EndLoc) {
  10206. // OpenMP [2.11.3, allocate Directive, Description]
  10207. // allocator is an expression of omp_allocator_handle_t type.
  10208. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  10209. return nullptr;
  10210. ExprResult Allocator = DefaultLvalueConversion(A);
  10211. if (Allocator.isInvalid())
  10212. return nullptr;
  10213. Allocator = PerformImplicitConversion(Allocator.get(),
  10214. DSAStack->getOMPAllocatorHandleT(),
  10215. Sema::AA_Initializing,
  10216. /*AllowExplicit=*/true);
  10217. if (Allocator.isInvalid())
  10218. return nullptr;
  10219. return new (Context)
  10220. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  10221. }
  10222. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  10223. SourceLocation StartLoc,
  10224. SourceLocation LParenLoc,
  10225. SourceLocation EndLoc) {
  10226. // OpenMP [2.7.1, loop construct, Description]
  10227. // OpenMP [2.8.1, simd construct, Description]
  10228. // OpenMP [2.9.6, distribute construct, Description]
  10229. // The parameter of the collapse clause must be a constant
  10230. // positive integer expression.
  10231. ExprResult NumForLoopsResult =
  10232. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  10233. if (NumForLoopsResult.isInvalid())
  10234. return nullptr;
  10235. return new (Context)
  10236. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  10237. }
  10238. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  10239. SourceLocation EndLoc,
  10240. SourceLocation LParenLoc,
  10241. Expr *NumForLoops) {
  10242. // OpenMP [2.7.1, loop construct, Description]
  10243. // OpenMP [2.8.1, simd construct, Description]
  10244. // OpenMP [2.9.6, distribute construct, Description]
  10245. // The parameter of the ordered clause must be a constant
  10246. // positive integer expression if any.
  10247. if (NumForLoops && LParenLoc.isValid()) {
  10248. ExprResult NumForLoopsResult =
  10249. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  10250. if (NumForLoopsResult.isInvalid())
  10251. return nullptr;
  10252. NumForLoops = NumForLoopsResult.get();
  10253. } else {
  10254. NumForLoops = nullptr;
  10255. }
  10256. auto *Clause = OMPOrderedClause::Create(
  10257. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  10258. StartLoc, LParenLoc, EndLoc);
  10259. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  10260. return Clause;
  10261. }
  10262. OMPClause *Sema::ActOnOpenMPSimpleClause(
  10263. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  10264. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10265. OMPClause *Res = nullptr;
  10266. switch (Kind) {
  10267. case OMPC_default:
  10268. Res =
  10269. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  10270. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10271. break;
  10272. case OMPC_proc_bind:
  10273. Res = ActOnOpenMPProcBindClause(
  10274. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  10275. LParenLoc, EndLoc);
  10276. break;
  10277. case OMPC_atomic_default_mem_order:
  10278. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  10279. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  10280. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10281. break;
  10282. case OMPC_if:
  10283. case OMPC_final:
  10284. case OMPC_num_threads:
  10285. case OMPC_safelen:
  10286. case OMPC_simdlen:
  10287. case OMPC_allocator:
  10288. case OMPC_collapse:
  10289. case OMPC_schedule:
  10290. case OMPC_private:
  10291. case OMPC_firstprivate:
  10292. case OMPC_lastprivate:
  10293. case OMPC_shared:
  10294. case OMPC_reduction:
  10295. case OMPC_task_reduction:
  10296. case OMPC_in_reduction:
  10297. case OMPC_linear:
  10298. case OMPC_aligned:
  10299. case OMPC_copyin:
  10300. case OMPC_copyprivate:
  10301. case OMPC_ordered:
  10302. case OMPC_nowait:
  10303. case OMPC_untied:
  10304. case OMPC_mergeable:
  10305. case OMPC_threadprivate:
  10306. case OMPC_allocate:
  10307. case OMPC_flush:
  10308. case OMPC_read:
  10309. case OMPC_write:
  10310. case OMPC_update:
  10311. case OMPC_capture:
  10312. case OMPC_seq_cst:
  10313. case OMPC_depend:
  10314. case OMPC_device:
  10315. case OMPC_threads:
  10316. case OMPC_simd:
  10317. case OMPC_map:
  10318. case OMPC_num_teams:
  10319. case OMPC_thread_limit:
  10320. case OMPC_priority:
  10321. case OMPC_grainsize:
  10322. case OMPC_nogroup:
  10323. case OMPC_num_tasks:
  10324. case OMPC_hint:
  10325. case OMPC_dist_schedule:
  10326. case OMPC_defaultmap:
  10327. case OMPC_unknown:
  10328. case OMPC_uniform:
  10329. case OMPC_to:
  10330. case OMPC_from:
  10331. case OMPC_use_device_ptr:
  10332. case OMPC_is_device_ptr:
  10333. case OMPC_unified_address:
  10334. case OMPC_unified_shared_memory:
  10335. case OMPC_reverse_offload:
  10336. case OMPC_dynamic_allocators:
  10337. case OMPC_device_type:
  10338. case OMPC_match:
  10339. llvm_unreachable("Clause is not allowed.");
  10340. }
  10341. return Res;
  10342. }
  10343. static std::string
  10344. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  10345. ArrayRef<unsigned> Exclude = llvm::None) {
  10346. SmallString<256> Buffer;
  10347. llvm::raw_svector_ostream Out(Buffer);
  10348. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  10349. unsigned Skipped = Exclude.size();
  10350. auto S = Exclude.begin(), E = Exclude.end();
  10351. for (unsigned I = First; I < Last; ++I) {
  10352. if (std::find(S, E, I) != E) {
  10353. --Skipped;
  10354. continue;
  10355. }
  10356. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  10357. if (I == Bound - Skipped)
  10358. Out << " or ";
  10359. else if (I != Bound + 1 - Skipped)
  10360. Out << ", ";
  10361. }
  10362. return Out.str();
  10363. }
  10364. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  10365. SourceLocation KindKwLoc,
  10366. SourceLocation StartLoc,
  10367. SourceLocation LParenLoc,
  10368. SourceLocation EndLoc) {
  10369. if (Kind == OMPC_DEFAULT_unknown) {
  10370. static_assert(OMPC_DEFAULT_unknown > 0,
  10371. "OMPC_DEFAULT_unknown not greater than 0");
  10372. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10373. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  10374. /*Last=*/OMPC_DEFAULT_unknown)
  10375. << getOpenMPClauseName(OMPC_default);
  10376. return nullptr;
  10377. }
  10378. switch (Kind) {
  10379. case OMPC_DEFAULT_none:
  10380. DSAStack->setDefaultDSANone(KindKwLoc);
  10381. break;
  10382. case OMPC_DEFAULT_shared:
  10383. DSAStack->setDefaultDSAShared(KindKwLoc);
  10384. break;
  10385. case OMPC_DEFAULT_unknown:
  10386. llvm_unreachable("Clause kind is not allowed.");
  10387. break;
  10388. }
  10389. return new (Context)
  10390. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10391. }
  10392. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  10393. SourceLocation KindKwLoc,
  10394. SourceLocation StartLoc,
  10395. SourceLocation LParenLoc,
  10396. SourceLocation EndLoc) {
  10397. if (Kind == OMPC_PROC_BIND_unknown) {
  10398. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10399. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  10400. /*Last=*/OMPC_PROC_BIND_unknown)
  10401. << getOpenMPClauseName(OMPC_proc_bind);
  10402. return nullptr;
  10403. }
  10404. return new (Context)
  10405. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10406. }
  10407. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  10408. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  10409. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10410. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  10411. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10412. << getListOfPossibleValues(
  10413. OMPC_atomic_default_mem_order, /*First=*/0,
  10414. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  10415. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  10416. return nullptr;
  10417. }
  10418. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  10419. LParenLoc, EndLoc);
  10420. }
  10421. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  10422. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  10423. SourceLocation StartLoc, SourceLocation LParenLoc,
  10424. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  10425. SourceLocation EndLoc) {
  10426. OMPClause *Res = nullptr;
  10427. switch (Kind) {
  10428. case OMPC_schedule:
  10429. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  10430. assert(Argument.size() == NumberOfElements &&
  10431. ArgumentLoc.size() == NumberOfElements);
  10432. Res = ActOnOpenMPScheduleClause(
  10433. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  10434. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  10435. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  10436. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  10437. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  10438. break;
  10439. case OMPC_if:
  10440. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  10441. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  10442. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  10443. DelimLoc, EndLoc);
  10444. break;
  10445. case OMPC_dist_schedule:
  10446. Res = ActOnOpenMPDistScheduleClause(
  10447. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  10448. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  10449. break;
  10450. case OMPC_defaultmap:
  10451. enum { Modifier, DefaultmapKind };
  10452. Res = ActOnOpenMPDefaultmapClause(
  10453. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  10454. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  10455. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  10456. EndLoc);
  10457. break;
  10458. case OMPC_final:
  10459. case OMPC_num_threads:
  10460. case OMPC_safelen:
  10461. case OMPC_simdlen:
  10462. case OMPC_allocator:
  10463. case OMPC_collapse:
  10464. case OMPC_default:
  10465. case OMPC_proc_bind:
  10466. case OMPC_private:
  10467. case OMPC_firstprivate:
  10468. case OMPC_lastprivate:
  10469. case OMPC_shared:
  10470. case OMPC_reduction:
  10471. case OMPC_task_reduction:
  10472. case OMPC_in_reduction:
  10473. case OMPC_linear:
  10474. case OMPC_aligned:
  10475. case OMPC_copyin:
  10476. case OMPC_copyprivate:
  10477. case OMPC_ordered:
  10478. case OMPC_nowait:
  10479. case OMPC_untied:
  10480. case OMPC_mergeable:
  10481. case OMPC_threadprivate:
  10482. case OMPC_allocate:
  10483. case OMPC_flush:
  10484. case OMPC_read:
  10485. case OMPC_write:
  10486. case OMPC_update:
  10487. case OMPC_capture:
  10488. case OMPC_seq_cst:
  10489. case OMPC_depend:
  10490. case OMPC_device:
  10491. case OMPC_threads:
  10492. case OMPC_simd:
  10493. case OMPC_map:
  10494. case OMPC_num_teams:
  10495. case OMPC_thread_limit:
  10496. case OMPC_priority:
  10497. case OMPC_grainsize:
  10498. case OMPC_nogroup:
  10499. case OMPC_num_tasks:
  10500. case OMPC_hint:
  10501. case OMPC_unknown:
  10502. case OMPC_uniform:
  10503. case OMPC_to:
  10504. case OMPC_from:
  10505. case OMPC_use_device_ptr:
  10506. case OMPC_is_device_ptr:
  10507. case OMPC_unified_address:
  10508. case OMPC_unified_shared_memory:
  10509. case OMPC_reverse_offload:
  10510. case OMPC_dynamic_allocators:
  10511. case OMPC_atomic_default_mem_order:
  10512. case OMPC_device_type:
  10513. case OMPC_match:
  10514. llvm_unreachable("Clause is not allowed.");
  10515. }
  10516. return Res;
  10517. }
  10518. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  10519. OpenMPScheduleClauseModifier M2,
  10520. SourceLocation M1Loc, SourceLocation M2Loc) {
  10521. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  10522. SmallVector<unsigned, 2> Excluded;
  10523. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  10524. Excluded.push_back(M2);
  10525. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  10526. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  10527. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  10528. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  10529. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  10530. << getListOfPossibleValues(OMPC_schedule,
  10531. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  10532. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10533. Excluded)
  10534. << getOpenMPClauseName(OMPC_schedule);
  10535. return true;
  10536. }
  10537. return false;
  10538. }
  10539. OMPClause *Sema::ActOnOpenMPScheduleClause(
  10540. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  10541. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  10542. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  10543. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  10544. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  10545. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  10546. return nullptr;
  10547. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10548. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  10549. // but not both.
  10550. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  10551. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  10552. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  10553. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  10554. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  10555. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  10556. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  10557. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  10558. return nullptr;
  10559. }
  10560. if (Kind == OMPC_SCHEDULE_unknown) {
  10561. std::string Values;
  10562. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  10563. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  10564. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10565. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10566. Exclude);
  10567. } else {
  10568. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10569. /*Last=*/OMPC_SCHEDULE_unknown);
  10570. }
  10571. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  10572. << Values << getOpenMPClauseName(OMPC_schedule);
  10573. return nullptr;
  10574. }
  10575. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10576. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  10577. // schedule(guided).
  10578. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  10579. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  10580. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  10581. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  10582. diag::err_omp_schedule_nonmonotonic_static);
  10583. return nullptr;
  10584. }
  10585. Expr *ValExpr = ChunkSize;
  10586. Stmt *HelperValStmt = nullptr;
  10587. if (ChunkSize) {
  10588. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  10589. !ChunkSize->isInstantiationDependent() &&
  10590. !ChunkSize->containsUnexpandedParameterPack()) {
  10591. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  10592. ExprResult Val =
  10593. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  10594. if (Val.isInvalid())
  10595. return nullptr;
  10596. ValExpr = Val.get();
  10597. // OpenMP [2.7.1, Restrictions]
  10598. // chunk_size must be a loop invariant integer expression with a positive
  10599. // value.
  10600. llvm::APSInt Result;
  10601. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  10602. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  10603. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  10604. << "schedule" << 1 << ChunkSize->getSourceRange();
  10605. return nullptr;
  10606. }
  10607. } else if (getOpenMPCaptureRegionForClause(
  10608. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  10609. OMPD_unknown &&
  10610. !CurContext->isDependentContext()) {
  10611. ValExpr = MakeFullExpr(ValExpr).get();
  10612. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10613. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10614. HelperValStmt = buildPreInits(Context, Captures);
  10615. }
  10616. }
  10617. }
  10618. return new (Context)
  10619. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  10620. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  10621. }
  10622. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  10623. SourceLocation StartLoc,
  10624. SourceLocation EndLoc) {
  10625. OMPClause *Res = nullptr;
  10626. switch (Kind) {
  10627. case OMPC_ordered:
  10628. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  10629. break;
  10630. case OMPC_nowait:
  10631. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  10632. break;
  10633. case OMPC_untied:
  10634. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  10635. break;
  10636. case OMPC_mergeable:
  10637. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  10638. break;
  10639. case OMPC_read:
  10640. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  10641. break;
  10642. case OMPC_write:
  10643. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  10644. break;
  10645. case OMPC_update:
  10646. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  10647. break;
  10648. case OMPC_capture:
  10649. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  10650. break;
  10651. case OMPC_seq_cst:
  10652. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  10653. break;
  10654. case OMPC_threads:
  10655. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  10656. break;
  10657. case OMPC_simd:
  10658. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  10659. break;
  10660. case OMPC_nogroup:
  10661. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  10662. break;
  10663. case OMPC_unified_address:
  10664. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  10665. break;
  10666. case OMPC_unified_shared_memory:
  10667. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10668. break;
  10669. case OMPC_reverse_offload:
  10670. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  10671. break;
  10672. case OMPC_dynamic_allocators:
  10673. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10674. break;
  10675. case OMPC_if:
  10676. case OMPC_final:
  10677. case OMPC_num_threads:
  10678. case OMPC_safelen:
  10679. case OMPC_simdlen:
  10680. case OMPC_allocator:
  10681. case OMPC_collapse:
  10682. case OMPC_schedule:
  10683. case OMPC_private:
  10684. case OMPC_firstprivate:
  10685. case OMPC_lastprivate:
  10686. case OMPC_shared:
  10687. case OMPC_reduction:
  10688. case OMPC_task_reduction:
  10689. case OMPC_in_reduction:
  10690. case OMPC_linear:
  10691. case OMPC_aligned:
  10692. case OMPC_copyin:
  10693. case OMPC_copyprivate:
  10694. case OMPC_default:
  10695. case OMPC_proc_bind:
  10696. case OMPC_threadprivate:
  10697. case OMPC_allocate:
  10698. case OMPC_flush:
  10699. case OMPC_depend:
  10700. case OMPC_device:
  10701. case OMPC_map:
  10702. case OMPC_num_teams:
  10703. case OMPC_thread_limit:
  10704. case OMPC_priority:
  10705. case OMPC_grainsize:
  10706. case OMPC_num_tasks:
  10707. case OMPC_hint:
  10708. case OMPC_dist_schedule:
  10709. case OMPC_defaultmap:
  10710. case OMPC_unknown:
  10711. case OMPC_uniform:
  10712. case OMPC_to:
  10713. case OMPC_from:
  10714. case OMPC_use_device_ptr:
  10715. case OMPC_is_device_ptr:
  10716. case OMPC_atomic_default_mem_order:
  10717. case OMPC_device_type:
  10718. case OMPC_match:
  10719. llvm_unreachable("Clause is not allowed.");
  10720. }
  10721. return Res;
  10722. }
  10723. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  10724. SourceLocation EndLoc) {
  10725. DSAStack->setNowaitRegion();
  10726. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  10727. }
  10728. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  10729. SourceLocation EndLoc) {
  10730. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  10731. }
  10732. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  10733. SourceLocation EndLoc) {
  10734. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  10735. }
  10736. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  10737. SourceLocation EndLoc) {
  10738. return new (Context) OMPReadClause(StartLoc, EndLoc);
  10739. }
  10740. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  10741. SourceLocation EndLoc) {
  10742. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  10743. }
  10744. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  10745. SourceLocation EndLoc) {
  10746. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  10747. }
  10748. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  10749. SourceLocation EndLoc) {
  10750. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  10751. }
  10752. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  10753. SourceLocation EndLoc) {
  10754. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  10755. }
  10756. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  10757. SourceLocation EndLoc) {
  10758. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  10759. }
  10760. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  10761. SourceLocation EndLoc) {
  10762. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  10763. }
  10764. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  10765. SourceLocation EndLoc) {
  10766. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  10767. }
  10768. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  10769. SourceLocation EndLoc) {
  10770. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  10771. }
  10772. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  10773. SourceLocation EndLoc) {
  10774. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10775. }
  10776. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  10777. SourceLocation EndLoc) {
  10778. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  10779. }
  10780. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  10781. SourceLocation EndLoc) {
  10782. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10783. }
  10784. OMPClause *Sema::ActOnOpenMPVarListClause(
  10785. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  10786. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  10787. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  10788. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  10789. OpenMPLinearClauseKind LinKind,
  10790. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  10791. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  10792. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  10793. SourceLocation StartLoc = Locs.StartLoc;
  10794. SourceLocation LParenLoc = Locs.LParenLoc;
  10795. SourceLocation EndLoc = Locs.EndLoc;
  10796. OMPClause *Res = nullptr;
  10797. switch (Kind) {
  10798. case OMPC_private:
  10799. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10800. break;
  10801. case OMPC_firstprivate:
  10802. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10803. break;
  10804. case OMPC_lastprivate:
  10805. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10806. break;
  10807. case OMPC_shared:
  10808. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  10809. break;
  10810. case OMPC_reduction:
  10811. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10812. EndLoc, ReductionOrMapperIdScopeSpec,
  10813. ReductionOrMapperId);
  10814. break;
  10815. case OMPC_task_reduction:
  10816. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10817. EndLoc, ReductionOrMapperIdScopeSpec,
  10818. ReductionOrMapperId);
  10819. break;
  10820. case OMPC_in_reduction:
  10821. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10822. EndLoc, ReductionOrMapperIdScopeSpec,
  10823. ReductionOrMapperId);
  10824. break;
  10825. case OMPC_linear:
  10826. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  10827. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  10828. break;
  10829. case OMPC_aligned:
  10830. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  10831. ColonLoc, EndLoc);
  10832. break;
  10833. case OMPC_copyin:
  10834. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  10835. break;
  10836. case OMPC_copyprivate:
  10837. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10838. break;
  10839. case OMPC_flush:
  10840. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  10841. break;
  10842. case OMPC_depend:
  10843. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  10844. StartLoc, LParenLoc, EndLoc);
  10845. break;
  10846. case OMPC_map:
  10847. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  10848. ReductionOrMapperIdScopeSpec,
  10849. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  10850. DepLinMapLoc, ColonLoc, VarList, Locs);
  10851. break;
  10852. case OMPC_to:
  10853. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  10854. ReductionOrMapperId, Locs);
  10855. break;
  10856. case OMPC_from:
  10857. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  10858. ReductionOrMapperId, Locs);
  10859. break;
  10860. case OMPC_use_device_ptr:
  10861. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  10862. break;
  10863. case OMPC_is_device_ptr:
  10864. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  10865. break;
  10866. case OMPC_allocate:
  10867. Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
  10868. ColonLoc, EndLoc);
  10869. break;
  10870. case OMPC_if:
  10871. case OMPC_final:
  10872. case OMPC_num_threads:
  10873. case OMPC_safelen:
  10874. case OMPC_simdlen:
  10875. case OMPC_allocator:
  10876. case OMPC_collapse:
  10877. case OMPC_default:
  10878. case OMPC_proc_bind:
  10879. case OMPC_schedule:
  10880. case OMPC_ordered:
  10881. case OMPC_nowait:
  10882. case OMPC_untied:
  10883. case OMPC_mergeable:
  10884. case OMPC_threadprivate:
  10885. case OMPC_read:
  10886. case OMPC_write:
  10887. case OMPC_update:
  10888. case OMPC_capture:
  10889. case OMPC_seq_cst:
  10890. case OMPC_device:
  10891. case OMPC_threads:
  10892. case OMPC_simd:
  10893. case OMPC_num_teams:
  10894. case OMPC_thread_limit:
  10895. case OMPC_priority:
  10896. case OMPC_grainsize:
  10897. case OMPC_nogroup:
  10898. case OMPC_num_tasks:
  10899. case OMPC_hint:
  10900. case OMPC_dist_schedule:
  10901. case OMPC_defaultmap:
  10902. case OMPC_unknown:
  10903. case OMPC_uniform:
  10904. case OMPC_unified_address:
  10905. case OMPC_unified_shared_memory:
  10906. case OMPC_reverse_offload:
  10907. case OMPC_dynamic_allocators:
  10908. case OMPC_atomic_default_mem_order:
  10909. case OMPC_device_type:
  10910. case OMPC_match:
  10911. llvm_unreachable("Clause is not allowed.");
  10912. }
  10913. return Res;
  10914. }
  10915. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  10916. ExprObjectKind OK, SourceLocation Loc) {
  10917. ExprResult Res = BuildDeclRefExpr(
  10918. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  10919. if (!Res.isUsable())
  10920. return ExprError();
  10921. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  10922. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  10923. if (!Res.isUsable())
  10924. return ExprError();
  10925. }
  10926. if (VK != VK_LValue && Res.get()->isGLValue()) {
  10927. Res = DefaultLvalueConversion(Res.get());
  10928. if (!Res.isUsable())
  10929. return ExprError();
  10930. }
  10931. return Res;
  10932. }
  10933. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  10934. SourceLocation StartLoc,
  10935. SourceLocation LParenLoc,
  10936. SourceLocation EndLoc) {
  10937. SmallVector<Expr *, 8> Vars;
  10938. SmallVector<Expr *, 8> PrivateCopies;
  10939. for (Expr *RefExpr : VarList) {
  10940. assert(RefExpr && "NULL expr in OpenMP private clause.");
  10941. SourceLocation ELoc;
  10942. SourceRange ERange;
  10943. Expr *SimpleRefExpr = RefExpr;
  10944. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10945. if (Res.second) {
  10946. // It will be analyzed later.
  10947. Vars.push_back(RefExpr);
  10948. PrivateCopies.push_back(nullptr);
  10949. }
  10950. ValueDecl *D = Res.first;
  10951. if (!D)
  10952. continue;
  10953. QualType Type = D->getType();
  10954. auto *VD = dyn_cast<VarDecl>(D);
  10955. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10956. // A variable that appears in a private clause must not have an incomplete
  10957. // type or a reference type.
  10958. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  10959. continue;
  10960. Type = Type.getNonReferenceType();
  10961. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  10962. // A variable that is privatized must not have a const-qualified type
  10963. // unless it is of class type with a mutable member. This restriction does
  10964. // not apply to the firstprivate clause.
  10965. //
  10966. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  10967. // A variable that appears in a private clause must not have a
  10968. // const-qualified type unless it is of class type with a mutable member.
  10969. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  10970. continue;
  10971. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10972. // in a Construct]
  10973. // Variables with the predetermined data-sharing attributes may not be
  10974. // listed in data-sharing attributes clauses, except for the cases
  10975. // listed below. For these exceptions only, listing a predetermined
  10976. // variable in a data-sharing attribute clause is allowed and overrides
  10977. // the variable's predetermined data-sharing attributes.
  10978. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10979. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  10980. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10981. << getOpenMPClauseName(OMPC_private);
  10982. reportOriginalDsa(*this, DSAStack, D, DVar);
  10983. continue;
  10984. }
  10985. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  10986. // Variably modified types are not supported for tasks.
  10987. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  10988. isOpenMPTaskingDirective(CurrDir)) {
  10989. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10990. << getOpenMPClauseName(OMPC_private) << Type
  10991. << getOpenMPDirectiveName(CurrDir);
  10992. bool IsDecl =
  10993. !VD ||
  10994. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10995. Diag(D->getLocation(),
  10996. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10997. << D;
  10998. continue;
  10999. }
  11000. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11001. // A list item cannot appear in both a map clause and a data-sharing
  11002. // attribute clause on the same construct
  11003. //
  11004. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11005. // A list item cannot appear in both a map clause and a data-sharing
  11006. // attribute clause on the same construct unless the construct is a
  11007. // combined construct.
  11008. if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
  11009. CurrDir == OMPD_target) {
  11010. OpenMPClauseKind ConflictKind;
  11011. if (DSAStack->checkMappableExprComponentListsForDecl(
  11012. VD, /*CurrentRegionOnly=*/true,
  11013. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11014. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  11015. ConflictKind = WhereFoundClauseKind;
  11016. return true;
  11017. })) {
  11018. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11019. << getOpenMPClauseName(OMPC_private)
  11020. << getOpenMPClauseName(ConflictKind)
  11021. << getOpenMPDirectiveName(CurrDir);
  11022. reportOriginalDsa(*this, DSAStack, D, DVar);
  11023. continue;
  11024. }
  11025. }
  11026. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  11027. // A variable of class type (or array thereof) that appears in a private
  11028. // clause requires an accessible, unambiguous default constructor for the
  11029. // class type.
  11030. // Generate helper private variable and initialize it with the default
  11031. // value. The address of the original variable is replaced by the address of
  11032. // the new private variable in CodeGen. This new variable is not added to
  11033. // IdResolver, so the code in the OpenMP region uses original variable for
  11034. // proper diagnostics.
  11035. Type = Type.getUnqualifiedType();
  11036. VarDecl *VDPrivate =
  11037. buildVarDecl(*this, ELoc, Type, D->getName(),
  11038. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11039. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11040. ActOnUninitializedDecl(VDPrivate);
  11041. if (VDPrivate->isInvalidDecl())
  11042. continue;
  11043. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11044. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11045. DeclRefExpr *Ref = nullptr;
  11046. if (!VD && !CurContext->isDependentContext())
  11047. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11048. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  11049. Vars.push_back((VD || CurContext->isDependentContext())
  11050. ? RefExpr->IgnoreParens()
  11051. : Ref);
  11052. PrivateCopies.push_back(VDPrivateRefExpr);
  11053. }
  11054. if (Vars.empty())
  11055. return nullptr;
  11056. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11057. PrivateCopies);
  11058. }
  11059. namespace {
  11060. class DiagsUninitializedSeveretyRAII {
  11061. private:
  11062. DiagnosticsEngine &Diags;
  11063. SourceLocation SavedLoc;
  11064. bool IsIgnored = false;
  11065. public:
  11066. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  11067. bool IsIgnored)
  11068. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  11069. if (!IsIgnored) {
  11070. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  11071. /*Map*/ diag::Severity::Ignored, Loc);
  11072. }
  11073. }
  11074. ~DiagsUninitializedSeveretyRAII() {
  11075. if (!IsIgnored)
  11076. Diags.popMappings(SavedLoc);
  11077. }
  11078. };
  11079. }
  11080. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  11081. SourceLocation StartLoc,
  11082. SourceLocation LParenLoc,
  11083. SourceLocation EndLoc) {
  11084. SmallVector<Expr *, 8> Vars;
  11085. SmallVector<Expr *, 8> PrivateCopies;
  11086. SmallVector<Expr *, 8> Inits;
  11087. SmallVector<Decl *, 4> ExprCaptures;
  11088. bool IsImplicitClause =
  11089. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  11090. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  11091. for (Expr *RefExpr : VarList) {
  11092. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  11093. SourceLocation ELoc;
  11094. SourceRange ERange;
  11095. Expr *SimpleRefExpr = RefExpr;
  11096. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11097. if (Res.second) {
  11098. // It will be analyzed later.
  11099. Vars.push_back(RefExpr);
  11100. PrivateCopies.push_back(nullptr);
  11101. Inits.push_back(nullptr);
  11102. }
  11103. ValueDecl *D = Res.first;
  11104. if (!D)
  11105. continue;
  11106. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  11107. QualType Type = D->getType();
  11108. auto *VD = dyn_cast<VarDecl>(D);
  11109. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  11110. // A variable that appears in a private clause must not have an incomplete
  11111. // type or a reference type.
  11112. if (RequireCompleteType(ELoc, Type,
  11113. diag::err_omp_firstprivate_incomplete_type))
  11114. continue;
  11115. Type = Type.getNonReferenceType();
  11116. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  11117. // A variable of class type (or array thereof) that appears in a private
  11118. // clause requires an accessible, unambiguous copy constructor for the
  11119. // class type.
  11120. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11121. // If an implicit firstprivate variable found it was checked already.
  11122. DSAStackTy::DSAVarData TopDVar;
  11123. if (!IsImplicitClause) {
  11124. DSAStackTy::DSAVarData DVar =
  11125. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11126. TopDVar = DVar;
  11127. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11128. bool IsConstant = ElemType.isConstant(Context);
  11129. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  11130. // A list item that specifies a given variable may not appear in more
  11131. // than one clause on the same directive, except that a variable may be
  11132. // specified in both firstprivate and lastprivate clauses.
  11133. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11134. // A list item may appear in a firstprivate or lastprivate clause but not
  11135. // both.
  11136. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  11137. (isOpenMPDistributeDirective(CurrDir) ||
  11138. DVar.CKind != OMPC_lastprivate) &&
  11139. DVar.RefExpr) {
  11140. Diag(ELoc, diag::err_omp_wrong_dsa)
  11141. << getOpenMPClauseName(DVar.CKind)
  11142. << getOpenMPClauseName(OMPC_firstprivate);
  11143. reportOriginalDsa(*this, DSAStack, D, DVar);
  11144. continue;
  11145. }
  11146. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11147. // in a Construct]
  11148. // Variables with the predetermined data-sharing attributes may not be
  11149. // listed in data-sharing attributes clauses, except for the cases
  11150. // listed below. For these exceptions only, listing a predetermined
  11151. // variable in a data-sharing attribute clause is allowed and overrides
  11152. // the variable's predetermined data-sharing attributes.
  11153. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11154. // in a Construct, C/C++, p.2]
  11155. // Variables with const-qualified type having no mutable member may be
  11156. // listed in a firstprivate clause, even if they are static data members.
  11157. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  11158. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  11159. Diag(ELoc, diag::err_omp_wrong_dsa)
  11160. << getOpenMPClauseName(DVar.CKind)
  11161. << getOpenMPClauseName(OMPC_firstprivate);
  11162. reportOriginalDsa(*this, DSAStack, D, DVar);
  11163. continue;
  11164. }
  11165. // OpenMP [2.9.3.4, Restrictions, p.2]
  11166. // A list item that is private within a parallel region must not appear
  11167. // in a firstprivate clause on a worksharing construct if any of the
  11168. // worksharing regions arising from the worksharing construct ever bind
  11169. // to any of the parallel regions arising from the parallel construct.
  11170. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11171. // A list item that is private within a teams region must not appear in a
  11172. // firstprivate clause on a distribute construct if any of the distribute
  11173. // regions arising from the distribute construct ever bind to any of the
  11174. // teams regions arising from the teams construct.
  11175. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11176. // A list item that appears in a reduction clause of a teams construct
  11177. // must not appear in a firstprivate clause on a distribute construct if
  11178. // any of the distribute regions arising from the distribute construct
  11179. // ever bind to any of the teams regions arising from the teams construct.
  11180. if ((isOpenMPWorksharingDirective(CurrDir) ||
  11181. isOpenMPDistributeDirective(CurrDir)) &&
  11182. !isOpenMPParallelDirective(CurrDir) &&
  11183. !isOpenMPTeamsDirective(CurrDir)) {
  11184. DVar = DSAStack->getImplicitDSA(D, true);
  11185. if (DVar.CKind != OMPC_shared &&
  11186. (isOpenMPParallelDirective(DVar.DKind) ||
  11187. isOpenMPTeamsDirective(DVar.DKind) ||
  11188. DVar.DKind == OMPD_unknown)) {
  11189. Diag(ELoc, diag::err_omp_required_access)
  11190. << getOpenMPClauseName(OMPC_firstprivate)
  11191. << getOpenMPClauseName(OMPC_shared);
  11192. reportOriginalDsa(*this, DSAStack, D, DVar);
  11193. continue;
  11194. }
  11195. }
  11196. // OpenMP [2.9.3.4, Restrictions, p.3]
  11197. // A list item that appears in a reduction clause of a parallel construct
  11198. // must not appear in a firstprivate clause on a worksharing or task
  11199. // construct if any of the worksharing or task regions arising from the
  11200. // worksharing or task construct ever bind to any of the parallel regions
  11201. // arising from the parallel construct.
  11202. // OpenMP [2.9.3.4, Restrictions, p.4]
  11203. // A list item that appears in a reduction clause in worksharing
  11204. // construct must not appear in a firstprivate clause in a task construct
  11205. // encountered during execution of any of the worksharing regions arising
  11206. // from the worksharing construct.
  11207. if (isOpenMPTaskingDirective(CurrDir)) {
  11208. DVar = DSAStack->hasInnermostDSA(
  11209. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  11210. [](OpenMPDirectiveKind K) {
  11211. return isOpenMPParallelDirective(K) ||
  11212. isOpenMPWorksharingDirective(K) ||
  11213. isOpenMPTeamsDirective(K);
  11214. },
  11215. /*FromParent=*/true);
  11216. if (DVar.CKind == OMPC_reduction &&
  11217. (isOpenMPParallelDirective(DVar.DKind) ||
  11218. isOpenMPWorksharingDirective(DVar.DKind) ||
  11219. isOpenMPTeamsDirective(DVar.DKind))) {
  11220. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  11221. << getOpenMPDirectiveName(DVar.DKind);
  11222. reportOriginalDsa(*this, DSAStack, D, DVar);
  11223. continue;
  11224. }
  11225. }
  11226. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11227. // A list item cannot appear in both a map clause and a data-sharing
  11228. // attribute clause on the same construct
  11229. //
  11230. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11231. // A list item cannot appear in both a map clause and a data-sharing
  11232. // attribute clause on the same construct unless the construct is a
  11233. // combined construct.
  11234. if ((LangOpts.OpenMP <= 45 &&
  11235. isOpenMPTargetExecutionDirective(CurrDir)) ||
  11236. CurrDir == OMPD_target) {
  11237. OpenMPClauseKind ConflictKind;
  11238. if (DSAStack->checkMappableExprComponentListsForDecl(
  11239. VD, /*CurrentRegionOnly=*/true,
  11240. [&ConflictKind](
  11241. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11242. OpenMPClauseKind WhereFoundClauseKind) {
  11243. ConflictKind = WhereFoundClauseKind;
  11244. return true;
  11245. })) {
  11246. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11247. << getOpenMPClauseName(OMPC_firstprivate)
  11248. << getOpenMPClauseName(ConflictKind)
  11249. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11250. reportOriginalDsa(*this, DSAStack, D, DVar);
  11251. continue;
  11252. }
  11253. }
  11254. }
  11255. // Variably modified types are not supported for tasks.
  11256. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  11257. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  11258. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11259. << getOpenMPClauseName(OMPC_firstprivate) << Type
  11260. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11261. bool IsDecl =
  11262. !VD ||
  11263. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11264. Diag(D->getLocation(),
  11265. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11266. << D;
  11267. continue;
  11268. }
  11269. Type = Type.getUnqualifiedType();
  11270. VarDecl *VDPrivate =
  11271. buildVarDecl(*this, ELoc, Type, D->getName(),
  11272. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11273. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11274. // Generate helper private variable and initialize it with the value of the
  11275. // original variable. The address of the original variable is replaced by
  11276. // the address of the new private variable in the CodeGen. This new variable
  11277. // is not added to IdResolver, so the code in the OpenMP region uses
  11278. // original variable for proper diagnostics and variable capturing.
  11279. Expr *VDInitRefExpr = nullptr;
  11280. // For arrays generate initializer for single element and replace it by the
  11281. // original array element in CodeGen.
  11282. if (Type->isArrayType()) {
  11283. VarDecl *VDInit =
  11284. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  11285. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  11286. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  11287. ElemType = ElemType.getUnqualifiedType();
  11288. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  11289. ".firstprivate.temp");
  11290. InitializedEntity Entity =
  11291. InitializedEntity::InitializeVariable(VDInitTemp);
  11292. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  11293. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  11294. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  11295. if (Result.isInvalid())
  11296. VDPrivate->setInvalidDecl();
  11297. else
  11298. VDPrivate->setInit(Result.getAs<Expr>());
  11299. // Remove temp variable declaration.
  11300. Context.Deallocate(VDInitTemp);
  11301. } else {
  11302. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  11303. ".firstprivate.temp");
  11304. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11305. RefExpr->getExprLoc());
  11306. AddInitializerToDecl(VDPrivate,
  11307. DefaultLvalueConversion(VDInitRefExpr).get(),
  11308. /*DirectInit=*/false);
  11309. }
  11310. if (VDPrivate->isInvalidDecl()) {
  11311. if (IsImplicitClause) {
  11312. Diag(RefExpr->getExprLoc(),
  11313. diag::note_omp_task_predetermined_firstprivate_here);
  11314. }
  11315. continue;
  11316. }
  11317. CurContext->addDecl(VDPrivate);
  11318. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11319. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  11320. RefExpr->getExprLoc());
  11321. DeclRefExpr *Ref = nullptr;
  11322. if (!VD && !CurContext->isDependentContext()) {
  11323. if (TopDVar.CKind == OMPC_lastprivate) {
  11324. Ref = TopDVar.PrivateCopy;
  11325. } else {
  11326. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11327. if (!isOpenMPCapturedDecl(D))
  11328. ExprCaptures.push_back(Ref->getDecl());
  11329. }
  11330. }
  11331. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11332. Vars.push_back((VD || CurContext->isDependentContext())
  11333. ? RefExpr->IgnoreParens()
  11334. : Ref);
  11335. PrivateCopies.push_back(VDPrivateRefExpr);
  11336. Inits.push_back(VDInitRefExpr);
  11337. }
  11338. if (Vars.empty())
  11339. return nullptr;
  11340. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11341. Vars, PrivateCopies, Inits,
  11342. buildPreInits(Context, ExprCaptures));
  11343. }
  11344. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  11345. SourceLocation StartLoc,
  11346. SourceLocation LParenLoc,
  11347. SourceLocation EndLoc) {
  11348. SmallVector<Expr *, 8> Vars;
  11349. SmallVector<Expr *, 8> SrcExprs;
  11350. SmallVector<Expr *, 8> DstExprs;
  11351. SmallVector<Expr *, 8> AssignmentOps;
  11352. SmallVector<Decl *, 4> ExprCaptures;
  11353. SmallVector<Expr *, 4> ExprPostUpdates;
  11354. for (Expr *RefExpr : VarList) {
  11355. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11356. SourceLocation ELoc;
  11357. SourceRange ERange;
  11358. Expr *SimpleRefExpr = RefExpr;
  11359. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11360. if (Res.second) {
  11361. // It will be analyzed later.
  11362. Vars.push_back(RefExpr);
  11363. SrcExprs.push_back(nullptr);
  11364. DstExprs.push_back(nullptr);
  11365. AssignmentOps.push_back(nullptr);
  11366. }
  11367. ValueDecl *D = Res.first;
  11368. if (!D)
  11369. continue;
  11370. QualType Type = D->getType();
  11371. auto *VD = dyn_cast<VarDecl>(D);
  11372. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  11373. // A variable that appears in a lastprivate clause must not have an
  11374. // incomplete type or a reference type.
  11375. if (RequireCompleteType(ELoc, Type,
  11376. diag::err_omp_lastprivate_incomplete_type))
  11377. continue;
  11378. Type = Type.getNonReferenceType();
  11379. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11380. // A variable that is privatized must not have a const-qualified type
  11381. // unless it is of class type with a mutable member. This restriction does
  11382. // not apply to the firstprivate clause.
  11383. //
  11384. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  11385. // A variable that appears in a lastprivate clause must not have a
  11386. // const-qualified type unless it is of class type with a mutable member.
  11387. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  11388. continue;
  11389. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11390. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  11391. // in a Construct]
  11392. // Variables with the predetermined data-sharing attributes may not be
  11393. // listed in data-sharing attributes clauses, except for the cases
  11394. // listed below.
  11395. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11396. // A list item may appear in a firstprivate or lastprivate clause but not
  11397. // both.
  11398. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11399. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  11400. (isOpenMPDistributeDirective(CurrDir) ||
  11401. DVar.CKind != OMPC_firstprivate) &&
  11402. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  11403. Diag(ELoc, diag::err_omp_wrong_dsa)
  11404. << getOpenMPClauseName(DVar.CKind)
  11405. << getOpenMPClauseName(OMPC_lastprivate);
  11406. reportOriginalDsa(*this, DSAStack, D, DVar);
  11407. continue;
  11408. }
  11409. // OpenMP [2.14.3.5, Restrictions, p.2]
  11410. // A list item that is private within a parallel region, or that appears in
  11411. // the reduction clause of a parallel construct, must not appear in a
  11412. // lastprivate clause on a worksharing construct if any of the corresponding
  11413. // worksharing regions ever binds to any of the corresponding parallel
  11414. // regions.
  11415. DSAStackTy::DSAVarData TopDVar = DVar;
  11416. if (isOpenMPWorksharingDirective(CurrDir) &&
  11417. !isOpenMPParallelDirective(CurrDir) &&
  11418. !isOpenMPTeamsDirective(CurrDir)) {
  11419. DVar = DSAStack->getImplicitDSA(D, true);
  11420. if (DVar.CKind != OMPC_shared) {
  11421. Diag(ELoc, diag::err_omp_required_access)
  11422. << getOpenMPClauseName(OMPC_lastprivate)
  11423. << getOpenMPClauseName(OMPC_shared);
  11424. reportOriginalDsa(*this, DSAStack, D, DVar);
  11425. continue;
  11426. }
  11427. }
  11428. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  11429. // A variable of class type (or array thereof) that appears in a
  11430. // lastprivate clause requires an accessible, unambiguous default
  11431. // constructor for the class type, unless the list item is also specified
  11432. // in a firstprivate clause.
  11433. // A variable of class type (or array thereof) that appears in a
  11434. // lastprivate clause requires an accessible, unambiguous copy assignment
  11435. // operator for the class type.
  11436. Type = Context.getBaseElementType(Type).getNonReferenceType();
  11437. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  11438. Type.getUnqualifiedType(), ".lastprivate.src",
  11439. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11440. DeclRefExpr *PseudoSrcExpr =
  11441. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  11442. VarDecl *DstVD =
  11443. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  11444. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11445. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11446. // For arrays generate assignment operation for single element and replace
  11447. // it by the original array element in CodeGen.
  11448. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  11449. PseudoDstExpr, PseudoSrcExpr);
  11450. if (AssignmentOp.isInvalid())
  11451. continue;
  11452. AssignmentOp =
  11453. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  11454. if (AssignmentOp.isInvalid())
  11455. continue;
  11456. DeclRefExpr *Ref = nullptr;
  11457. if (!VD && !CurContext->isDependentContext()) {
  11458. if (TopDVar.CKind == OMPC_firstprivate) {
  11459. Ref = TopDVar.PrivateCopy;
  11460. } else {
  11461. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11462. if (!isOpenMPCapturedDecl(D))
  11463. ExprCaptures.push_back(Ref->getDecl());
  11464. }
  11465. if (TopDVar.CKind == OMPC_firstprivate ||
  11466. (!isOpenMPCapturedDecl(D) &&
  11467. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  11468. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11469. if (!RefRes.isUsable())
  11470. continue;
  11471. ExprResult PostUpdateRes =
  11472. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  11473. RefRes.get());
  11474. if (!PostUpdateRes.isUsable())
  11475. continue;
  11476. ExprPostUpdates.push_back(
  11477. IgnoredValueConversions(PostUpdateRes.get()).get());
  11478. }
  11479. }
  11480. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  11481. Vars.push_back((VD || CurContext->isDependentContext())
  11482. ? RefExpr->IgnoreParens()
  11483. : Ref);
  11484. SrcExprs.push_back(PseudoSrcExpr);
  11485. DstExprs.push_back(PseudoDstExpr);
  11486. AssignmentOps.push_back(AssignmentOp.get());
  11487. }
  11488. if (Vars.empty())
  11489. return nullptr;
  11490. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11491. Vars, SrcExprs, DstExprs, AssignmentOps,
  11492. buildPreInits(Context, ExprCaptures),
  11493. buildPostUpdate(*this, ExprPostUpdates));
  11494. }
  11495. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  11496. SourceLocation StartLoc,
  11497. SourceLocation LParenLoc,
  11498. SourceLocation EndLoc) {
  11499. SmallVector<Expr *, 8> Vars;
  11500. for (Expr *RefExpr : VarList) {
  11501. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11502. SourceLocation ELoc;
  11503. SourceRange ERange;
  11504. Expr *SimpleRefExpr = RefExpr;
  11505. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11506. if (Res.second) {
  11507. // It will be analyzed later.
  11508. Vars.push_back(RefExpr);
  11509. }
  11510. ValueDecl *D = Res.first;
  11511. if (!D)
  11512. continue;
  11513. auto *VD = dyn_cast<VarDecl>(D);
  11514. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11515. // in a Construct]
  11516. // Variables with the predetermined data-sharing attributes may not be
  11517. // listed in data-sharing attributes clauses, except for the cases
  11518. // listed below. For these exceptions only, listing a predetermined
  11519. // variable in a data-sharing attribute clause is allowed and overrides
  11520. // the variable's predetermined data-sharing attributes.
  11521. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11522. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  11523. DVar.RefExpr) {
  11524. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11525. << getOpenMPClauseName(OMPC_shared);
  11526. reportOriginalDsa(*this, DSAStack, D, DVar);
  11527. continue;
  11528. }
  11529. DeclRefExpr *Ref = nullptr;
  11530. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  11531. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11532. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  11533. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  11534. ? RefExpr->IgnoreParens()
  11535. : Ref);
  11536. }
  11537. if (Vars.empty())
  11538. return nullptr;
  11539. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  11540. }
  11541. namespace {
  11542. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  11543. DSAStackTy *Stack;
  11544. public:
  11545. bool VisitDeclRefExpr(DeclRefExpr *E) {
  11546. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  11547. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  11548. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  11549. return false;
  11550. if (DVar.CKind != OMPC_unknown)
  11551. return true;
  11552. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  11553. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  11554. /*FromParent=*/true);
  11555. return DVarPrivate.CKind != OMPC_unknown;
  11556. }
  11557. return false;
  11558. }
  11559. bool VisitStmt(Stmt *S) {
  11560. for (Stmt *Child : S->children()) {
  11561. if (Child && Visit(Child))
  11562. return true;
  11563. }
  11564. return false;
  11565. }
  11566. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  11567. };
  11568. } // namespace
  11569. namespace {
  11570. // Transform MemberExpression for specified FieldDecl of current class to
  11571. // DeclRefExpr to specified OMPCapturedExprDecl.
  11572. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  11573. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  11574. ValueDecl *Field = nullptr;
  11575. DeclRefExpr *CapturedExpr = nullptr;
  11576. public:
  11577. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  11578. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  11579. ExprResult TransformMemberExpr(MemberExpr *E) {
  11580. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  11581. E->getMemberDecl() == Field) {
  11582. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  11583. return CapturedExpr;
  11584. }
  11585. return BaseTransform::TransformMemberExpr(E);
  11586. }
  11587. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  11588. };
  11589. } // namespace
  11590. template <typename T, typename U>
  11591. static T filterLookupForUDReductionAndMapper(
  11592. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  11593. for (U &Set : Lookups) {
  11594. for (auto *D : Set) {
  11595. if (T Res = Gen(cast<ValueDecl>(D)))
  11596. return Res;
  11597. }
  11598. }
  11599. return T();
  11600. }
  11601. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  11602. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  11603. for (auto RD : D->redecls()) {
  11604. // Don't bother with extra checks if we already know this one isn't visible.
  11605. if (RD == D)
  11606. continue;
  11607. auto ND = cast<NamedDecl>(RD);
  11608. if (LookupResult::isVisible(SemaRef, ND))
  11609. return ND;
  11610. }
  11611. return nullptr;
  11612. }
  11613. static void
  11614. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  11615. SourceLocation Loc, QualType Ty,
  11616. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  11617. // Find all of the associated namespaces and classes based on the
  11618. // arguments we have.
  11619. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  11620. Sema::AssociatedClassSet AssociatedClasses;
  11621. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  11622. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  11623. AssociatedClasses);
  11624. // C++ [basic.lookup.argdep]p3:
  11625. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  11626. // and let Y be the lookup set produced by argument dependent
  11627. // lookup (defined as follows). If X contains [...] then Y is
  11628. // empty. Otherwise Y is the set of declarations found in the
  11629. // namespaces associated with the argument types as described
  11630. // below. The set of declarations found by the lookup of the name
  11631. // is the union of X and Y.
  11632. //
  11633. // Here, we compute Y and add its members to the overloaded
  11634. // candidate set.
  11635. for (auto *NS : AssociatedNamespaces) {
  11636. // When considering an associated namespace, the lookup is the
  11637. // same as the lookup performed when the associated namespace is
  11638. // used as a qualifier (3.4.3.2) except that:
  11639. //
  11640. // -- Any using-directives in the associated namespace are
  11641. // ignored.
  11642. //
  11643. // -- Any namespace-scope friend functions declared in
  11644. // associated classes are visible within their respective
  11645. // namespaces even if they are not visible during an ordinary
  11646. // lookup (11.4).
  11647. DeclContext::lookup_result R = NS->lookup(Id.getName());
  11648. for (auto *D : R) {
  11649. auto *Underlying = D;
  11650. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11651. Underlying = USD->getTargetDecl();
  11652. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  11653. !isa<OMPDeclareMapperDecl>(Underlying))
  11654. continue;
  11655. if (!SemaRef.isVisible(D)) {
  11656. D = findAcceptableDecl(SemaRef, D);
  11657. if (!D)
  11658. continue;
  11659. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11660. Underlying = USD->getTargetDecl();
  11661. }
  11662. Lookups.emplace_back();
  11663. Lookups.back().addDecl(Underlying);
  11664. }
  11665. }
  11666. }
  11667. static ExprResult
  11668. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  11669. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  11670. const DeclarationNameInfo &ReductionId, QualType Ty,
  11671. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  11672. if (ReductionIdScopeSpec.isInvalid())
  11673. return ExprError();
  11674. SmallVector<UnresolvedSet<8>, 4> Lookups;
  11675. if (S) {
  11676. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11677. Lookup.suppressDiagnostics();
  11678. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  11679. NamedDecl *D = Lookup.getRepresentativeDecl();
  11680. do {
  11681. S = S->getParent();
  11682. } while (S && !S->isDeclScope(D));
  11683. if (S)
  11684. S = S->getParent();
  11685. Lookups.emplace_back();
  11686. Lookups.back().append(Lookup.begin(), Lookup.end());
  11687. Lookup.clear();
  11688. }
  11689. } else if (auto *ULE =
  11690. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  11691. Lookups.push_back(UnresolvedSet<8>());
  11692. Decl *PrevD = nullptr;
  11693. for (NamedDecl *D : ULE->decls()) {
  11694. if (D == PrevD)
  11695. Lookups.push_back(UnresolvedSet<8>());
  11696. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  11697. Lookups.back().addDecl(DRD);
  11698. PrevD = D;
  11699. }
  11700. }
  11701. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  11702. Ty->isInstantiationDependentType() ||
  11703. Ty->containsUnexpandedParameterPack() ||
  11704. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  11705. return !D->isInvalidDecl() &&
  11706. (D->getType()->isDependentType() ||
  11707. D->getType()->isInstantiationDependentType() ||
  11708. D->getType()->containsUnexpandedParameterPack());
  11709. })) {
  11710. UnresolvedSet<8> ResSet;
  11711. for (const UnresolvedSet<8> &Set : Lookups) {
  11712. if (Set.empty())
  11713. continue;
  11714. ResSet.append(Set.begin(), Set.end());
  11715. // The last item marks the end of all declarations at the specified scope.
  11716. ResSet.addDecl(Set[Set.size() - 1]);
  11717. }
  11718. return UnresolvedLookupExpr::Create(
  11719. SemaRef.Context, /*NamingClass=*/nullptr,
  11720. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  11721. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  11722. }
  11723. // Lookup inside the classes.
  11724. // C++ [over.match.oper]p3:
  11725. // For a unary operator @ with an operand of a type whose
  11726. // cv-unqualified version is T1, and for a binary operator @ with
  11727. // a left operand of a type whose cv-unqualified version is T1 and
  11728. // a right operand of a type whose cv-unqualified version is T2,
  11729. // three sets of candidate functions, designated member
  11730. // candidates, non-member candidates and built-in candidates, are
  11731. // constructed as follows:
  11732. // -- If T1 is a complete class type or a class currently being
  11733. // defined, the set of member candidates is the result of the
  11734. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  11735. // the set of member candidates is empty.
  11736. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11737. Lookup.suppressDiagnostics();
  11738. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  11739. // Complete the type if it can be completed.
  11740. // If the type is neither complete nor being defined, bail out now.
  11741. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  11742. TyRec->getDecl()->getDefinition()) {
  11743. Lookup.clear();
  11744. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  11745. if (Lookup.empty()) {
  11746. Lookups.emplace_back();
  11747. Lookups.back().append(Lookup.begin(), Lookup.end());
  11748. }
  11749. }
  11750. }
  11751. // Perform ADL.
  11752. if (SemaRef.getLangOpts().CPlusPlus)
  11753. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  11754. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  11755. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  11756. if (!D->isInvalidDecl() &&
  11757. SemaRef.Context.hasSameType(D->getType(), Ty))
  11758. return D;
  11759. return nullptr;
  11760. }))
  11761. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  11762. VK_LValue, Loc);
  11763. if (SemaRef.getLangOpts().CPlusPlus) {
  11764. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  11765. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  11766. if (!D->isInvalidDecl() &&
  11767. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  11768. !Ty.isMoreQualifiedThan(D->getType()))
  11769. return D;
  11770. return nullptr;
  11771. })) {
  11772. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  11773. /*DetectVirtual=*/false);
  11774. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  11775. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  11776. VD->getType().getUnqualifiedType()))) {
  11777. if (SemaRef.CheckBaseClassAccess(
  11778. Loc, VD->getType(), Ty, Paths.front(),
  11779. /*DiagID=*/0) != Sema::AR_inaccessible) {
  11780. SemaRef.BuildBasePathArray(Paths, BasePath);
  11781. return SemaRef.BuildDeclRefExpr(
  11782. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  11783. }
  11784. }
  11785. }
  11786. }
  11787. }
  11788. if (ReductionIdScopeSpec.isSet()) {
  11789. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  11790. return ExprError();
  11791. }
  11792. return ExprEmpty();
  11793. }
  11794. namespace {
  11795. /// Data for the reduction-based clauses.
  11796. struct ReductionData {
  11797. /// List of original reduction items.
  11798. SmallVector<Expr *, 8> Vars;
  11799. /// List of private copies of the reduction items.
  11800. SmallVector<Expr *, 8> Privates;
  11801. /// LHS expressions for the reduction_op expressions.
  11802. SmallVector<Expr *, 8> LHSs;
  11803. /// RHS expressions for the reduction_op expressions.
  11804. SmallVector<Expr *, 8> RHSs;
  11805. /// Reduction operation expression.
  11806. SmallVector<Expr *, 8> ReductionOps;
  11807. /// Taskgroup descriptors for the corresponding reduction items in
  11808. /// in_reduction clauses.
  11809. SmallVector<Expr *, 8> TaskgroupDescriptors;
  11810. /// List of captures for clause.
  11811. SmallVector<Decl *, 4> ExprCaptures;
  11812. /// List of postupdate expressions.
  11813. SmallVector<Expr *, 4> ExprPostUpdates;
  11814. ReductionData() = delete;
  11815. /// Reserves required memory for the reduction data.
  11816. ReductionData(unsigned Size) {
  11817. Vars.reserve(Size);
  11818. Privates.reserve(Size);
  11819. LHSs.reserve(Size);
  11820. RHSs.reserve(Size);
  11821. ReductionOps.reserve(Size);
  11822. TaskgroupDescriptors.reserve(Size);
  11823. ExprCaptures.reserve(Size);
  11824. ExprPostUpdates.reserve(Size);
  11825. }
  11826. /// Stores reduction item and reduction operation only (required for dependent
  11827. /// reduction item).
  11828. void push(Expr *Item, Expr *ReductionOp) {
  11829. Vars.emplace_back(Item);
  11830. Privates.emplace_back(nullptr);
  11831. LHSs.emplace_back(nullptr);
  11832. RHSs.emplace_back(nullptr);
  11833. ReductionOps.emplace_back(ReductionOp);
  11834. TaskgroupDescriptors.emplace_back(nullptr);
  11835. }
  11836. /// Stores reduction data.
  11837. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  11838. Expr *TaskgroupDescriptor) {
  11839. Vars.emplace_back(Item);
  11840. Privates.emplace_back(Private);
  11841. LHSs.emplace_back(LHS);
  11842. RHSs.emplace_back(RHS);
  11843. ReductionOps.emplace_back(ReductionOp);
  11844. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  11845. }
  11846. };
  11847. } // namespace
  11848. static bool checkOMPArraySectionConstantForReduction(
  11849. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  11850. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  11851. const Expr *Length = OASE->getLength();
  11852. if (Length == nullptr) {
  11853. // For array sections of the form [1:] or [:], we would need to analyze
  11854. // the lower bound...
  11855. if (OASE->getColonLoc().isValid())
  11856. return false;
  11857. // This is an array subscript which has implicit length 1!
  11858. SingleElement = true;
  11859. ArraySizes.push_back(llvm::APSInt::get(1));
  11860. } else {
  11861. Expr::EvalResult Result;
  11862. if (!Length->EvaluateAsInt(Result, Context))
  11863. return false;
  11864. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11865. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  11866. ArraySizes.push_back(ConstantLengthValue);
  11867. }
  11868. // Get the base of this array section and walk up from there.
  11869. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  11870. // We require length = 1 for all array sections except the right-most to
  11871. // guarantee that the memory region is contiguous and has no holes in it.
  11872. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  11873. Length = TempOASE->getLength();
  11874. if (Length == nullptr) {
  11875. // For array sections of the form [1:] or [:], we would need to analyze
  11876. // the lower bound...
  11877. if (OASE->getColonLoc().isValid())
  11878. return false;
  11879. // This is an array subscript which has implicit length 1!
  11880. ArraySizes.push_back(llvm::APSInt::get(1));
  11881. } else {
  11882. Expr::EvalResult Result;
  11883. if (!Length->EvaluateAsInt(Result, Context))
  11884. return false;
  11885. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11886. if (ConstantLengthValue.getSExtValue() != 1)
  11887. return false;
  11888. ArraySizes.push_back(ConstantLengthValue);
  11889. }
  11890. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  11891. }
  11892. // If we have a single element, we don't need to add the implicit lengths.
  11893. if (!SingleElement) {
  11894. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  11895. // Has implicit length 1!
  11896. ArraySizes.push_back(llvm::APSInt::get(1));
  11897. Base = TempASE->getBase()->IgnoreParenImpCasts();
  11898. }
  11899. }
  11900. // This array section can be privatized as a single value or as a constant
  11901. // sized array.
  11902. return true;
  11903. }
  11904. static bool actOnOMPReductionKindClause(
  11905. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  11906. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11907. SourceLocation ColonLoc, SourceLocation EndLoc,
  11908. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11909. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  11910. DeclarationName DN = ReductionId.getName();
  11911. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  11912. BinaryOperatorKind BOK = BO_Comma;
  11913. ASTContext &Context = S.Context;
  11914. // OpenMP [2.14.3.6, reduction clause]
  11915. // C
  11916. // reduction-identifier is either an identifier or one of the following
  11917. // operators: +, -, *, &, |, ^, && and ||
  11918. // C++
  11919. // reduction-identifier is either an id-expression or one of the following
  11920. // operators: +, -, *, &, |, ^, && and ||
  11921. switch (OOK) {
  11922. case OO_Plus:
  11923. case OO_Minus:
  11924. BOK = BO_Add;
  11925. break;
  11926. case OO_Star:
  11927. BOK = BO_Mul;
  11928. break;
  11929. case OO_Amp:
  11930. BOK = BO_And;
  11931. break;
  11932. case OO_Pipe:
  11933. BOK = BO_Or;
  11934. break;
  11935. case OO_Caret:
  11936. BOK = BO_Xor;
  11937. break;
  11938. case OO_AmpAmp:
  11939. BOK = BO_LAnd;
  11940. break;
  11941. case OO_PipePipe:
  11942. BOK = BO_LOr;
  11943. break;
  11944. case OO_New:
  11945. case OO_Delete:
  11946. case OO_Array_New:
  11947. case OO_Array_Delete:
  11948. case OO_Slash:
  11949. case OO_Percent:
  11950. case OO_Tilde:
  11951. case OO_Exclaim:
  11952. case OO_Equal:
  11953. case OO_Less:
  11954. case OO_Greater:
  11955. case OO_LessEqual:
  11956. case OO_GreaterEqual:
  11957. case OO_PlusEqual:
  11958. case OO_MinusEqual:
  11959. case OO_StarEqual:
  11960. case OO_SlashEqual:
  11961. case OO_PercentEqual:
  11962. case OO_CaretEqual:
  11963. case OO_AmpEqual:
  11964. case OO_PipeEqual:
  11965. case OO_LessLess:
  11966. case OO_GreaterGreater:
  11967. case OO_LessLessEqual:
  11968. case OO_GreaterGreaterEqual:
  11969. case OO_EqualEqual:
  11970. case OO_ExclaimEqual:
  11971. case OO_Spaceship:
  11972. case OO_PlusPlus:
  11973. case OO_MinusMinus:
  11974. case OO_Comma:
  11975. case OO_ArrowStar:
  11976. case OO_Arrow:
  11977. case OO_Call:
  11978. case OO_Subscript:
  11979. case OO_Conditional:
  11980. case OO_Coawait:
  11981. case NUM_OVERLOADED_OPERATORS:
  11982. llvm_unreachable("Unexpected reduction identifier");
  11983. case OO_None:
  11984. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  11985. if (II->isStr("max"))
  11986. BOK = BO_GT;
  11987. else if (II->isStr("min"))
  11988. BOK = BO_LT;
  11989. }
  11990. break;
  11991. }
  11992. SourceRange ReductionIdRange;
  11993. if (ReductionIdScopeSpec.isValid())
  11994. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  11995. else
  11996. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  11997. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  11998. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  11999. bool FirstIter = true;
  12000. for (Expr *RefExpr : VarList) {
  12001. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  12002. // OpenMP [2.1, C/C++]
  12003. // A list item is a variable or array section, subject to the restrictions
  12004. // specified in Section 2.4 on page 42 and in each of the sections
  12005. // describing clauses and directives for which a list appears.
  12006. // OpenMP [2.14.3.3, Restrictions, p.1]
  12007. // A variable that is part of another variable (as an array or
  12008. // structure element) cannot appear in a private clause.
  12009. if (!FirstIter && IR != ER)
  12010. ++IR;
  12011. FirstIter = false;
  12012. SourceLocation ELoc;
  12013. SourceRange ERange;
  12014. Expr *SimpleRefExpr = RefExpr;
  12015. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  12016. /*AllowArraySection=*/true);
  12017. if (Res.second) {
  12018. // Try to find 'declare reduction' corresponding construct before using
  12019. // builtin/overloaded operators.
  12020. QualType Type = Context.DependentTy;
  12021. CXXCastPath BasePath;
  12022. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12023. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12024. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12025. Expr *ReductionOp = nullptr;
  12026. if (S.CurContext->isDependentContext() &&
  12027. (DeclareReductionRef.isUnset() ||
  12028. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  12029. ReductionOp = DeclareReductionRef.get();
  12030. // It will be analyzed later.
  12031. RD.push(RefExpr, ReductionOp);
  12032. }
  12033. ValueDecl *D = Res.first;
  12034. if (!D)
  12035. continue;
  12036. Expr *TaskgroupDescriptor = nullptr;
  12037. QualType Type;
  12038. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  12039. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  12040. if (ASE) {
  12041. Type = ASE->getType().getNonReferenceType();
  12042. } else if (OASE) {
  12043. QualType BaseType =
  12044. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  12045. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  12046. Type = ATy->getElementType();
  12047. else
  12048. Type = BaseType->getPointeeType();
  12049. Type = Type.getNonReferenceType();
  12050. } else {
  12051. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  12052. }
  12053. auto *VD = dyn_cast<VarDecl>(D);
  12054. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  12055. // A variable that appears in a private clause must not have an incomplete
  12056. // type or a reference type.
  12057. if (S.RequireCompleteType(ELoc, D->getType(),
  12058. diag::err_omp_reduction_incomplete_type))
  12059. continue;
  12060. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12061. // A list item that appears in a reduction clause must not be
  12062. // const-qualified.
  12063. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  12064. /*AcceptIfMutable*/ false, ASE || OASE))
  12065. continue;
  12066. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  12067. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  12068. // If a list-item is a reference type then it must bind to the same object
  12069. // for all threads of the team.
  12070. if (!ASE && !OASE) {
  12071. if (VD) {
  12072. VarDecl *VDDef = VD->getDefinition();
  12073. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  12074. DSARefChecker Check(Stack);
  12075. if (Check.Visit(VDDef->getInit())) {
  12076. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  12077. << getOpenMPClauseName(ClauseKind) << ERange;
  12078. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  12079. continue;
  12080. }
  12081. }
  12082. }
  12083. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  12084. // in a Construct]
  12085. // Variables with the predetermined data-sharing attributes may not be
  12086. // listed in data-sharing attributes clauses, except for the cases
  12087. // listed below. For these exceptions only, listing a predetermined
  12088. // variable in a data-sharing attribute clause is allowed and overrides
  12089. // the variable's predetermined data-sharing attributes.
  12090. // OpenMP [2.14.3.6, Restrictions, p.3]
  12091. // Any number of reduction clauses can be specified on the directive,
  12092. // but a list item can appear only once in the reduction clauses for that
  12093. // directive.
  12094. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  12095. if (DVar.CKind == OMPC_reduction) {
  12096. S.Diag(ELoc, diag::err_omp_once_referenced)
  12097. << getOpenMPClauseName(ClauseKind);
  12098. if (DVar.RefExpr)
  12099. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  12100. continue;
  12101. }
  12102. if (DVar.CKind != OMPC_unknown) {
  12103. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  12104. << getOpenMPClauseName(DVar.CKind)
  12105. << getOpenMPClauseName(OMPC_reduction);
  12106. reportOriginalDsa(S, Stack, D, DVar);
  12107. continue;
  12108. }
  12109. // OpenMP [2.14.3.6, Restrictions, p.1]
  12110. // A list item that appears in a reduction clause of a worksharing
  12111. // construct must be shared in the parallel regions to which any of the
  12112. // worksharing regions arising from the worksharing construct bind.
  12113. if (isOpenMPWorksharingDirective(CurrDir) &&
  12114. !isOpenMPParallelDirective(CurrDir) &&
  12115. !isOpenMPTeamsDirective(CurrDir)) {
  12116. DVar = Stack->getImplicitDSA(D, true);
  12117. if (DVar.CKind != OMPC_shared) {
  12118. S.Diag(ELoc, diag::err_omp_required_access)
  12119. << getOpenMPClauseName(OMPC_reduction)
  12120. << getOpenMPClauseName(OMPC_shared);
  12121. reportOriginalDsa(S, Stack, D, DVar);
  12122. continue;
  12123. }
  12124. }
  12125. }
  12126. // Try to find 'declare reduction' corresponding construct before using
  12127. // builtin/overloaded operators.
  12128. CXXCastPath BasePath;
  12129. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12130. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12131. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12132. if (DeclareReductionRef.isInvalid())
  12133. continue;
  12134. if (S.CurContext->isDependentContext() &&
  12135. (DeclareReductionRef.isUnset() ||
  12136. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  12137. RD.push(RefExpr, DeclareReductionRef.get());
  12138. continue;
  12139. }
  12140. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  12141. // Not allowed reduction identifier is found.
  12142. S.Diag(ReductionId.getBeginLoc(),
  12143. diag::err_omp_unknown_reduction_identifier)
  12144. << Type << ReductionIdRange;
  12145. continue;
  12146. }
  12147. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12148. // The type of a list item that appears in a reduction clause must be valid
  12149. // for the reduction-identifier. For a max or min reduction in C, the type
  12150. // of the list item must be an allowed arithmetic data type: char, int,
  12151. // float, double, or _Bool, possibly modified with long, short, signed, or
  12152. // unsigned. For a max or min reduction in C++, the type of the list item
  12153. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  12154. // double, or bool, possibly modified with long, short, signed, or unsigned.
  12155. if (DeclareReductionRef.isUnset()) {
  12156. if ((BOK == BO_GT || BOK == BO_LT) &&
  12157. !(Type->isScalarType() ||
  12158. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  12159. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  12160. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  12161. if (!ASE && !OASE) {
  12162. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12163. VarDecl::DeclarationOnly;
  12164. S.Diag(D->getLocation(),
  12165. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12166. << D;
  12167. }
  12168. continue;
  12169. }
  12170. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  12171. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  12172. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  12173. << getOpenMPClauseName(ClauseKind);
  12174. if (!ASE && !OASE) {
  12175. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12176. VarDecl::DeclarationOnly;
  12177. S.Diag(D->getLocation(),
  12178. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12179. << D;
  12180. }
  12181. continue;
  12182. }
  12183. }
  12184. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  12185. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  12186. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12187. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  12188. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12189. QualType PrivateTy = Type;
  12190. // Try if we can determine constant lengths for all array sections and avoid
  12191. // the VLA.
  12192. bool ConstantLengthOASE = false;
  12193. if (OASE) {
  12194. bool SingleElement;
  12195. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  12196. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  12197. Context, OASE, SingleElement, ArraySizes);
  12198. // If we don't have a single element, we must emit a constant array type.
  12199. if (ConstantLengthOASE && !SingleElement) {
  12200. for (llvm::APSInt &Size : ArraySizes)
  12201. PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
  12202. ArrayType::Normal,
  12203. /*IndexTypeQuals=*/0);
  12204. }
  12205. }
  12206. if ((OASE && !ConstantLengthOASE) ||
  12207. (!OASE && !ASE &&
  12208. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  12209. if (!Context.getTargetInfo().isVLASupported()) {
  12210. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
  12211. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12212. S.Diag(ELoc, diag::note_vla_unsupported);
  12213. } else {
  12214. S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12215. S.targetDiag(ELoc, diag::note_vla_unsupported);
  12216. }
  12217. continue;
  12218. }
  12219. // For arrays/array sections only:
  12220. // Create pseudo array type for private copy. The size for this array will
  12221. // be generated during codegen.
  12222. // For array subscripts or single variables Private Ty is the same as Type
  12223. // (type of the variable or single array element).
  12224. PrivateTy = Context.getVariableArrayType(
  12225. Type,
  12226. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  12227. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  12228. } else if (!ASE && !OASE &&
  12229. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  12230. PrivateTy = D->getType().getNonReferenceType();
  12231. }
  12232. // Private copy.
  12233. VarDecl *PrivateVD =
  12234. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  12235. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12236. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12237. // Add initializer for private variable.
  12238. Expr *Init = nullptr;
  12239. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  12240. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  12241. if (DeclareReductionRef.isUsable()) {
  12242. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  12243. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  12244. if (DRD->getInitializer()) {
  12245. Init = DRDRef;
  12246. RHSVD->setInit(DRDRef);
  12247. RHSVD->setInitStyle(VarDecl::CallInit);
  12248. }
  12249. } else {
  12250. switch (BOK) {
  12251. case BO_Add:
  12252. case BO_Xor:
  12253. case BO_Or:
  12254. case BO_LOr:
  12255. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  12256. if (Type->isScalarType() || Type->isAnyComplexType())
  12257. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  12258. break;
  12259. case BO_Mul:
  12260. case BO_LAnd:
  12261. if (Type->isScalarType() || Type->isAnyComplexType()) {
  12262. // '*' and '&&' reduction ops - initializer is '1'.
  12263. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  12264. }
  12265. break;
  12266. case BO_And: {
  12267. // '&' reduction op - initializer is '~0'.
  12268. QualType OrigType = Type;
  12269. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  12270. Type = ComplexTy->getElementType();
  12271. if (Type->isRealFloatingType()) {
  12272. llvm::APFloat InitValue =
  12273. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  12274. /*isIEEE=*/true);
  12275. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12276. Type, ELoc);
  12277. } else if (Type->isScalarType()) {
  12278. uint64_t Size = Context.getTypeSize(Type);
  12279. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  12280. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  12281. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12282. }
  12283. if (Init && OrigType->isAnyComplexType()) {
  12284. // Init = 0xFFFF + 0xFFFFi;
  12285. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  12286. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  12287. }
  12288. Type = OrigType;
  12289. break;
  12290. }
  12291. case BO_LT:
  12292. case BO_GT: {
  12293. // 'min' reduction op - initializer is 'Largest representable number in
  12294. // the reduction list item type'.
  12295. // 'max' reduction op - initializer is 'Least representable number in
  12296. // the reduction list item type'.
  12297. if (Type->isIntegerType() || Type->isPointerType()) {
  12298. bool IsSigned = Type->hasSignedIntegerRepresentation();
  12299. uint64_t Size = Context.getTypeSize(Type);
  12300. QualType IntTy =
  12301. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  12302. llvm::APInt InitValue =
  12303. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  12304. : llvm::APInt::getMinValue(Size)
  12305. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  12306. : llvm::APInt::getMaxValue(Size);
  12307. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12308. if (Type->isPointerType()) {
  12309. // Cast to pointer type.
  12310. ExprResult CastExpr = S.BuildCStyleCastExpr(
  12311. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  12312. if (CastExpr.isInvalid())
  12313. continue;
  12314. Init = CastExpr.get();
  12315. }
  12316. } else if (Type->isRealFloatingType()) {
  12317. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  12318. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  12319. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12320. Type, ELoc);
  12321. }
  12322. break;
  12323. }
  12324. case BO_PtrMemD:
  12325. case BO_PtrMemI:
  12326. case BO_MulAssign:
  12327. case BO_Div:
  12328. case BO_Rem:
  12329. case BO_Sub:
  12330. case BO_Shl:
  12331. case BO_Shr:
  12332. case BO_LE:
  12333. case BO_GE:
  12334. case BO_EQ:
  12335. case BO_NE:
  12336. case BO_Cmp:
  12337. case BO_AndAssign:
  12338. case BO_XorAssign:
  12339. case BO_OrAssign:
  12340. case BO_Assign:
  12341. case BO_AddAssign:
  12342. case BO_SubAssign:
  12343. case BO_DivAssign:
  12344. case BO_RemAssign:
  12345. case BO_ShlAssign:
  12346. case BO_ShrAssign:
  12347. case BO_Comma:
  12348. llvm_unreachable("Unexpected reduction operation");
  12349. }
  12350. }
  12351. if (Init && DeclareReductionRef.isUnset())
  12352. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  12353. else if (!Init)
  12354. S.ActOnUninitializedDecl(RHSVD);
  12355. if (RHSVD->isInvalidDecl())
  12356. continue;
  12357. if (!RHSVD->hasInit() &&
  12358. (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
  12359. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  12360. << Type << ReductionIdRange;
  12361. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12362. VarDecl::DeclarationOnly;
  12363. S.Diag(D->getLocation(),
  12364. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12365. << D;
  12366. continue;
  12367. }
  12368. // Store initializer for single element in private copy. Will be used during
  12369. // codegen.
  12370. PrivateVD->setInit(RHSVD->getInit());
  12371. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  12372. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  12373. ExprResult ReductionOp;
  12374. if (DeclareReductionRef.isUsable()) {
  12375. QualType RedTy = DeclareReductionRef.get()->getType();
  12376. QualType PtrRedTy = Context.getPointerType(RedTy);
  12377. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  12378. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  12379. if (!BasePath.empty()) {
  12380. LHS = S.DefaultLvalueConversion(LHS.get());
  12381. RHS = S.DefaultLvalueConversion(RHS.get());
  12382. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12383. CK_UncheckedDerivedToBase, LHS.get(),
  12384. &BasePath, LHS.get()->getValueKind());
  12385. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12386. CK_UncheckedDerivedToBase, RHS.get(),
  12387. &BasePath, RHS.get()->getValueKind());
  12388. }
  12389. FunctionProtoType::ExtProtoInfo EPI;
  12390. QualType Params[] = {PtrRedTy, PtrRedTy};
  12391. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  12392. auto *OVE = new (Context) OpaqueValueExpr(
  12393. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  12394. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  12395. Expr *Args[] = {LHS.get(), RHS.get()};
  12396. ReductionOp =
  12397. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  12398. } else {
  12399. ReductionOp = S.BuildBinOp(
  12400. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  12401. if (ReductionOp.isUsable()) {
  12402. if (BOK != BO_LT && BOK != BO_GT) {
  12403. ReductionOp =
  12404. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12405. BO_Assign, LHSDRE, ReductionOp.get());
  12406. } else {
  12407. auto *ConditionalOp = new (Context)
  12408. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  12409. Type, VK_LValue, OK_Ordinary);
  12410. ReductionOp =
  12411. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12412. BO_Assign, LHSDRE, ConditionalOp);
  12413. }
  12414. if (ReductionOp.isUsable())
  12415. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  12416. /*DiscardedValue*/ false);
  12417. }
  12418. if (!ReductionOp.isUsable())
  12419. continue;
  12420. }
  12421. // OpenMP [2.15.4.6, Restrictions, p.2]
  12422. // A list item that appears in an in_reduction clause of a task construct
  12423. // must appear in a task_reduction clause of a construct associated with a
  12424. // taskgroup region that includes the participating task in its taskgroup
  12425. // set. The construct associated with the innermost region that meets this
  12426. // condition must specify the same reduction-identifier as the in_reduction
  12427. // clause.
  12428. if (ClauseKind == OMPC_in_reduction) {
  12429. SourceRange ParentSR;
  12430. BinaryOperatorKind ParentBOK;
  12431. const Expr *ParentReductionOp;
  12432. Expr *ParentBOKTD, *ParentReductionOpTD;
  12433. DSAStackTy::DSAVarData ParentBOKDSA =
  12434. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  12435. ParentBOKTD);
  12436. DSAStackTy::DSAVarData ParentReductionOpDSA =
  12437. Stack->getTopMostTaskgroupReductionData(
  12438. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  12439. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  12440. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  12441. if (!IsParentBOK && !IsParentReductionOp) {
  12442. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  12443. continue;
  12444. }
  12445. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  12446. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  12447. IsParentReductionOp) {
  12448. bool EmitError = true;
  12449. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  12450. llvm::FoldingSetNodeID RedId, ParentRedId;
  12451. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  12452. DeclareReductionRef.get()->Profile(RedId, Context,
  12453. /*Canonical=*/true);
  12454. EmitError = RedId != ParentRedId;
  12455. }
  12456. if (EmitError) {
  12457. S.Diag(ReductionId.getBeginLoc(),
  12458. diag::err_omp_reduction_identifier_mismatch)
  12459. << ReductionIdRange << RefExpr->getSourceRange();
  12460. S.Diag(ParentSR.getBegin(),
  12461. diag::note_omp_previous_reduction_identifier)
  12462. << ParentSR
  12463. << (IsParentBOK ? ParentBOKDSA.RefExpr
  12464. : ParentReductionOpDSA.RefExpr)
  12465. ->getSourceRange();
  12466. continue;
  12467. }
  12468. }
  12469. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  12470. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  12471. }
  12472. DeclRefExpr *Ref = nullptr;
  12473. Expr *VarsExpr = RefExpr->IgnoreParens();
  12474. if (!VD && !S.CurContext->isDependentContext()) {
  12475. if (ASE || OASE) {
  12476. TransformExprToCaptures RebuildToCapture(S, D);
  12477. VarsExpr =
  12478. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  12479. Ref = RebuildToCapture.getCapturedExpr();
  12480. } else {
  12481. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  12482. }
  12483. if (!S.isOpenMPCapturedDecl(D)) {
  12484. RD.ExprCaptures.emplace_back(Ref->getDecl());
  12485. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12486. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  12487. if (!RefRes.isUsable())
  12488. continue;
  12489. ExprResult PostUpdateRes =
  12490. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  12491. RefRes.get());
  12492. if (!PostUpdateRes.isUsable())
  12493. continue;
  12494. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  12495. Stack->getCurrentDirective() == OMPD_taskgroup) {
  12496. S.Diag(RefExpr->getExprLoc(),
  12497. diag::err_omp_reduction_non_addressable_expression)
  12498. << RefExpr->getSourceRange();
  12499. continue;
  12500. }
  12501. RD.ExprPostUpdates.emplace_back(
  12502. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  12503. }
  12504. }
  12505. }
  12506. // All reduction items are still marked as reduction (to do not increase
  12507. // code base size).
  12508. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  12509. if (CurrDir == OMPD_taskgroup) {
  12510. if (DeclareReductionRef.isUsable())
  12511. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  12512. DeclareReductionRef.get());
  12513. else
  12514. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  12515. }
  12516. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  12517. TaskgroupDescriptor);
  12518. }
  12519. return RD.Vars.empty();
  12520. }
  12521. OMPClause *Sema::ActOnOpenMPReductionClause(
  12522. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12523. SourceLocation ColonLoc, SourceLocation EndLoc,
  12524. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12525. ArrayRef<Expr *> UnresolvedReductions) {
  12526. ReductionData RD(VarList.size());
  12527. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  12528. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12529. ReductionIdScopeSpec, ReductionId,
  12530. UnresolvedReductions, RD))
  12531. return nullptr;
  12532. return OMPReductionClause::Create(
  12533. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12534. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12535. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12536. buildPreInits(Context, RD.ExprCaptures),
  12537. buildPostUpdate(*this, RD.ExprPostUpdates));
  12538. }
  12539. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  12540. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12541. SourceLocation ColonLoc, SourceLocation EndLoc,
  12542. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12543. ArrayRef<Expr *> UnresolvedReductions) {
  12544. ReductionData RD(VarList.size());
  12545. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  12546. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12547. ReductionIdScopeSpec, ReductionId,
  12548. UnresolvedReductions, RD))
  12549. return nullptr;
  12550. return OMPTaskReductionClause::Create(
  12551. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12552. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12553. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12554. buildPreInits(Context, RD.ExprCaptures),
  12555. buildPostUpdate(*this, RD.ExprPostUpdates));
  12556. }
  12557. OMPClause *Sema::ActOnOpenMPInReductionClause(
  12558. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12559. SourceLocation ColonLoc, SourceLocation EndLoc,
  12560. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12561. ArrayRef<Expr *> UnresolvedReductions) {
  12562. ReductionData RD(VarList.size());
  12563. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  12564. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12565. ReductionIdScopeSpec, ReductionId,
  12566. UnresolvedReductions, RD))
  12567. return nullptr;
  12568. return OMPInReductionClause::Create(
  12569. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12570. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12571. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  12572. buildPreInits(Context, RD.ExprCaptures),
  12573. buildPostUpdate(*this, RD.ExprPostUpdates));
  12574. }
  12575. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  12576. SourceLocation LinLoc) {
  12577. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  12578. LinKind == OMPC_LINEAR_unknown) {
  12579. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  12580. return true;
  12581. }
  12582. return false;
  12583. }
  12584. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  12585. OpenMPLinearClauseKind LinKind,
  12586. QualType Type) {
  12587. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  12588. // A variable must not have an incomplete type or a reference type.
  12589. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  12590. return true;
  12591. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  12592. !Type->isReferenceType()) {
  12593. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  12594. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  12595. return true;
  12596. }
  12597. Type = Type.getNonReferenceType();
  12598. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  12599. // A variable that is privatized must not have a const-qualified type
  12600. // unless it is of class type with a mutable member. This restriction does
  12601. // not apply to the firstprivate clause.
  12602. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  12603. return true;
  12604. // A list item must be of integral or pointer type.
  12605. Type = Type.getUnqualifiedType().getCanonicalType();
  12606. const auto *Ty = Type.getTypePtrOrNull();
  12607. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  12608. !Ty->isPointerType())) {
  12609. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  12610. if (D) {
  12611. bool IsDecl =
  12612. !VD ||
  12613. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12614. Diag(D->getLocation(),
  12615. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12616. << D;
  12617. }
  12618. return true;
  12619. }
  12620. return false;
  12621. }
  12622. OMPClause *Sema::ActOnOpenMPLinearClause(
  12623. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  12624. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  12625. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12626. SmallVector<Expr *, 8> Vars;
  12627. SmallVector<Expr *, 8> Privates;
  12628. SmallVector<Expr *, 8> Inits;
  12629. SmallVector<Decl *, 4> ExprCaptures;
  12630. SmallVector<Expr *, 4> ExprPostUpdates;
  12631. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  12632. LinKind = OMPC_LINEAR_val;
  12633. for (Expr *RefExpr : VarList) {
  12634. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12635. SourceLocation ELoc;
  12636. SourceRange ERange;
  12637. Expr *SimpleRefExpr = RefExpr;
  12638. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12639. if (Res.second) {
  12640. // It will be analyzed later.
  12641. Vars.push_back(RefExpr);
  12642. Privates.push_back(nullptr);
  12643. Inits.push_back(nullptr);
  12644. }
  12645. ValueDecl *D = Res.first;
  12646. if (!D)
  12647. continue;
  12648. QualType Type = D->getType();
  12649. auto *VD = dyn_cast<VarDecl>(D);
  12650. // OpenMP [2.14.3.7, linear clause]
  12651. // A list-item cannot appear in more than one linear clause.
  12652. // A list-item that appears in a linear clause cannot appear in any
  12653. // other data-sharing attribute clause.
  12654. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12655. if (DVar.RefExpr) {
  12656. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  12657. << getOpenMPClauseName(OMPC_linear);
  12658. reportOriginalDsa(*this, DSAStack, D, DVar);
  12659. continue;
  12660. }
  12661. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  12662. continue;
  12663. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12664. // Build private copy of original var.
  12665. VarDecl *Private =
  12666. buildVarDecl(*this, ELoc, Type, D->getName(),
  12667. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12668. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12669. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  12670. // Build var to save initial value.
  12671. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  12672. Expr *InitExpr;
  12673. DeclRefExpr *Ref = nullptr;
  12674. if (!VD && !CurContext->isDependentContext()) {
  12675. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  12676. if (!isOpenMPCapturedDecl(D)) {
  12677. ExprCaptures.push_back(Ref->getDecl());
  12678. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12679. ExprResult RefRes = DefaultLvalueConversion(Ref);
  12680. if (!RefRes.isUsable())
  12681. continue;
  12682. ExprResult PostUpdateRes =
  12683. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  12684. SimpleRefExpr, RefRes.get());
  12685. if (!PostUpdateRes.isUsable())
  12686. continue;
  12687. ExprPostUpdates.push_back(
  12688. IgnoredValueConversions(PostUpdateRes.get()).get());
  12689. }
  12690. }
  12691. }
  12692. if (LinKind == OMPC_LINEAR_uval)
  12693. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  12694. else
  12695. InitExpr = VD ? SimpleRefExpr : Ref;
  12696. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  12697. /*DirectInit=*/false);
  12698. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  12699. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  12700. Vars.push_back((VD || CurContext->isDependentContext())
  12701. ? RefExpr->IgnoreParens()
  12702. : Ref);
  12703. Privates.push_back(PrivateRef);
  12704. Inits.push_back(InitRef);
  12705. }
  12706. if (Vars.empty())
  12707. return nullptr;
  12708. Expr *StepExpr = Step;
  12709. Expr *CalcStepExpr = nullptr;
  12710. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  12711. !Step->isInstantiationDependent() &&
  12712. !Step->containsUnexpandedParameterPack()) {
  12713. SourceLocation StepLoc = Step->getBeginLoc();
  12714. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  12715. if (Val.isInvalid())
  12716. return nullptr;
  12717. StepExpr = Val.get();
  12718. // Build var to save the step value.
  12719. VarDecl *SaveVar =
  12720. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  12721. ExprResult SaveRef =
  12722. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  12723. ExprResult CalcStep =
  12724. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  12725. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  12726. // Warn about zero linear step (it would be probably better specified as
  12727. // making corresponding variables 'const').
  12728. llvm::APSInt Result;
  12729. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  12730. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  12731. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  12732. << (Vars.size() > 1);
  12733. if (!IsConstant && CalcStep.isUsable()) {
  12734. // Calculate the step beforehand instead of doing this on each iteration.
  12735. // (This is not used if the number of iterations may be kfold-ed).
  12736. CalcStepExpr = CalcStep.get();
  12737. }
  12738. }
  12739. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  12740. ColonLoc, EndLoc, Vars, Privates, Inits,
  12741. StepExpr, CalcStepExpr,
  12742. buildPreInits(Context, ExprCaptures),
  12743. buildPostUpdate(*this, ExprPostUpdates));
  12744. }
  12745. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  12746. Expr *NumIterations, Sema &SemaRef,
  12747. Scope *S, DSAStackTy *Stack) {
  12748. // Walk the vars and build update/final expressions for the CodeGen.
  12749. SmallVector<Expr *, 8> Updates;
  12750. SmallVector<Expr *, 8> Finals;
  12751. SmallVector<Expr *, 8> UsedExprs;
  12752. Expr *Step = Clause.getStep();
  12753. Expr *CalcStep = Clause.getCalcStep();
  12754. // OpenMP [2.14.3.7, linear clause]
  12755. // If linear-step is not specified it is assumed to be 1.
  12756. if (!Step)
  12757. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  12758. else if (CalcStep)
  12759. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  12760. bool HasErrors = false;
  12761. auto CurInit = Clause.inits().begin();
  12762. auto CurPrivate = Clause.privates().begin();
  12763. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  12764. for (Expr *RefExpr : Clause.varlists()) {
  12765. SourceLocation ELoc;
  12766. SourceRange ERange;
  12767. Expr *SimpleRefExpr = RefExpr;
  12768. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  12769. ValueDecl *D = Res.first;
  12770. if (Res.second || !D) {
  12771. Updates.push_back(nullptr);
  12772. Finals.push_back(nullptr);
  12773. HasErrors = true;
  12774. continue;
  12775. }
  12776. auto &&Info = Stack->isLoopControlVariable(D);
  12777. // OpenMP [2.15.11, distribute simd Construct]
  12778. // A list item may not appear in a linear clause, unless it is the loop
  12779. // iteration variable.
  12780. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  12781. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  12782. SemaRef.Diag(ELoc,
  12783. diag::err_omp_linear_distribute_var_non_loop_iteration);
  12784. Updates.push_back(nullptr);
  12785. Finals.push_back(nullptr);
  12786. HasErrors = true;
  12787. continue;
  12788. }
  12789. Expr *InitExpr = *CurInit;
  12790. // Build privatized reference to the current linear var.
  12791. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  12792. Expr *CapturedRef;
  12793. if (LinKind == OMPC_LINEAR_uval)
  12794. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  12795. else
  12796. CapturedRef =
  12797. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  12798. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  12799. /*RefersToCapture=*/true);
  12800. // Build update: Var = InitExpr + IV * Step
  12801. ExprResult Update;
  12802. if (!Info.first)
  12803. Update = buildCounterUpdate(
  12804. SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
  12805. /*Subtract=*/false, /*IsNonRectangularLB=*/false);
  12806. else
  12807. Update = *CurPrivate;
  12808. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  12809. /*DiscardedValue*/ false);
  12810. // Build final: Var = InitExpr + NumIterations * Step
  12811. ExprResult Final;
  12812. if (!Info.first)
  12813. Final =
  12814. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  12815. InitExpr, NumIterations, Step, /*Subtract=*/false,
  12816. /*IsNonRectangularLB=*/false);
  12817. else
  12818. Final = *CurPrivate;
  12819. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  12820. /*DiscardedValue*/ false);
  12821. if (!Update.isUsable() || !Final.isUsable()) {
  12822. Updates.push_back(nullptr);
  12823. Finals.push_back(nullptr);
  12824. UsedExprs.push_back(nullptr);
  12825. HasErrors = true;
  12826. } else {
  12827. Updates.push_back(Update.get());
  12828. Finals.push_back(Final.get());
  12829. if (!Info.first)
  12830. UsedExprs.push_back(SimpleRefExpr);
  12831. }
  12832. ++CurInit;
  12833. ++CurPrivate;
  12834. }
  12835. if (Expr *S = Clause.getStep())
  12836. UsedExprs.push_back(S);
  12837. // Fill the remaining part with the nullptr.
  12838. UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
  12839. Clause.setUpdates(Updates);
  12840. Clause.setFinals(Finals);
  12841. Clause.setUsedExprs(UsedExprs);
  12842. return HasErrors;
  12843. }
  12844. OMPClause *Sema::ActOnOpenMPAlignedClause(
  12845. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  12846. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12847. SmallVector<Expr *, 8> Vars;
  12848. for (Expr *RefExpr : VarList) {
  12849. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12850. SourceLocation ELoc;
  12851. SourceRange ERange;
  12852. Expr *SimpleRefExpr = RefExpr;
  12853. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12854. if (Res.second) {
  12855. // It will be analyzed later.
  12856. Vars.push_back(RefExpr);
  12857. }
  12858. ValueDecl *D = Res.first;
  12859. if (!D)
  12860. continue;
  12861. QualType QType = D->getType();
  12862. auto *VD = dyn_cast<VarDecl>(D);
  12863. // OpenMP [2.8.1, simd construct, Restrictions]
  12864. // The type of list items appearing in the aligned clause must be
  12865. // array, pointer, reference to array, or reference to pointer.
  12866. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12867. const Type *Ty = QType.getTypePtrOrNull();
  12868. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  12869. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  12870. << QType << getLangOpts().CPlusPlus << ERange;
  12871. bool IsDecl =
  12872. !VD ||
  12873. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12874. Diag(D->getLocation(),
  12875. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12876. << D;
  12877. continue;
  12878. }
  12879. // OpenMP [2.8.1, simd construct, Restrictions]
  12880. // A list-item cannot appear in more than one aligned clause.
  12881. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  12882. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  12883. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  12884. << getOpenMPClauseName(OMPC_aligned);
  12885. continue;
  12886. }
  12887. DeclRefExpr *Ref = nullptr;
  12888. if (!VD && isOpenMPCapturedDecl(D))
  12889. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12890. Vars.push_back(DefaultFunctionArrayConversion(
  12891. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  12892. .get());
  12893. }
  12894. // OpenMP [2.8.1, simd construct, Description]
  12895. // The parameter of the aligned clause, alignment, must be a constant
  12896. // positive integer expression.
  12897. // If no optional parameter is specified, implementation-defined default
  12898. // alignments for SIMD instructions on the target platforms are assumed.
  12899. if (Alignment != nullptr) {
  12900. ExprResult AlignResult =
  12901. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  12902. if (AlignResult.isInvalid())
  12903. return nullptr;
  12904. Alignment = AlignResult.get();
  12905. }
  12906. if (Vars.empty())
  12907. return nullptr;
  12908. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  12909. EndLoc, Vars, Alignment);
  12910. }
  12911. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  12912. SourceLocation StartLoc,
  12913. SourceLocation LParenLoc,
  12914. SourceLocation EndLoc) {
  12915. SmallVector<Expr *, 8> Vars;
  12916. SmallVector<Expr *, 8> SrcExprs;
  12917. SmallVector<Expr *, 8> DstExprs;
  12918. SmallVector<Expr *, 8> AssignmentOps;
  12919. for (Expr *RefExpr : VarList) {
  12920. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  12921. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  12922. // It will be analyzed later.
  12923. Vars.push_back(RefExpr);
  12924. SrcExprs.push_back(nullptr);
  12925. DstExprs.push_back(nullptr);
  12926. AssignmentOps.push_back(nullptr);
  12927. continue;
  12928. }
  12929. SourceLocation ELoc = RefExpr->getExprLoc();
  12930. // OpenMP [2.1, C/C++]
  12931. // A list item is a variable name.
  12932. // OpenMP [2.14.4.1, Restrictions, p.1]
  12933. // A list item that appears in a copyin clause must be threadprivate.
  12934. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  12935. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  12936. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  12937. << 0 << RefExpr->getSourceRange();
  12938. continue;
  12939. }
  12940. Decl *D = DE->getDecl();
  12941. auto *VD = cast<VarDecl>(D);
  12942. QualType Type = VD->getType();
  12943. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  12944. // It will be analyzed later.
  12945. Vars.push_back(DE);
  12946. SrcExprs.push_back(nullptr);
  12947. DstExprs.push_back(nullptr);
  12948. AssignmentOps.push_back(nullptr);
  12949. continue;
  12950. }
  12951. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  12952. // A list item that appears in a copyin clause must be threadprivate.
  12953. if (!DSAStack->isThreadPrivate(VD)) {
  12954. Diag(ELoc, diag::err_omp_required_access)
  12955. << getOpenMPClauseName(OMPC_copyin)
  12956. << getOpenMPDirectiveName(OMPD_threadprivate);
  12957. continue;
  12958. }
  12959. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  12960. // A variable of class type (or array thereof) that appears in a
  12961. // copyin clause requires an accessible, unambiguous copy assignment
  12962. // operator for the class type.
  12963. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  12964. VarDecl *SrcVD =
  12965. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  12966. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  12967. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  12968. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  12969. VarDecl *DstVD =
  12970. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  12971. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  12972. DeclRefExpr *PseudoDstExpr =
  12973. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  12974. // For arrays generate assignment operation for single element and replace
  12975. // it by the original array element in CodeGen.
  12976. ExprResult AssignmentOp =
  12977. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  12978. PseudoSrcExpr);
  12979. if (AssignmentOp.isInvalid())
  12980. continue;
  12981. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  12982. /*DiscardedValue*/ false);
  12983. if (AssignmentOp.isInvalid())
  12984. continue;
  12985. DSAStack->addDSA(VD, DE, OMPC_copyin);
  12986. Vars.push_back(DE);
  12987. SrcExprs.push_back(PseudoSrcExpr);
  12988. DstExprs.push_back(PseudoDstExpr);
  12989. AssignmentOps.push_back(AssignmentOp.get());
  12990. }
  12991. if (Vars.empty())
  12992. return nullptr;
  12993. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  12994. SrcExprs, DstExprs, AssignmentOps);
  12995. }
  12996. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  12997. SourceLocation StartLoc,
  12998. SourceLocation LParenLoc,
  12999. SourceLocation EndLoc) {
  13000. SmallVector<Expr *, 8> Vars;
  13001. SmallVector<Expr *, 8> SrcExprs;
  13002. SmallVector<Expr *, 8> DstExprs;
  13003. SmallVector<Expr *, 8> AssignmentOps;
  13004. for (Expr *RefExpr : VarList) {
  13005. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  13006. SourceLocation ELoc;
  13007. SourceRange ERange;
  13008. Expr *SimpleRefExpr = RefExpr;
  13009. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13010. if (Res.second) {
  13011. // It will be analyzed later.
  13012. Vars.push_back(RefExpr);
  13013. SrcExprs.push_back(nullptr);
  13014. DstExprs.push_back(nullptr);
  13015. AssignmentOps.push_back(nullptr);
  13016. }
  13017. ValueDecl *D = Res.first;
  13018. if (!D)
  13019. continue;
  13020. QualType Type = D->getType();
  13021. auto *VD = dyn_cast<VarDecl>(D);
  13022. // OpenMP [2.14.4.2, Restrictions, p.2]
  13023. // A list item that appears in a copyprivate clause may not appear in a
  13024. // private or firstprivate clause on the single construct.
  13025. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  13026. DSAStackTy::DSAVarData DVar =
  13027. DSAStack->getTopDSA(D, /*FromParent=*/false);
  13028. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  13029. DVar.RefExpr) {
  13030. Diag(ELoc, diag::err_omp_wrong_dsa)
  13031. << getOpenMPClauseName(DVar.CKind)
  13032. << getOpenMPClauseName(OMPC_copyprivate);
  13033. reportOriginalDsa(*this, DSAStack, D, DVar);
  13034. continue;
  13035. }
  13036. // OpenMP [2.11.4.2, Restrictions, p.1]
  13037. // All list items that appear in a copyprivate clause must be either
  13038. // threadprivate or private in the enclosing context.
  13039. if (DVar.CKind == OMPC_unknown) {
  13040. DVar = DSAStack->getImplicitDSA(D, false);
  13041. if (DVar.CKind == OMPC_shared) {
  13042. Diag(ELoc, diag::err_omp_required_access)
  13043. << getOpenMPClauseName(OMPC_copyprivate)
  13044. << "threadprivate or private in the enclosing context";
  13045. reportOriginalDsa(*this, DSAStack, D, DVar);
  13046. continue;
  13047. }
  13048. }
  13049. }
  13050. // Variably modified types are not supported.
  13051. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  13052. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  13053. << getOpenMPClauseName(OMPC_copyprivate) << Type
  13054. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  13055. bool IsDecl =
  13056. !VD ||
  13057. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  13058. Diag(D->getLocation(),
  13059. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  13060. << D;
  13061. continue;
  13062. }
  13063. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  13064. // A variable of class type (or array thereof) that appears in a
  13065. // copyin clause requires an accessible, unambiguous copy assignment
  13066. // operator for the class type.
  13067. Type = Context.getBaseElementType(Type.getNonReferenceType())
  13068. .getUnqualifiedType();
  13069. VarDecl *SrcVD =
  13070. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  13071. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13072. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  13073. VarDecl *DstVD =
  13074. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  13075. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13076. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  13077. ExprResult AssignmentOp = BuildBinOp(
  13078. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  13079. if (AssignmentOp.isInvalid())
  13080. continue;
  13081. AssignmentOp =
  13082. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  13083. if (AssignmentOp.isInvalid())
  13084. continue;
  13085. // No need to mark vars as copyprivate, they are already threadprivate or
  13086. // implicitly private.
  13087. assert(VD || isOpenMPCapturedDecl(D));
  13088. Vars.push_back(
  13089. VD ? RefExpr->IgnoreParens()
  13090. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  13091. SrcExprs.push_back(PseudoSrcExpr);
  13092. DstExprs.push_back(PseudoDstExpr);
  13093. AssignmentOps.push_back(AssignmentOp.get());
  13094. }
  13095. if (Vars.empty())
  13096. return nullptr;
  13097. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13098. Vars, SrcExprs, DstExprs, AssignmentOps);
  13099. }
  13100. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  13101. SourceLocation StartLoc,
  13102. SourceLocation LParenLoc,
  13103. SourceLocation EndLoc) {
  13104. if (VarList.empty())
  13105. return nullptr;
  13106. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  13107. }
  13108. OMPClause *
  13109. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  13110. SourceLocation DepLoc, SourceLocation ColonLoc,
  13111. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  13112. SourceLocation LParenLoc, SourceLocation EndLoc) {
  13113. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  13114. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  13115. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13116. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  13117. return nullptr;
  13118. }
  13119. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  13120. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  13121. DepKind == OMPC_DEPEND_sink)) {
  13122. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  13123. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13124. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  13125. /*Last=*/OMPC_DEPEND_unknown, Except)
  13126. << getOpenMPClauseName(OMPC_depend);
  13127. return nullptr;
  13128. }
  13129. SmallVector<Expr *, 8> Vars;
  13130. DSAStackTy::OperatorOffsetTy OpsOffs;
  13131. llvm::APSInt DepCounter(/*BitWidth=*/32);
  13132. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  13133. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  13134. if (const Expr *OrderedCountExpr =
  13135. DSAStack->getParentOrderedRegionParam().first) {
  13136. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  13137. TotalDepCount.setIsUnsigned(/*Val=*/true);
  13138. }
  13139. }
  13140. for (Expr *RefExpr : VarList) {
  13141. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  13142. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  13143. // It will be analyzed later.
  13144. Vars.push_back(RefExpr);
  13145. continue;
  13146. }
  13147. SourceLocation ELoc = RefExpr->getExprLoc();
  13148. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  13149. if (DepKind == OMPC_DEPEND_sink) {
  13150. if (DSAStack->getParentOrderedRegionParam().first &&
  13151. DepCounter >= TotalDepCount) {
  13152. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  13153. continue;
  13154. }
  13155. ++DepCounter;
  13156. // OpenMP [2.13.9, Summary]
  13157. // depend(dependence-type : vec), where dependence-type is:
  13158. // 'sink' and where vec is the iteration vector, which has the form:
  13159. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  13160. // where n is the value specified by the ordered clause in the loop
  13161. // directive, xi denotes the loop iteration variable of the i-th nested
  13162. // loop associated with the loop directive, and di is a constant
  13163. // non-negative integer.
  13164. if (CurContext->isDependentContext()) {
  13165. // It will be analyzed later.
  13166. Vars.push_back(RefExpr);
  13167. continue;
  13168. }
  13169. SimpleExpr = SimpleExpr->IgnoreImplicit();
  13170. OverloadedOperatorKind OOK = OO_None;
  13171. SourceLocation OOLoc;
  13172. Expr *LHS = SimpleExpr;
  13173. Expr *RHS = nullptr;
  13174. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  13175. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  13176. OOLoc = BO->getOperatorLoc();
  13177. LHS = BO->getLHS()->IgnoreParenImpCasts();
  13178. RHS = BO->getRHS()->IgnoreParenImpCasts();
  13179. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  13180. OOK = OCE->getOperator();
  13181. OOLoc = OCE->getOperatorLoc();
  13182. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13183. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  13184. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  13185. OOK = MCE->getMethodDecl()
  13186. ->getNameInfo()
  13187. .getName()
  13188. .getCXXOverloadedOperator();
  13189. OOLoc = MCE->getCallee()->getExprLoc();
  13190. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  13191. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13192. }
  13193. SourceLocation ELoc;
  13194. SourceRange ERange;
  13195. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  13196. if (Res.second) {
  13197. // It will be analyzed later.
  13198. Vars.push_back(RefExpr);
  13199. }
  13200. ValueDecl *D = Res.first;
  13201. if (!D)
  13202. continue;
  13203. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  13204. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  13205. continue;
  13206. }
  13207. if (RHS) {
  13208. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  13209. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  13210. if (RHSRes.isInvalid())
  13211. continue;
  13212. }
  13213. if (!CurContext->isDependentContext() &&
  13214. DSAStack->getParentOrderedRegionParam().first &&
  13215. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  13216. const ValueDecl *VD =
  13217. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  13218. if (VD)
  13219. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13220. << 1 << VD;
  13221. else
  13222. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  13223. continue;
  13224. }
  13225. OpsOffs.emplace_back(RHS, OOK);
  13226. } else {
  13227. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  13228. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  13229. (ASE &&
  13230. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  13231. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  13232. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13233. << RefExpr->getSourceRange();
  13234. continue;
  13235. }
  13236. ExprResult Res;
  13237. {
  13238. Sema::TentativeAnalysisScope Trap(*this);
  13239. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  13240. RefExpr->IgnoreParenImpCasts());
  13241. }
  13242. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  13243. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13244. << RefExpr->getSourceRange();
  13245. continue;
  13246. }
  13247. }
  13248. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  13249. }
  13250. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  13251. TotalDepCount > VarList.size() &&
  13252. DSAStack->getParentOrderedRegionParam().first &&
  13253. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  13254. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13255. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  13256. }
  13257. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  13258. Vars.empty())
  13259. return nullptr;
  13260. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13261. DepKind, DepLoc, ColonLoc, Vars,
  13262. TotalDepCount.getZExtValue());
  13263. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  13264. DSAStack->isParentOrderedRegion())
  13265. DSAStack->addDoacrossDependClause(C, OpsOffs);
  13266. return C;
  13267. }
  13268. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  13269. SourceLocation LParenLoc,
  13270. SourceLocation EndLoc) {
  13271. Expr *ValExpr = Device;
  13272. Stmt *HelperValStmt = nullptr;
  13273. // OpenMP [2.9.1, Restrictions]
  13274. // The device expression must evaluate to a non-negative integer value.
  13275. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  13276. /*StrictlyPositive=*/false))
  13277. return nullptr;
  13278. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13279. OpenMPDirectiveKind CaptureRegion =
  13280. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  13281. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13282. ValExpr = MakeFullExpr(ValExpr).get();
  13283. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13284. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13285. HelperValStmt = buildPreInits(Context, Captures);
  13286. }
  13287. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  13288. StartLoc, LParenLoc, EndLoc);
  13289. }
  13290. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  13291. DSAStackTy *Stack, QualType QTy,
  13292. bool FullCheck = true) {
  13293. NamedDecl *ND;
  13294. if (QTy->isIncompleteType(&ND)) {
  13295. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  13296. return false;
  13297. }
  13298. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  13299. !QTy.isTrivialType(SemaRef.Context))
  13300. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  13301. return true;
  13302. }
  13303. /// Return true if it can be proven that the provided array expression
  13304. /// (array section or array subscript) does NOT specify the whole size of the
  13305. /// array whose base type is \a BaseQTy.
  13306. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  13307. const Expr *E,
  13308. QualType BaseQTy) {
  13309. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13310. // If this is an array subscript, it refers to the whole size if the size of
  13311. // the dimension is constant and equals 1. Also, an array section assumes the
  13312. // format of an array subscript if no colon is used.
  13313. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  13314. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13315. return ATy->getSize().getSExtValue() != 1;
  13316. // Size can't be evaluated statically.
  13317. return false;
  13318. }
  13319. assert(OASE && "Expecting array section if not an array subscript.");
  13320. const Expr *LowerBound = OASE->getLowerBound();
  13321. const Expr *Length = OASE->getLength();
  13322. // If there is a lower bound that does not evaluates to zero, we are not
  13323. // covering the whole dimension.
  13324. if (LowerBound) {
  13325. Expr::EvalResult Result;
  13326. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13327. return false; // Can't get the integer value as a constant.
  13328. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  13329. if (ConstLowerBound.getSExtValue())
  13330. return true;
  13331. }
  13332. // If we don't have a length we covering the whole dimension.
  13333. if (!Length)
  13334. return false;
  13335. // If the base is a pointer, we don't have a way to get the size of the
  13336. // pointee.
  13337. if (BaseQTy->isPointerType())
  13338. return false;
  13339. // We can only check if the length is the same as the size of the dimension
  13340. // if we have a constant array.
  13341. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  13342. if (!CATy)
  13343. return false;
  13344. Expr::EvalResult Result;
  13345. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13346. return false; // Can't get the integer value as a constant.
  13347. llvm::APSInt ConstLength = Result.Val.getInt();
  13348. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  13349. }
  13350. // Return true if it can be proven that the provided array expression (array
  13351. // section or array subscript) does NOT specify a single element of the array
  13352. // whose base type is \a BaseQTy.
  13353. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  13354. const Expr *E,
  13355. QualType BaseQTy) {
  13356. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13357. // An array subscript always refer to a single element. Also, an array section
  13358. // assumes the format of an array subscript if no colon is used.
  13359. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  13360. return false;
  13361. assert(OASE && "Expecting array section if not an array subscript.");
  13362. const Expr *Length = OASE->getLength();
  13363. // If we don't have a length we have to check if the array has unitary size
  13364. // for this dimension. Also, we should always expect a length if the base type
  13365. // is pointer.
  13366. if (!Length) {
  13367. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13368. return ATy->getSize().getSExtValue() != 1;
  13369. // We cannot assume anything.
  13370. return false;
  13371. }
  13372. // Check if the length evaluates to 1.
  13373. Expr::EvalResult Result;
  13374. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13375. return false; // Can't get the integer value as a constant.
  13376. llvm::APSInt ConstLength = Result.Val.getInt();
  13377. return ConstLength.getSExtValue() != 1;
  13378. }
  13379. // Return the expression of the base of the mappable expression or null if it
  13380. // cannot be determined and do all the necessary checks to see if the expression
  13381. // is valid as a standalone mappable expression. In the process, record all the
  13382. // components of the expression.
  13383. static const Expr *checkMapClauseExpressionBase(
  13384. Sema &SemaRef, Expr *E,
  13385. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  13386. OpenMPClauseKind CKind, bool NoDiagnose) {
  13387. SourceLocation ELoc = E->getExprLoc();
  13388. SourceRange ERange = E->getSourceRange();
  13389. // The base of elements of list in a map clause have to be either:
  13390. // - a reference to variable or field.
  13391. // - a member expression.
  13392. // - an array expression.
  13393. //
  13394. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  13395. // reference to 'r'.
  13396. //
  13397. // If we have:
  13398. //
  13399. // struct SS {
  13400. // Bla S;
  13401. // foo() {
  13402. // #pragma omp target map (S.Arr[:12]);
  13403. // }
  13404. // }
  13405. //
  13406. // We want to retrieve the member expression 'this->S';
  13407. const Expr *RelevantExpr = nullptr;
  13408. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  13409. // If a list item is an array section, it must specify contiguous storage.
  13410. //
  13411. // For this restriction it is sufficient that we make sure only references
  13412. // to variables or fields and array expressions, and that no array sections
  13413. // exist except in the rightmost expression (unless they cover the whole
  13414. // dimension of the array). E.g. these would be invalid:
  13415. //
  13416. // r.ArrS[3:5].Arr[6:7]
  13417. //
  13418. // r.ArrS[3:5].x
  13419. //
  13420. // but these would be valid:
  13421. // r.ArrS[3].Arr[6:7]
  13422. //
  13423. // r.ArrS[3].x
  13424. bool AllowUnitySizeArraySection = true;
  13425. bool AllowWholeSizeArraySection = true;
  13426. while (!RelevantExpr) {
  13427. E = E->IgnoreParenImpCasts();
  13428. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  13429. if (!isa<VarDecl>(CurE->getDecl()))
  13430. return nullptr;
  13431. RelevantExpr = CurE;
  13432. // If we got a reference to a declaration, we should not expect any array
  13433. // section before that.
  13434. AllowUnitySizeArraySection = false;
  13435. AllowWholeSizeArraySection = false;
  13436. // Record the component.
  13437. CurComponents.emplace_back(CurE, CurE->getDecl());
  13438. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  13439. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  13440. if (isa<CXXThisExpr>(BaseE))
  13441. // We found a base expression: this->Val.
  13442. RelevantExpr = CurE;
  13443. else
  13444. E = BaseE;
  13445. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  13446. if (!NoDiagnose) {
  13447. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  13448. << CurE->getSourceRange();
  13449. return nullptr;
  13450. }
  13451. if (RelevantExpr)
  13452. return nullptr;
  13453. continue;
  13454. }
  13455. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  13456. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  13457. // A bit-field cannot appear in a map clause.
  13458. //
  13459. if (FD->isBitField()) {
  13460. if (!NoDiagnose) {
  13461. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  13462. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  13463. return nullptr;
  13464. }
  13465. if (RelevantExpr)
  13466. return nullptr;
  13467. continue;
  13468. }
  13469. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13470. // If the type of a list item is a reference to a type T then the type
  13471. // will be considered to be T for all purposes of this clause.
  13472. QualType CurType = BaseE->getType().getNonReferenceType();
  13473. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  13474. // A list item cannot be a variable that is a member of a structure with
  13475. // a union type.
  13476. //
  13477. if (CurType->isUnionType()) {
  13478. if (!NoDiagnose) {
  13479. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  13480. << CurE->getSourceRange();
  13481. return nullptr;
  13482. }
  13483. continue;
  13484. }
  13485. // If we got a member expression, we should not expect any array section
  13486. // before that:
  13487. //
  13488. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  13489. // If a list item is an element of a structure, only the rightmost symbol
  13490. // of the variable reference can be an array section.
  13491. //
  13492. AllowUnitySizeArraySection = false;
  13493. AllowWholeSizeArraySection = false;
  13494. // Record the component.
  13495. CurComponents.emplace_back(CurE, FD);
  13496. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  13497. E = CurE->getBase()->IgnoreParenImpCasts();
  13498. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  13499. if (!NoDiagnose) {
  13500. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13501. << 0 << CurE->getSourceRange();
  13502. return nullptr;
  13503. }
  13504. continue;
  13505. }
  13506. // If we got an array subscript that express the whole dimension we
  13507. // can have any array expressions before. If it only expressing part of
  13508. // the dimension, we can only have unitary-size array expressions.
  13509. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  13510. E->getType()))
  13511. AllowWholeSizeArraySection = false;
  13512. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13513. Expr::EvalResult Result;
  13514. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  13515. if (!Result.Val.getInt().isNullValue()) {
  13516. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13517. diag::err_omp_invalid_map_this_expr);
  13518. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13519. diag::note_omp_invalid_subscript_on_this_ptr_map);
  13520. }
  13521. }
  13522. RelevantExpr = TE;
  13523. }
  13524. // Record the component - we don't have any declaration associated.
  13525. CurComponents.emplace_back(CurE, nullptr);
  13526. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  13527. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  13528. E = CurE->getBase()->IgnoreParenImpCasts();
  13529. QualType CurType =
  13530. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13531. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13532. // If the type of a list item is a reference to a type T then the type
  13533. // will be considered to be T for all purposes of this clause.
  13534. if (CurType->isReferenceType())
  13535. CurType = CurType->getPointeeType();
  13536. bool IsPointer = CurType->isAnyPointerType();
  13537. if (!IsPointer && !CurType->isArrayType()) {
  13538. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13539. << 0 << CurE->getSourceRange();
  13540. return nullptr;
  13541. }
  13542. bool NotWhole =
  13543. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  13544. bool NotUnity =
  13545. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  13546. if (AllowWholeSizeArraySection) {
  13547. // Any array section is currently allowed. Allowing a whole size array
  13548. // section implies allowing a unity array section as well.
  13549. //
  13550. // If this array section refers to the whole dimension we can still
  13551. // accept other array sections before this one, except if the base is a
  13552. // pointer. Otherwise, only unitary sections are accepted.
  13553. if (NotWhole || IsPointer)
  13554. AllowWholeSizeArraySection = false;
  13555. } else if (AllowUnitySizeArraySection && NotUnity) {
  13556. // A unity or whole array section is not allowed and that is not
  13557. // compatible with the properties of the current array section.
  13558. SemaRef.Diag(
  13559. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  13560. << CurE->getSourceRange();
  13561. return nullptr;
  13562. }
  13563. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13564. Expr::EvalResult ResultR;
  13565. Expr::EvalResult ResultL;
  13566. if (CurE->getLength()->EvaluateAsInt(ResultR,
  13567. SemaRef.getASTContext())) {
  13568. if (!ResultR.Val.getInt().isOneValue()) {
  13569. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13570. diag::err_omp_invalid_map_this_expr);
  13571. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13572. diag::note_omp_invalid_length_on_this_ptr_mapping);
  13573. }
  13574. }
  13575. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  13576. ResultL, SemaRef.getASTContext())) {
  13577. if (!ResultL.Val.getInt().isNullValue()) {
  13578. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13579. diag::err_omp_invalid_map_this_expr);
  13580. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13581. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  13582. }
  13583. }
  13584. RelevantExpr = TE;
  13585. }
  13586. // Record the component - we don't have any declaration associated.
  13587. CurComponents.emplace_back(CurE, nullptr);
  13588. } else {
  13589. if (!NoDiagnose) {
  13590. // If nothing else worked, this is not a valid map clause expression.
  13591. SemaRef.Diag(
  13592. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  13593. << ERange;
  13594. }
  13595. return nullptr;
  13596. }
  13597. }
  13598. return RelevantExpr;
  13599. }
  13600. // Return true if expression E associated with value VD has conflicts with other
  13601. // map information.
  13602. static bool checkMapConflicts(
  13603. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  13604. bool CurrentRegionOnly,
  13605. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  13606. OpenMPClauseKind CKind) {
  13607. assert(VD && E);
  13608. SourceLocation ELoc = E->getExprLoc();
  13609. SourceRange ERange = E->getSourceRange();
  13610. // In order to easily check the conflicts we need to match each component of
  13611. // the expression under test with the components of the expressions that are
  13612. // already in the stack.
  13613. assert(!CurComponents.empty() && "Map clause expression with no components!");
  13614. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  13615. "Map clause expression with unexpected base!");
  13616. // Variables to help detecting enclosing problems in data environment nests.
  13617. bool IsEnclosedByDataEnvironmentExpr = false;
  13618. const Expr *EnclosingExpr = nullptr;
  13619. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  13620. VD, CurrentRegionOnly,
  13621. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  13622. ERange, CKind, &EnclosingExpr,
  13623. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  13624. StackComponents,
  13625. OpenMPClauseKind) {
  13626. assert(!StackComponents.empty() &&
  13627. "Map clause expression with no components!");
  13628. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  13629. "Map clause expression with unexpected base!");
  13630. (void)VD;
  13631. // The whole expression in the stack.
  13632. const Expr *RE = StackComponents.front().getAssociatedExpression();
  13633. // Expressions must start from the same base. Here we detect at which
  13634. // point both expressions diverge from each other and see if we can
  13635. // detect if the memory referred to both expressions is contiguous and
  13636. // do not overlap.
  13637. auto CI = CurComponents.rbegin();
  13638. auto CE = CurComponents.rend();
  13639. auto SI = StackComponents.rbegin();
  13640. auto SE = StackComponents.rend();
  13641. for (; CI != CE && SI != SE; ++CI, ++SI) {
  13642. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  13643. // At most one list item can be an array item derived from a given
  13644. // variable in map clauses of the same construct.
  13645. if (CurrentRegionOnly &&
  13646. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  13647. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  13648. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  13649. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  13650. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  13651. diag::err_omp_multiple_array_items_in_map_clause)
  13652. << CI->getAssociatedExpression()->getSourceRange();
  13653. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  13654. diag::note_used_here)
  13655. << SI->getAssociatedExpression()->getSourceRange();
  13656. return true;
  13657. }
  13658. // Do both expressions have the same kind?
  13659. if (CI->getAssociatedExpression()->getStmtClass() !=
  13660. SI->getAssociatedExpression()->getStmtClass())
  13661. break;
  13662. // Are we dealing with different variables/fields?
  13663. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  13664. break;
  13665. }
  13666. // Check if the extra components of the expressions in the enclosing
  13667. // data environment are redundant for the current base declaration.
  13668. // If they are, the maps completely overlap, which is legal.
  13669. for (; SI != SE; ++SI) {
  13670. QualType Type;
  13671. if (const auto *ASE =
  13672. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  13673. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  13674. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  13675. SI->getAssociatedExpression())) {
  13676. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  13677. Type =
  13678. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13679. }
  13680. if (Type.isNull() || Type->isAnyPointerType() ||
  13681. checkArrayExpressionDoesNotReferToWholeSize(
  13682. SemaRef, SI->getAssociatedExpression(), Type))
  13683. break;
  13684. }
  13685. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  13686. // List items of map clauses in the same construct must not share
  13687. // original storage.
  13688. //
  13689. // If the expressions are exactly the same or one is a subset of the
  13690. // other, it means they are sharing storage.
  13691. if (CI == CE && SI == SE) {
  13692. if (CurrentRegionOnly) {
  13693. if (CKind == OMPC_map) {
  13694. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  13695. } else {
  13696. assert(CKind == OMPC_to || CKind == OMPC_from);
  13697. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  13698. << ERange;
  13699. }
  13700. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13701. << RE->getSourceRange();
  13702. return true;
  13703. }
  13704. // If we find the same expression in the enclosing data environment,
  13705. // that is legal.
  13706. IsEnclosedByDataEnvironmentExpr = true;
  13707. return false;
  13708. }
  13709. QualType DerivedType =
  13710. std::prev(CI)->getAssociatedDeclaration()->getType();
  13711. SourceLocation DerivedLoc =
  13712. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  13713. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13714. // If the type of a list item is a reference to a type T then the type
  13715. // will be considered to be T for all purposes of this clause.
  13716. DerivedType = DerivedType.getNonReferenceType();
  13717. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  13718. // A variable for which the type is pointer and an array section
  13719. // derived from that variable must not appear as list items of map
  13720. // clauses of the same construct.
  13721. //
  13722. // Also, cover one of the cases in:
  13723. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  13724. // If any part of the original storage of a list item has corresponding
  13725. // storage in the device data environment, all of the original storage
  13726. // must have corresponding storage in the device data environment.
  13727. //
  13728. if (DerivedType->isAnyPointerType()) {
  13729. if (CI == CE || SI == SE) {
  13730. SemaRef.Diag(
  13731. DerivedLoc,
  13732. diag::err_omp_pointer_mapped_along_with_derived_section)
  13733. << DerivedLoc;
  13734. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13735. << RE->getSourceRange();
  13736. return true;
  13737. }
  13738. if (CI->getAssociatedExpression()->getStmtClass() !=
  13739. SI->getAssociatedExpression()->getStmtClass() ||
  13740. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  13741. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  13742. assert(CI != CE && SI != SE);
  13743. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  13744. << DerivedLoc;
  13745. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13746. << RE->getSourceRange();
  13747. return true;
  13748. }
  13749. }
  13750. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  13751. // List items of map clauses in the same construct must not share
  13752. // original storage.
  13753. //
  13754. // An expression is a subset of the other.
  13755. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  13756. if (CKind == OMPC_map) {
  13757. if (CI != CE || SI != SE) {
  13758. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  13759. // a pointer.
  13760. auto Begin =
  13761. CI != CE ? CurComponents.begin() : StackComponents.begin();
  13762. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  13763. auto It = Begin;
  13764. while (It != End && !It->getAssociatedDeclaration())
  13765. std::advance(It, 1);
  13766. assert(It != End &&
  13767. "Expected at least one component with the declaration.");
  13768. if (It != Begin && It->getAssociatedDeclaration()
  13769. ->getType()
  13770. .getCanonicalType()
  13771. ->isAnyPointerType()) {
  13772. IsEnclosedByDataEnvironmentExpr = false;
  13773. EnclosingExpr = nullptr;
  13774. return false;
  13775. }
  13776. }
  13777. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  13778. } else {
  13779. assert(CKind == OMPC_to || CKind == OMPC_from);
  13780. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  13781. << ERange;
  13782. }
  13783. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13784. << RE->getSourceRange();
  13785. return true;
  13786. }
  13787. // The current expression uses the same base as other expression in the
  13788. // data environment but does not contain it completely.
  13789. if (!CurrentRegionOnly && SI != SE)
  13790. EnclosingExpr = RE;
  13791. // The current expression is a subset of the expression in the data
  13792. // environment.
  13793. IsEnclosedByDataEnvironmentExpr |=
  13794. (!CurrentRegionOnly && CI != CE && SI == SE);
  13795. return false;
  13796. });
  13797. if (CurrentRegionOnly)
  13798. return FoundError;
  13799. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  13800. // If any part of the original storage of a list item has corresponding
  13801. // storage in the device data environment, all of the original storage must
  13802. // have corresponding storage in the device data environment.
  13803. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  13804. // If a list item is an element of a structure, and a different element of
  13805. // the structure has a corresponding list item in the device data environment
  13806. // prior to a task encountering the construct associated with the map clause,
  13807. // then the list item must also have a corresponding list item in the device
  13808. // data environment prior to the task encountering the construct.
  13809. //
  13810. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  13811. SemaRef.Diag(ELoc,
  13812. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  13813. << ERange;
  13814. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  13815. << EnclosingExpr->getSourceRange();
  13816. return true;
  13817. }
  13818. return FoundError;
  13819. }
  13820. // Look up the user-defined mapper given the mapper name and mapped type, and
  13821. // build a reference to it.
  13822. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  13823. CXXScopeSpec &MapperIdScopeSpec,
  13824. const DeclarationNameInfo &MapperId,
  13825. QualType Type,
  13826. Expr *UnresolvedMapper) {
  13827. if (MapperIdScopeSpec.isInvalid())
  13828. return ExprError();
  13829. // Get the actual type for the array type.
  13830. if (Type->isArrayType()) {
  13831. assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
  13832. Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
  13833. }
  13834. // Find all user-defined mappers with the given MapperId.
  13835. SmallVector<UnresolvedSet<8>, 4> Lookups;
  13836. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  13837. Lookup.suppressDiagnostics();
  13838. if (S) {
  13839. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  13840. NamedDecl *D = Lookup.getRepresentativeDecl();
  13841. while (S && !S->isDeclScope(D))
  13842. S = S->getParent();
  13843. if (S)
  13844. S = S->getParent();
  13845. Lookups.emplace_back();
  13846. Lookups.back().append(Lookup.begin(), Lookup.end());
  13847. Lookup.clear();
  13848. }
  13849. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  13850. // Extract the user-defined mappers with the given MapperId.
  13851. Lookups.push_back(UnresolvedSet<8>());
  13852. for (NamedDecl *D : ULE->decls()) {
  13853. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  13854. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  13855. Lookups.back().addDecl(DMD);
  13856. }
  13857. }
  13858. // Defer the lookup for dependent types. The results will be passed through
  13859. // UnresolvedMapper on instantiation.
  13860. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  13861. Type->isInstantiationDependentType() ||
  13862. Type->containsUnexpandedParameterPack() ||
  13863. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  13864. return !D->isInvalidDecl() &&
  13865. (D->getType()->isDependentType() ||
  13866. D->getType()->isInstantiationDependentType() ||
  13867. D->getType()->containsUnexpandedParameterPack());
  13868. })) {
  13869. UnresolvedSet<8> URS;
  13870. for (const UnresolvedSet<8> &Set : Lookups) {
  13871. if (Set.empty())
  13872. continue;
  13873. URS.append(Set.begin(), Set.end());
  13874. }
  13875. return UnresolvedLookupExpr::Create(
  13876. SemaRef.Context, /*NamingClass=*/nullptr,
  13877. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  13878. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  13879. }
  13880. SourceLocation Loc = MapperId.getLoc();
  13881. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13882. // The type must be of struct, union or class type in C and C++
  13883. if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
  13884. (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
  13885. SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
  13886. return ExprError();
  13887. }
  13888. // Perform argument dependent lookup.
  13889. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  13890. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  13891. // Return the first user-defined mapper with the desired type.
  13892. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13893. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  13894. if (!D->isInvalidDecl() &&
  13895. SemaRef.Context.hasSameType(D->getType(), Type))
  13896. return D;
  13897. return nullptr;
  13898. }))
  13899. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13900. // Find the first user-defined mapper with a type derived from the desired
  13901. // type.
  13902. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13903. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  13904. if (!D->isInvalidDecl() &&
  13905. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  13906. !Type.isMoreQualifiedThan(D->getType()))
  13907. return D;
  13908. return nullptr;
  13909. })) {
  13910. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  13911. /*DetectVirtual=*/false);
  13912. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  13913. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  13914. VD->getType().getUnqualifiedType()))) {
  13915. if (SemaRef.CheckBaseClassAccess(
  13916. Loc, VD->getType(), Type, Paths.front(),
  13917. /*DiagID=*/0) != Sema::AR_inaccessible) {
  13918. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13919. }
  13920. }
  13921. }
  13922. }
  13923. // Report error if a mapper is specified, but cannot be found.
  13924. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  13925. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  13926. << Type << MapperId.getName();
  13927. return ExprError();
  13928. }
  13929. return ExprEmpty();
  13930. }
  13931. namespace {
  13932. // Utility struct that gathers all the related lists associated with a mappable
  13933. // expression.
  13934. struct MappableVarListInfo {
  13935. // The list of expressions.
  13936. ArrayRef<Expr *> VarList;
  13937. // The list of processed expressions.
  13938. SmallVector<Expr *, 16> ProcessedVarList;
  13939. // The mappble components for each expression.
  13940. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  13941. // The base declaration of the variable.
  13942. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  13943. // The reference to the user-defined mapper associated with every expression.
  13944. SmallVector<Expr *, 16> UDMapperList;
  13945. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  13946. // We have a list of components and base declarations for each entry in the
  13947. // variable list.
  13948. VarComponents.reserve(VarList.size());
  13949. VarBaseDeclarations.reserve(VarList.size());
  13950. }
  13951. };
  13952. }
  13953. // Check the validity of the provided variable list for the provided clause kind
  13954. // \a CKind. In the check process the valid expressions, mappable expression
  13955. // components, variables, and user-defined mappers are extracted and used to
  13956. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  13957. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  13958. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  13959. static void checkMappableExpressionList(
  13960. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  13961. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  13962. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  13963. ArrayRef<Expr *> UnresolvedMappers,
  13964. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  13965. bool IsMapTypeImplicit = false) {
  13966. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  13967. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  13968. "Unexpected clause kind with mappable expressions!");
  13969. // If the identifier of user-defined mapper is not specified, it is "default".
  13970. // We do not change the actual name in this clause to distinguish whether a
  13971. // mapper is specified explicitly, i.e., it is not explicitly specified when
  13972. // MapperId.getName() is empty.
  13973. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  13974. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  13975. MapperId.setName(DeclNames.getIdentifier(
  13976. &SemaRef.getASTContext().Idents.get("default")));
  13977. }
  13978. // Iterators to find the current unresolved mapper expression.
  13979. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  13980. bool UpdateUMIt = false;
  13981. Expr *UnresolvedMapper = nullptr;
  13982. // Keep track of the mappable components and base declarations in this clause.
  13983. // Each entry in the list is going to have a list of components associated. We
  13984. // record each set of the components so that we can build the clause later on.
  13985. // In the end we should have the same amount of declarations and component
  13986. // lists.
  13987. for (Expr *RE : MVLI.VarList) {
  13988. assert(RE && "Null expr in omp to/from/map clause");
  13989. SourceLocation ELoc = RE->getExprLoc();
  13990. // Find the current unresolved mapper expression.
  13991. if (UpdateUMIt && UMIt != UMEnd) {
  13992. UMIt++;
  13993. assert(
  13994. UMIt != UMEnd &&
  13995. "Expect the size of UnresolvedMappers to match with that of VarList");
  13996. }
  13997. UpdateUMIt = true;
  13998. if (UMIt != UMEnd)
  13999. UnresolvedMapper = *UMIt;
  14000. const Expr *VE = RE->IgnoreParenLValueCasts();
  14001. if (VE->isValueDependent() || VE->isTypeDependent() ||
  14002. VE->isInstantiationDependent() ||
  14003. VE->containsUnexpandedParameterPack()) {
  14004. // Try to find the associated user-defined mapper.
  14005. ExprResult ER = buildUserDefinedMapperRef(
  14006. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14007. VE->getType().getCanonicalType(), UnresolvedMapper);
  14008. if (ER.isInvalid())
  14009. continue;
  14010. MVLI.UDMapperList.push_back(ER.get());
  14011. // We can only analyze this information once the missing information is
  14012. // resolved.
  14013. MVLI.ProcessedVarList.push_back(RE);
  14014. continue;
  14015. }
  14016. Expr *SimpleExpr = RE->IgnoreParenCasts();
  14017. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  14018. SemaRef.Diag(ELoc,
  14019. diag::err_omp_expected_named_var_member_or_array_expression)
  14020. << RE->getSourceRange();
  14021. continue;
  14022. }
  14023. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  14024. ValueDecl *CurDeclaration = nullptr;
  14025. // Obtain the array or member expression bases if required. Also, fill the
  14026. // components array with all the components identified in the process.
  14027. const Expr *BE = checkMapClauseExpressionBase(
  14028. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  14029. if (!BE)
  14030. continue;
  14031. assert(!CurComponents.empty() &&
  14032. "Invalid mappable expression information.");
  14033. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  14034. // Add store "this" pointer to class in DSAStackTy for future checking
  14035. DSAS->addMappedClassesQualTypes(TE->getType());
  14036. // Try to find the associated user-defined mapper.
  14037. ExprResult ER = buildUserDefinedMapperRef(
  14038. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14039. VE->getType().getCanonicalType(), UnresolvedMapper);
  14040. if (ER.isInvalid())
  14041. continue;
  14042. MVLI.UDMapperList.push_back(ER.get());
  14043. // Skip restriction checking for variable or field declarations
  14044. MVLI.ProcessedVarList.push_back(RE);
  14045. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14046. MVLI.VarComponents.back().append(CurComponents.begin(),
  14047. CurComponents.end());
  14048. MVLI.VarBaseDeclarations.push_back(nullptr);
  14049. continue;
  14050. }
  14051. // For the following checks, we rely on the base declaration which is
  14052. // expected to be associated with the last component. The declaration is
  14053. // expected to be a variable or a field (if 'this' is being mapped).
  14054. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  14055. assert(CurDeclaration && "Null decl on map clause.");
  14056. assert(
  14057. CurDeclaration->isCanonicalDecl() &&
  14058. "Expecting components to have associated only canonical declarations.");
  14059. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  14060. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  14061. assert((VD || FD) && "Only variables or fields are expected here!");
  14062. (void)FD;
  14063. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  14064. // threadprivate variables cannot appear in a map clause.
  14065. // OpenMP 4.5 [2.10.5, target update Construct]
  14066. // threadprivate variables cannot appear in a from clause.
  14067. if (VD && DSAS->isThreadPrivate(VD)) {
  14068. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14069. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  14070. << getOpenMPClauseName(CKind);
  14071. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  14072. continue;
  14073. }
  14074. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14075. // A list item cannot appear in both a map clause and a data-sharing
  14076. // attribute clause on the same construct.
  14077. // Check conflicts with other map clause expressions. We check the conflicts
  14078. // with the current construct separately from the enclosing data
  14079. // environment, because the restrictions are different. We only have to
  14080. // check conflicts across regions for the map clauses.
  14081. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14082. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  14083. break;
  14084. if (CKind == OMPC_map &&
  14085. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14086. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  14087. break;
  14088. // OpenMP 4.5 [2.10.5, target update Construct]
  14089. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  14090. // If the type of a list item is a reference to a type T then the type will
  14091. // be considered to be T for all purposes of this clause.
  14092. auto I = llvm::find_if(
  14093. CurComponents,
  14094. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  14095. return MC.getAssociatedDeclaration();
  14096. });
  14097. assert(I != CurComponents.end() && "Null decl on map clause.");
  14098. QualType Type =
  14099. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  14100. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  14101. // A list item in a to or from clause must have a mappable type.
  14102. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14103. // A list item must have a mappable type.
  14104. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  14105. DSAS, Type))
  14106. continue;
  14107. if (CKind == OMPC_map) {
  14108. // target enter data
  14109. // OpenMP [2.10.2, Restrictions, p. 99]
  14110. // A map-type must be specified in all map clauses and must be either
  14111. // to or alloc.
  14112. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  14113. if (DKind == OMPD_target_enter_data &&
  14114. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  14115. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14116. << (IsMapTypeImplicit ? 1 : 0)
  14117. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14118. << getOpenMPDirectiveName(DKind);
  14119. continue;
  14120. }
  14121. // target exit_data
  14122. // OpenMP [2.10.3, Restrictions, p. 102]
  14123. // A map-type must be specified in all map clauses and must be either
  14124. // from, release, or delete.
  14125. if (DKind == OMPD_target_exit_data &&
  14126. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  14127. MapType == OMPC_MAP_delete)) {
  14128. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14129. << (IsMapTypeImplicit ? 1 : 0)
  14130. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14131. << getOpenMPDirectiveName(DKind);
  14132. continue;
  14133. }
  14134. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  14135. // A list item cannot appear in both a map clause and a data-sharing
  14136. // attribute clause on the same construct
  14137. //
  14138. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  14139. // A list item cannot appear in both a map clause and a data-sharing
  14140. // attribute clause on the same construct unless the construct is a
  14141. // combined construct.
  14142. if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
  14143. isOpenMPTargetExecutionDirective(DKind)) ||
  14144. DKind == OMPD_target)) {
  14145. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14146. if (isOpenMPPrivate(DVar.CKind)) {
  14147. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  14148. << getOpenMPClauseName(DVar.CKind)
  14149. << getOpenMPClauseName(OMPC_map)
  14150. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  14151. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  14152. continue;
  14153. }
  14154. }
  14155. }
  14156. // Try to find the associated user-defined mapper.
  14157. ExprResult ER = buildUserDefinedMapperRef(
  14158. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14159. Type.getCanonicalType(), UnresolvedMapper);
  14160. if (ER.isInvalid())
  14161. continue;
  14162. MVLI.UDMapperList.push_back(ER.get());
  14163. // Save the current expression.
  14164. MVLI.ProcessedVarList.push_back(RE);
  14165. // Store the components in the stack so that they can be used to check
  14166. // against other clauses later on.
  14167. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  14168. /*WhereFoundClauseKind=*/OMPC_map);
  14169. // Save the components and declaration to create the clause. For purposes of
  14170. // the clause creation, any component list that has has base 'this' uses
  14171. // null as base declaration.
  14172. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14173. MVLI.VarComponents.back().append(CurComponents.begin(),
  14174. CurComponents.end());
  14175. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  14176. : CurDeclaration);
  14177. }
  14178. }
  14179. OMPClause *Sema::ActOnOpenMPMapClause(
  14180. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  14181. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  14182. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  14183. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  14184. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  14185. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  14186. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  14187. OMPC_MAP_MODIFIER_unknown,
  14188. OMPC_MAP_MODIFIER_unknown};
  14189. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  14190. // Process map-type-modifiers, flag errors for duplicate modifiers.
  14191. unsigned Count = 0;
  14192. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  14193. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  14194. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  14195. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  14196. continue;
  14197. }
  14198. assert(Count < OMPMapClause::NumberOfModifiers &&
  14199. "Modifiers exceed the allowed number of map type modifiers");
  14200. Modifiers[Count] = MapTypeModifiers[I];
  14201. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  14202. ++Count;
  14203. }
  14204. MappableVarListInfo MVLI(VarList);
  14205. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  14206. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  14207. MapType, IsMapTypeImplicit);
  14208. // We need to produce a map clause even if we don't have variables so that
  14209. // other diagnostics related with non-existing map clauses are accurate.
  14210. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  14211. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  14212. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  14213. MapperIdScopeSpec.getWithLocInContext(Context),
  14214. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  14215. }
  14216. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  14217. TypeResult ParsedType) {
  14218. assert(ParsedType.isUsable());
  14219. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  14220. if (ReductionType.isNull())
  14221. return QualType();
  14222. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  14223. // A type name in a declare reduction directive cannot be a function type, an
  14224. // array type, a reference type, or a type qualified with const, volatile or
  14225. // restrict.
  14226. if (ReductionType.hasQualifiers()) {
  14227. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  14228. return QualType();
  14229. }
  14230. if (ReductionType->isFunctionType()) {
  14231. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  14232. return QualType();
  14233. }
  14234. if (ReductionType->isReferenceType()) {
  14235. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  14236. return QualType();
  14237. }
  14238. if (ReductionType->isArrayType()) {
  14239. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  14240. return QualType();
  14241. }
  14242. return ReductionType;
  14243. }
  14244. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  14245. Scope *S, DeclContext *DC, DeclarationName Name,
  14246. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  14247. AccessSpecifier AS, Decl *PrevDeclInScope) {
  14248. SmallVector<Decl *, 8> Decls;
  14249. Decls.reserve(ReductionTypes.size());
  14250. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  14251. forRedeclarationInCurContext());
  14252. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  14253. // A reduction-identifier may not be re-declared in the current scope for the
  14254. // same type or for a type that is compatible according to the base language
  14255. // rules.
  14256. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14257. OMPDeclareReductionDecl *PrevDRD = nullptr;
  14258. bool InCompoundScope = true;
  14259. if (S != nullptr) {
  14260. // Find previous declaration with the same name not referenced in other
  14261. // declarations.
  14262. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14263. InCompoundScope =
  14264. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14265. LookupName(Lookup, S);
  14266. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14267. /*AllowInlineNamespace=*/false);
  14268. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  14269. LookupResult::Filter Filter = Lookup.makeFilter();
  14270. while (Filter.hasNext()) {
  14271. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  14272. if (InCompoundScope) {
  14273. auto I = UsedAsPrevious.find(PrevDecl);
  14274. if (I == UsedAsPrevious.end())
  14275. UsedAsPrevious[PrevDecl] = false;
  14276. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  14277. UsedAsPrevious[D] = true;
  14278. }
  14279. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14280. PrevDecl->getLocation();
  14281. }
  14282. Filter.done();
  14283. if (InCompoundScope) {
  14284. for (const auto &PrevData : UsedAsPrevious) {
  14285. if (!PrevData.second) {
  14286. PrevDRD = PrevData.first;
  14287. break;
  14288. }
  14289. }
  14290. }
  14291. } else if (PrevDeclInScope != nullptr) {
  14292. auto *PrevDRDInScope = PrevDRD =
  14293. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  14294. do {
  14295. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  14296. PrevDRDInScope->getLocation();
  14297. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  14298. } while (PrevDRDInScope != nullptr);
  14299. }
  14300. for (const auto &TyData : ReductionTypes) {
  14301. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  14302. bool Invalid = false;
  14303. if (I != PreviousRedeclTypes.end()) {
  14304. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  14305. << TyData.first;
  14306. Diag(I->second, diag::note_previous_definition);
  14307. Invalid = true;
  14308. }
  14309. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  14310. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  14311. Name, TyData.first, PrevDRD);
  14312. DC->addDecl(DRD);
  14313. DRD->setAccess(AS);
  14314. Decls.push_back(DRD);
  14315. if (Invalid)
  14316. DRD->setInvalidDecl();
  14317. else
  14318. PrevDRD = DRD;
  14319. }
  14320. return DeclGroupPtrTy::make(
  14321. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  14322. }
  14323. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  14324. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14325. // Enter new function scope.
  14326. PushFunctionScope();
  14327. setFunctionHasBranchProtectedScope();
  14328. getCurFunction()->setHasOMPDeclareReductionCombiner();
  14329. if (S != nullptr)
  14330. PushDeclContext(S, DRD);
  14331. else
  14332. CurContext = DRD;
  14333. PushExpressionEvaluationContext(
  14334. ExpressionEvaluationContext::PotentiallyEvaluated);
  14335. QualType ReductionType = DRD->getType();
  14336. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  14337. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  14338. // uses semantics of argument handles by value, but it should be passed by
  14339. // reference. C lang does not support references, so pass all parameters as
  14340. // pointers.
  14341. // Create 'T omp_in;' variable.
  14342. VarDecl *OmpInParm =
  14343. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  14344. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  14345. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  14346. // uses semantics of argument handles by value, but it should be passed by
  14347. // reference. C lang does not support references, so pass all parameters as
  14348. // pointers.
  14349. // Create 'T omp_out;' variable.
  14350. VarDecl *OmpOutParm =
  14351. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  14352. if (S != nullptr) {
  14353. PushOnScopeChains(OmpInParm, S);
  14354. PushOnScopeChains(OmpOutParm, S);
  14355. } else {
  14356. DRD->addDecl(OmpInParm);
  14357. DRD->addDecl(OmpOutParm);
  14358. }
  14359. Expr *InE =
  14360. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  14361. Expr *OutE =
  14362. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  14363. DRD->setCombinerData(InE, OutE);
  14364. }
  14365. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  14366. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14367. DiscardCleanupsInEvaluationContext();
  14368. PopExpressionEvaluationContext();
  14369. PopDeclContext();
  14370. PopFunctionScopeInfo();
  14371. if (Combiner != nullptr)
  14372. DRD->setCombiner(Combiner);
  14373. else
  14374. DRD->setInvalidDecl();
  14375. }
  14376. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  14377. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14378. // Enter new function scope.
  14379. PushFunctionScope();
  14380. setFunctionHasBranchProtectedScope();
  14381. if (S != nullptr)
  14382. PushDeclContext(S, DRD);
  14383. else
  14384. CurContext = DRD;
  14385. PushExpressionEvaluationContext(
  14386. ExpressionEvaluationContext::PotentiallyEvaluated);
  14387. QualType ReductionType = DRD->getType();
  14388. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  14389. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  14390. // uses semantics of argument handles by value, but it should be passed by
  14391. // reference. C lang does not support references, so pass all parameters as
  14392. // pointers.
  14393. // Create 'T omp_priv;' variable.
  14394. VarDecl *OmpPrivParm =
  14395. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  14396. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  14397. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  14398. // uses semantics of argument handles by value, but it should be passed by
  14399. // reference. C lang does not support references, so pass all parameters as
  14400. // pointers.
  14401. // Create 'T omp_orig;' variable.
  14402. VarDecl *OmpOrigParm =
  14403. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  14404. if (S != nullptr) {
  14405. PushOnScopeChains(OmpPrivParm, S);
  14406. PushOnScopeChains(OmpOrigParm, S);
  14407. } else {
  14408. DRD->addDecl(OmpPrivParm);
  14409. DRD->addDecl(OmpOrigParm);
  14410. }
  14411. Expr *OrigE =
  14412. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  14413. Expr *PrivE =
  14414. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  14415. DRD->setInitializerData(OrigE, PrivE);
  14416. return OmpPrivParm;
  14417. }
  14418. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  14419. VarDecl *OmpPrivParm) {
  14420. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14421. DiscardCleanupsInEvaluationContext();
  14422. PopExpressionEvaluationContext();
  14423. PopDeclContext();
  14424. PopFunctionScopeInfo();
  14425. if (Initializer != nullptr) {
  14426. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  14427. } else if (OmpPrivParm->hasInit()) {
  14428. DRD->setInitializer(OmpPrivParm->getInit(),
  14429. OmpPrivParm->isDirectInit()
  14430. ? OMPDeclareReductionDecl::DirectInit
  14431. : OMPDeclareReductionDecl::CopyInit);
  14432. } else {
  14433. DRD->setInvalidDecl();
  14434. }
  14435. }
  14436. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  14437. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  14438. for (Decl *D : DeclReductions.get()) {
  14439. if (IsValid) {
  14440. if (S)
  14441. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  14442. /*AddToContext=*/false);
  14443. } else {
  14444. D->setInvalidDecl();
  14445. }
  14446. }
  14447. return DeclReductions;
  14448. }
  14449. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  14450. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14451. QualType T = TInfo->getType();
  14452. if (D.isInvalidType())
  14453. return true;
  14454. if (getLangOpts().CPlusPlus) {
  14455. // Check that there are no default arguments (C++ only).
  14456. CheckExtraCXXDefaultArguments(D);
  14457. }
  14458. return CreateParsedType(T, TInfo);
  14459. }
  14460. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  14461. TypeResult ParsedType) {
  14462. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  14463. QualType MapperType = GetTypeFromParser(ParsedType.get());
  14464. assert(!MapperType.isNull() && "Expect valid mapper type");
  14465. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14466. // The type must be of struct, union or class type in C and C++
  14467. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  14468. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  14469. return QualType();
  14470. }
  14471. return MapperType;
  14472. }
  14473. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  14474. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  14475. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  14476. Decl *PrevDeclInScope) {
  14477. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  14478. forRedeclarationInCurContext());
  14479. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14480. // A mapper-identifier may not be redeclared in the current scope for the
  14481. // same type or for a type that is compatible according to the base language
  14482. // rules.
  14483. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14484. OMPDeclareMapperDecl *PrevDMD = nullptr;
  14485. bool InCompoundScope = true;
  14486. if (S != nullptr) {
  14487. // Find previous declaration with the same name not referenced in other
  14488. // declarations.
  14489. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14490. InCompoundScope =
  14491. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14492. LookupName(Lookup, S);
  14493. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14494. /*AllowInlineNamespace=*/false);
  14495. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  14496. LookupResult::Filter Filter = Lookup.makeFilter();
  14497. while (Filter.hasNext()) {
  14498. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  14499. if (InCompoundScope) {
  14500. auto I = UsedAsPrevious.find(PrevDecl);
  14501. if (I == UsedAsPrevious.end())
  14502. UsedAsPrevious[PrevDecl] = false;
  14503. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  14504. UsedAsPrevious[D] = true;
  14505. }
  14506. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14507. PrevDecl->getLocation();
  14508. }
  14509. Filter.done();
  14510. if (InCompoundScope) {
  14511. for (const auto &PrevData : UsedAsPrevious) {
  14512. if (!PrevData.second) {
  14513. PrevDMD = PrevData.first;
  14514. break;
  14515. }
  14516. }
  14517. }
  14518. } else if (PrevDeclInScope) {
  14519. auto *PrevDMDInScope = PrevDMD =
  14520. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  14521. do {
  14522. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  14523. PrevDMDInScope->getLocation();
  14524. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  14525. } while (PrevDMDInScope != nullptr);
  14526. }
  14527. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  14528. bool Invalid = false;
  14529. if (I != PreviousRedeclTypes.end()) {
  14530. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  14531. << MapperType << Name;
  14532. Diag(I->second, diag::note_previous_definition);
  14533. Invalid = true;
  14534. }
  14535. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  14536. MapperType, VN, PrevDMD);
  14537. DC->addDecl(DMD);
  14538. DMD->setAccess(AS);
  14539. if (Invalid)
  14540. DMD->setInvalidDecl();
  14541. // Enter new function scope.
  14542. PushFunctionScope();
  14543. setFunctionHasBranchProtectedScope();
  14544. CurContext = DMD;
  14545. return DMD;
  14546. }
  14547. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  14548. Scope *S,
  14549. QualType MapperType,
  14550. SourceLocation StartLoc,
  14551. DeclarationName VN) {
  14552. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  14553. if (S)
  14554. PushOnScopeChains(VD, S);
  14555. else
  14556. DMD->addDecl(VD);
  14557. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  14558. DMD->setMapperVarRef(MapperVarRefExpr);
  14559. }
  14560. Sema::DeclGroupPtrTy
  14561. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  14562. ArrayRef<OMPClause *> ClauseList) {
  14563. PopDeclContext();
  14564. PopFunctionScopeInfo();
  14565. if (D) {
  14566. if (S)
  14567. PushOnScopeChains(D, S, /*AddToContext=*/false);
  14568. D->CreateClauses(Context, ClauseList);
  14569. }
  14570. return DeclGroupPtrTy::make(DeclGroupRef(D));
  14571. }
  14572. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  14573. SourceLocation StartLoc,
  14574. SourceLocation LParenLoc,
  14575. SourceLocation EndLoc) {
  14576. Expr *ValExpr = NumTeams;
  14577. Stmt *HelperValStmt = nullptr;
  14578. // OpenMP [teams Constrcut, Restrictions]
  14579. // The num_teams expression must evaluate to a positive integer value.
  14580. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  14581. /*StrictlyPositive=*/true))
  14582. return nullptr;
  14583. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14584. OpenMPDirectiveKind CaptureRegion =
  14585. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  14586. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14587. ValExpr = MakeFullExpr(ValExpr).get();
  14588. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14589. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14590. HelperValStmt = buildPreInits(Context, Captures);
  14591. }
  14592. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  14593. StartLoc, LParenLoc, EndLoc);
  14594. }
  14595. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  14596. SourceLocation StartLoc,
  14597. SourceLocation LParenLoc,
  14598. SourceLocation EndLoc) {
  14599. Expr *ValExpr = ThreadLimit;
  14600. Stmt *HelperValStmt = nullptr;
  14601. // OpenMP [teams Constrcut, Restrictions]
  14602. // The thread_limit expression must evaluate to a positive integer value.
  14603. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  14604. /*StrictlyPositive=*/true))
  14605. return nullptr;
  14606. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14607. OpenMPDirectiveKind CaptureRegion =
  14608. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  14609. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14610. ValExpr = MakeFullExpr(ValExpr).get();
  14611. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14612. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14613. HelperValStmt = buildPreInits(Context, Captures);
  14614. }
  14615. return new (Context) OMPThreadLimitClause(
  14616. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  14617. }
  14618. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  14619. SourceLocation StartLoc,
  14620. SourceLocation LParenLoc,
  14621. SourceLocation EndLoc) {
  14622. Expr *ValExpr = Priority;
  14623. // OpenMP [2.9.1, task Constrcut]
  14624. // The priority-value is a non-negative numerical scalar expression.
  14625. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  14626. /*StrictlyPositive=*/false))
  14627. return nullptr;
  14628. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14629. }
  14630. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  14631. SourceLocation StartLoc,
  14632. SourceLocation LParenLoc,
  14633. SourceLocation EndLoc) {
  14634. Expr *ValExpr = Grainsize;
  14635. // OpenMP [2.9.2, taskloop Constrcut]
  14636. // The parameter of the grainsize clause must be a positive integer
  14637. // expression.
  14638. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  14639. /*StrictlyPositive=*/true))
  14640. return nullptr;
  14641. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14642. }
  14643. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  14644. SourceLocation StartLoc,
  14645. SourceLocation LParenLoc,
  14646. SourceLocation EndLoc) {
  14647. Expr *ValExpr = NumTasks;
  14648. // OpenMP [2.9.2, taskloop Constrcut]
  14649. // The parameter of the num_tasks clause must be a positive integer
  14650. // expression.
  14651. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  14652. /*StrictlyPositive=*/true))
  14653. return nullptr;
  14654. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14655. }
  14656. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  14657. SourceLocation LParenLoc,
  14658. SourceLocation EndLoc) {
  14659. // OpenMP [2.13.2, critical construct, Description]
  14660. // ... where hint-expression is an integer constant expression that evaluates
  14661. // to a valid lock hint.
  14662. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  14663. if (HintExpr.isInvalid())
  14664. return nullptr;
  14665. return new (Context)
  14666. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  14667. }
  14668. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  14669. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  14670. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  14671. SourceLocation EndLoc) {
  14672. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  14673. std::string Values;
  14674. Values += "'";
  14675. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  14676. Values += "'";
  14677. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  14678. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  14679. return nullptr;
  14680. }
  14681. Expr *ValExpr = ChunkSize;
  14682. Stmt *HelperValStmt = nullptr;
  14683. if (ChunkSize) {
  14684. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  14685. !ChunkSize->isInstantiationDependent() &&
  14686. !ChunkSize->containsUnexpandedParameterPack()) {
  14687. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  14688. ExprResult Val =
  14689. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  14690. if (Val.isInvalid())
  14691. return nullptr;
  14692. ValExpr = Val.get();
  14693. // OpenMP [2.7.1, Restrictions]
  14694. // chunk_size must be a loop invariant integer expression with a positive
  14695. // value.
  14696. llvm::APSInt Result;
  14697. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  14698. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  14699. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  14700. << "dist_schedule" << ChunkSize->getSourceRange();
  14701. return nullptr;
  14702. }
  14703. } else if (getOpenMPCaptureRegionForClause(
  14704. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  14705. OMPD_unknown &&
  14706. !CurContext->isDependentContext()) {
  14707. ValExpr = MakeFullExpr(ValExpr).get();
  14708. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14709. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14710. HelperValStmt = buildPreInits(Context, Captures);
  14711. }
  14712. }
  14713. }
  14714. return new (Context)
  14715. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  14716. Kind, ValExpr, HelperValStmt);
  14717. }
  14718. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  14719. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  14720. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  14721. SourceLocation KindLoc, SourceLocation EndLoc) {
  14722. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  14723. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  14724. std::string Value;
  14725. SourceLocation Loc;
  14726. Value += "'";
  14727. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  14728. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  14729. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  14730. Loc = MLoc;
  14731. } else {
  14732. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  14733. OMPC_DEFAULTMAP_scalar);
  14734. Loc = KindLoc;
  14735. }
  14736. Value += "'";
  14737. Diag(Loc, diag::err_omp_unexpected_clause_value)
  14738. << Value << getOpenMPClauseName(OMPC_defaultmap);
  14739. return nullptr;
  14740. }
  14741. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  14742. return new (Context)
  14743. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  14744. }
  14745. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  14746. DeclContext *CurLexicalContext = getCurLexicalContext();
  14747. if (!CurLexicalContext->isFileContext() &&
  14748. !CurLexicalContext->isExternCContext() &&
  14749. !CurLexicalContext->isExternCXXContext() &&
  14750. !isa<CXXRecordDecl>(CurLexicalContext) &&
  14751. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  14752. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  14753. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  14754. Diag(Loc, diag::err_omp_region_not_file_context);
  14755. return false;
  14756. }
  14757. ++DeclareTargetNestingLevel;
  14758. return true;
  14759. }
  14760. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  14761. assert(DeclareTargetNestingLevel > 0 &&
  14762. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  14763. --DeclareTargetNestingLevel;
  14764. }
  14765. NamedDecl *
  14766. Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
  14767. const DeclarationNameInfo &Id,
  14768. NamedDeclSetType &SameDirectiveDecls) {
  14769. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  14770. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  14771. if (Lookup.isAmbiguous())
  14772. return nullptr;
  14773. Lookup.suppressDiagnostics();
  14774. if (!Lookup.isSingleResult()) {
  14775. VarOrFuncDeclFilterCCC CCC(*this);
  14776. if (TypoCorrection Corrected =
  14777. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  14778. CTK_ErrorRecovery)) {
  14779. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  14780. << Id.getName());
  14781. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  14782. return nullptr;
  14783. }
  14784. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  14785. return nullptr;
  14786. }
  14787. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  14788. if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
  14789. !isa<FunctionTemplateDecl>(ND)) {
  14790. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  14791. return nullptr;
  14792. }
  14793. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  14794. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  14795. return ND;
  14796. }
  14797. void Sema::ActOnOpenMPDeclareTargetName(
  14798. NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
  14799. OMPDeclareTargetDeclAttr::DevTypeTy DT) {
  14800. assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  14801. isa<FunctionTemplateDecl>(ND)) &&
  14802. "Expected variable, function or function template.");
  14803. // Diagnose marking after use as it may lead to incorrect diagnosis and
  14804. // codegen.
  14805. if (LangOpts.OpenMP >= 50 &&
  14806. (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
  14807. Diag(Loc, diag::warn_omp_declare_target_after_first_use);
  14808. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  14809. OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
  14810. if (DevTy.hasValue() && *DevTy != DT) {
  14811. Diag(Loc, diag::err_omp_device_type_mismatch)
  14812. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
  14813. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
  14814. return;
  14815. }
  14816. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  14817. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
  14818. if (!Res) {
  14819. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
  14820. SourceRange(Loc, Loc));
  14821. ND->addAttr(A);
  14822. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14823. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  14824. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
  14825. } else if (*Res != MT) {
  14826. Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
  14827. }
  14828. }
  14829. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  14830. Sema &SemaRef, Decl *D) {
  14831. if (!D || !isa<VarDecl>(D))
  14832. return;
  14833. auto *VD = cast<VarDecl>(D);
  14834. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  14835. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  14836. if (SemaRef.LangOpts.OpenMP >= 50 &&
  14837. (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
  14838. SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
  14839. VD->hasGlobalStorage()) {
  14840. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  14841. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  14842. if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
  14843. // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
  14844. // If a lambda declaration and definition appears between a
  14845. // declare target directive and the matching end declare target
  14846. // directive, all variables that are captured by the lambda
  14847. // expression must also appear in a to clause.
  14848. SemaRef.Diag(VD->getLocation(),
  14849. diag::err_omp_lambda_capture_in_declare_target_not_to);
  14850. SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
  14851. << VD << 0 << SR;
  14852. return;
  14853. }
  14854. }
  14855. if (MapTy.hasValue())
  14856. return;
  14857. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  14858. SemaRef.Diag(SL, diag::note_used_here) << SR;
  14859. }
  14860. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  14861. Sema &SemaRef, DSAStackTy *Stack,
  14862. ValueDecl *VD) {
  14863. return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
  14864. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  14865. /*FullCheck=*/false);
  14866. }
  14867. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  14868. SourceLocation IdLoc) {
  14869. if (!D || D->isInvalidDecl())
  14870. return;
  14871. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  14872. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  14873. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14874. // Only global variables can be marked as declare target.
  14875. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  14876. !VD->isStaticDataMember())
  14877. return;
  14878. // 2.10.6: threadprivate variable cannot appear in a declare target
  14879. // directive.
  14880. if (DSAStack->isThreadPrivate(VD)) {
  14881. Diag(SL, diag::err_omp_threadprivate_in_target);
  14882. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  14883. return;
  14884. }
  14885. }
  14886. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  14887. D = FTD->getTemplatedDecl();
  14888. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14889. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  14890. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  14891. if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  14892. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  14893. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  14894. return;
  14895. }
  14896. // Mark the function as must be emitted for the device.
  14897. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  14898. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  14899. if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  14900. *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
  14901. checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
  14902. if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  14903. *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
  14904. checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
  14905. }
  14906. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  14907. // Problem if any with var declared with incomplete type will be reported
  14908. // as normal, so no need to check it here.
  14909. if ((E || !VD->getType()->isIncompleteType()) &&
  14910. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  14911. return;
  14912. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  14913. // Checking declaration inside declare target region.
  14914. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  14915. isa<FunctionTemplateDecl>(D)) {
  14916. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  14917. Context, OMPDeclareTargetDeclAttr::MT_To,
  14918. OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
  14919. D->addAttr(A);
  14920. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14921. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  14922. }
  14923. return;
  14924. }
  14925. }
  14926. if (!E)
  14927. return;
  14928. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  14929. }
  14930. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  14931. CXXScopeSpec &MapperIdScopeSpec,
  14932. DeclarationNameInfo &MapperId,
  14933. const OMPVarListLocTy &Locs,
  14934. ArrayRef<Expr *> UnresolvedMappers) {
  14935. MappableVarListInfo MVLI(VarList);
  14936. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  14937. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14938. if (MVLI.ProcessedVarList.empty())
  14939. return nullptr;
  14940. return OMPToClause::Create(
  14941. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14942. MVLI.VarComponents, MVLI.UDMapperList,
  14943. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14944. }
  14945. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  14946. CXXScopeSpec &MapperIdScopeSpec,
  14947. DeclarationNameInfo &MapperId,
  14948. const OMPVarListLocTy &Locs,
  14949. ArrayRef<Expr *> UnresolvedMappers) {
  14950. MappableVarListInfo MVLI(VarList);
  14951. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  14952. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14953. if (MVLI.ProcessedVarList.empty())
  14954. return nullptr;
  14955. return OMPFromClause::Create(
  14956. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14957. MVLI.VarComponents, MVLI.UDMapperList,
  14958. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14959. }
  14960. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  14961. const OMPVarListLocTy &Locs) {
  14962. MappableVarListInfo MVLI(VarList);
  14963. SmallVector<Expr *, 8> PrivateCopies;
  14964. SmallVector<Expr *, 8> Inits;
  14965. for (Expr *RefExpr : VarList) {
  14966. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  14967. SourceLocation ELoc;
  14968. SourceRange ERange;
  14969. Expr *SimpleRefExpr = RefExpr;
  14970. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  14971. if (Res.second) {
  14972. // It will be analyzed later.
  14973. MVLI.ProcessedVarList.push_back(RefExpr);
  14974. PrivateCopies.push_back(nullptr);
  14975. Inits.push_back(nullptr);
  14976. }
  14977. ValueDecl *D = Res.first;
  14978. if (!D)
  14979. continue;
  14980. QualType Type = D->getType();
  14981. Type = Type.getNonReferenceType().getUnqualifiedType();
  14982. auto *VD = dyn_cast<VarDecl>(D);
  14983. // Item should be a pointer or reference to pointer.
  14984. if (!Type->isPointerType()) {
  14985. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  14986. << 0 << RefExpr->getSourceRange();
  14987. continue;
  14988. }
  14989. // Build the private variable and the expression that refers to it.
  14990. auto VDPrivate =
  14991. buildVarDecl(*this, ELoc, Type, D->getName(),
  14992. D->hasAttrs() ? &D->getAttrs() : nullptr,
  14993. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  14994. if (VDPrivate->isInvalidDecl())
  14995. continue;
  14996. CurContext->addDecl(VDPrivate);
  14997. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  14998. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  14999. // Add temporary variable to initialize the private copy of the pointer.
  15000. VarDecl *VDInit =
  15001. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  15002. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  15003. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  15004. AddInitializerToDecl(VDPrivate,
  15005. DefaultLvalueConversion(VDInitRefExpr).get(),
  15006. /*DirectInit=*/false);
  15007. // If required, build a capture to implement the privatization initialized
  15008. // with the current list item value.
  15009. DeclRefExpr *Ref = nullptr;
  15010. if (!VD)
  15011. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  15012. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  15013. PrivateCopies.push_back(VDPrivateRefExpr);
  15014. Inits.push_back(VDInitRefExpr);
  15015. // We need to add a data sharing attribute for this variable to make sure it
  15016. // is correctly captured. A variable that shows up in a use_device_ptr has
  15017. // similar properties of a first private variable.
  15018. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  15019. // Create a mappable component for the list item. List items in this clause
  15020. // only need a component.
  15021. MVLI.VarBaseDeclarations.push_back(D);
  15022. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15023. MVLI.VarComponents.back().push_back(
  15024. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  15025. }
  15026. if (MVLI.ProcessedVarList.empty())
  15027. return nullptr;
  15028. return OMPUseDevicePtrClause::Create(
  15029. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  15030. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  15031. }
  15032. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  15033. const OMPVarListLocTy &Locs) {
  15034. MappableVarListInfo MVLI(VarList);
  15035. for (Expr *RefExpr : VarList) {
  15036. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  15037. SourceLocation ELoc;
  15038. SourceRange ERange;
  15039. Expr *SimpleRefExpr = RefExpr;
  15040. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15041. if (Res.second) {
  15042. // It will be analyzed later.
  15043. MVLI.ProcessedVarList.push_back(RefExpr);
  15044. }
  15045. ValueDecl *D = Res.first;
  15046. if (!D)
  15047. continue;
  15048. QualType Type = D->getType();
  15049. // item should be a pointer or array or reference to pointer or array
  15050. if (!Type.getNonReferenceType()->isPointerType() &&
  15051. !Type.getNonReferenceType()->isArrayType()) {
  15052. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  15053. << 0 << RefExpr->getSourceRange();
  15054. continue;
  15055. }
  15056. // Check if the declaration in the clause does not show up in any data
  15057. // sharing attribute.
  15058. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  15059. if (isOpenMPPrivate(DVar.CKind)) {
  15060. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  15061. << getOpenMPClauseName(DVar.CKind)
  15062. << getOpenMPClauseName(OMPC_is_device_ptr)
  15063. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  15064. reportOriginalDsa(*this, DSAStack, D, DVar);
  15065. continue;
  15066. }
  15067. const Expr *ConflictExpr;
  15068. if (DSAStack->checkMappableExprComponentListsForDecl(
  15069. D, /*CurrentRegionOnly=*/true,
  15070. [&ConflictExpr](
  15071. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  15072. OpenMPClauseKind) -> bool {
  15073. ConflictExpr = R.front().getAssociatedExpression();
  15074. return true;
  15075. })) {
  15076. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  15077. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  15078. << ConflictExpr->getSourceRange();
  15079. continue;
  15080. }
  15081. // Store the components in the stack so that they can be used to check
  15082. // against other clauses later on.
  15083. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  15084. DSAStack->addMappableExpressionComponents(
  15085. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  15086. // Record the expression we've just processed.
  15087. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  15088. // Create a mappable component for the list item. List items in this clause
  15089. // only need a component. We use a null declaration to signal fields in
  15090. // 'this'.
  15091. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  15092. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  15093. "Unexpected device pointer expression!");
  15094. MVLI.VarBaseDeclarations.push_back(
  15095. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  15096. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15097. MVLI.VarComponents.back().push_back(MC);
  15098. }
  15099. if (MVLI.ProcessedVarList.empty())
  15100. return nullptr;
  15101. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  15102. MVLI.VarBaseDeclarations,
  15103. MVLI.VarComponents);
  15104. }
  15105. OMPClause *Sema::ActOnOpenMPAllocateClause(
  15106. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  15107. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  15108. if (Allocator) {
  15109. // OpenMP [2.11.4 allocate Clause, Description]
  15110. // allocator is an expression of omp_allocator_handle_t type.
  15111. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  15112. return nullptr;
  15113. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  15114. if (AllocatorRes.isInvalid())
  15115. return nullptr;
  15116. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  15117. DSAStack->getOMPAllocatorHandleT(),
  15118. Sema::AA_Initializing,
  15119. /*AllowExplicit=*/true);
  15120. if (AllocatorRes.isInvalid())
  15121. return nullptr;
  15122. Allocator = AllocatorRes.get();
  15123. } else {
  15124. // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
  15125. // allocate clauses that appear on a target construct or on constructs in a
  15126. // target region must specify an allocator expression unless a requires
  15127. // directive with the dynamic_allocators clause is present in the same
  15128. // compilation unit.
  15129. if (LangOpts.OpenMPIsDevice &&
  15130. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  15131. targetDiag(StartLoc, diag::err_expected_allocator_expression);
  15132. }
  15133. // Analyze and build list of variables.
  15134. SmallVector<Expr *, 8> Vars;
  15135. for (Expr *RefExpr : VarList) {
  15136. assert(RefExpr && "NULL expr in OpenMP private clause.");
  15137. SourceLocation ELoc;
  15138. SourceRange ERange;
  15139. Expr *SimpleRefExpr = RefExpr;
  15140. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15141. if (Res.second) {
  15142. // It will be analyzed later.
  15143. Vars.push_back(RefExpr);
  15144. }
  15145. ValueDecl *D = Res.first;
  15146. if (!D)
  15147. continue;
  15148. auto *VD = dyn_cast<VarDecl>(D);
  15149. DeclRefExpr *Ref = nullptr;
  15150. if (!VD && !CurContext->isDependentContext())
  15151. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  15152. Vars.push_back((VD || CurContext->isDependentContext())
  15153. ? RefExpr->IgnoreParens()
  15154. : Ref);
  15155. }
  15156. if (Vars.empty())
  15157. return nullptr;
  15158. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  15159. ColonLoc, EndLoc, Vars);
  15160. }