SemaOpenMP.cpp 512 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// \brief This file implements semantic analysis for OpenMP directives and
  11. /// clauses.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/Basic/OpenMPKinds.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/ScopeInfo.h"
  29. #include "clang/Sema/SemaInternal.h"
  30. #include "llvm/ADT/PointerEmbeddedInt.h"
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // Stack of data-sharing attributes for variables
  34. //===----------------------------------------------------------------------===//
  35. static Expr *CheckMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind, bool NoDiagnose);
  39. namespace {
  40. /// \brief Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// \brief 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. /// \brief Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy final {
  54. public:
  55. struct DSAVarData final {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
  63. DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
  64. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  65. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  66. };
  67. typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
  68. OperatorOffsetTy;
  69. private:
  70. struct DSAInfo final {
  71. OpenMPClauseKind Attributes = OMPC_unknown;
  72. /// Pointer to a reference expression and a flag which shows that the
  73. /// variable is marked as lastprivate(true) or not (false).
  74. llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
  75. DeclRefExpr *PrivateCopy = nullptr;
  76. };
  77. typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
  78. typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
  79. typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
  80. typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
  81. /// Struct that associates a component with the clause kind where they are
  82. /// found.
  83. struct MappedExprComponentTy {
  84. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  85. OpenMPClauseKind Kind = OMPC_unknown;
  86. };
  87. typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
  88. MappedExprComponentsTy;
  89. typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
  90. CriticalsWithHintsTy;
  91. typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
  92. DoacrossDependMapTy;
  93. struct ReductionData {
  94. typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
  95. SourceRange ReductionRange;
  96. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  97. ReductionData() = default;
  98. void set(BinaryOperatorKind BO, SourceRange RR) {
  99. ReductionRange = RR;
  100. ReductionOp = BO;
  101. }
  102. void set(const Expr *RefExpr, SourceRange RR) {
  103. ReductionRange = RR;
  104. ReductionOp = RefExpr;
  105. }
  106. };
  107. typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
  108. struct SharingMapTy final {
  109. DeclSAMapTy SharingMap;
  110. DeclReductionMapTy ReductionMap;
  111. AlignedMapTy AlignedMap;
  112. MappedExprComponentsTy MappedExprComponents;
  113. LoopControlVariablesMapTy LCVMap;
  114. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  115. SourceLocation DefaultAttrLoc;
  116. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  117. SourceLocation DefaultMapAttrLoc;
  118. OpenMPDirectiveKind Directive = OMPD_unknown;
  119. DeclarationNameInfo DirectiveName;
  120. Scope *CurScope = nullptr;
  121. SourceLocation ConstructLoc;
  122. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  123. /// get the data (loop counters etc.) about enclosing loop-based construct.
  124. /// This data is required during codegen.
  125. DoacrossDependMapTy DoacrossDepends;
  126. /// \brief first argument (Expr *) contains optional argument of the
  127. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  128. /// clause, false otherwise.
  129. llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
  130. bool NowaitRegion = false;
  131. bool CancelRegion = false;
  132. unsigned AssociatedLoops = 1;
  133. SourceLocation InnerTeamsRegionLoc;
  134. /// Reference to the taskgroup task_reduction reference expression.
  135. Expr *TaskgroupReductionRef = nullptr;
  136. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  137. Scope *CurScope, SourceLocation Loc)
  138. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  139. ConstructLoc(Loc) {}
  140. SharingMapTy() = default;
  141. };
  142. typedef SmallVector<SharingMapTy, 4> StackTy;
  143. /// \brief Stack of used declaration and their data-sharing attributes.
  144. DeclSAMapTy Threadprivates;
  145. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  146. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  147. /// \brief true, if check for DSA must be from parent directive, false, if
  148. /// from current directive.
  149. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  150. Sema &SemaRef;
  151. bool ForceCapturing = false;
  152. CriticalsWithHintsTy Criticals;
  153. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  154. DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
  155. /// \brief Checks if the variable is a local for OpenMP region.
  156. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  157. bool isStackEmpty() const {
  158. return Stack.empty() ||
  159. Stack.back().second != CurrentNonCapturingFunctionScope ||
  160. Stack.back().first.empty();
  161. }
  162. public:
  163. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  164. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  165. OpenMPClauseKind getClauseParsingMode() const {
  166. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  167. return ClauseKindMode;
  168. }
  169. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  170. bool isForceVarCapturing() const { return ForceCapturing; }
  171. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  172. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  173. Scope *CurScope, SourceLocation Loc) {
  174. if (Stack.empty() ||
  175. Stack.back().second != CurrentNonCapturingFunctionScope)
  176. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  177. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  178. Stack.back().first.back().DefaultAttrLoc = Loc;
  179. }
  180. void pop() {
  181. assert(!Stack.back().first.empty() &&
  182. "Data-sharing attributes stack is empty!");
  183. Stack.back().first.pop_back();
  184. }
  185. /// Start new OpenMP region stack in new non-capturing function.
  186. void pushFunction() {
  187. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  188. assert(!isa<CapturingScopeInfo>(CurFnScope));
  189. CurrentNonCapturingFunctionScope = CurFnScope;
  190. }
  191. /// Pop region stack for non-capturing function.
  192. void popFunction(const FunctionScopeInfo *OldFSI) {
  193. if (!Stack.empty() && Stack.back().second == OldFSI) {
  194. assert(Stack.back().first.empty());
  195. Stack.pop_back();
  196. }
  197. CurrentNonCapturingFunctionScope = nullptr;
  198. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  199. if (!isa<CapturingScopeInfo>(FSI)) {
  200. CurrentNonCapturingFunctionScope = FSI;
  201. break;
  202. }
  203. }
  204. }
  205. void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
  206. Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
  207. }
  208. const std::pair<OMPCriticalDirective *, llvm::APSInt>
  209. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  210. auto I = Criticals.find(Name.getAsString());
  211. if (I != Criticals.end())
  212. return I->second;
  213. return std::make_pair(nullptr, llvm::APSInt());
  214. }
  215. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  216. /// add it and return NULL; otherwise return previous occurrence's expression
  217. /// for diagnostics.
  218. Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
  219. /// \brief Register specified variable as loop control variable.
  220. void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
  221. /// \brief Check if the specified variable is a loop control variable for
  222. /// current region.
  223. /// \return The index of the loop control variable in the list of associated
  224. /// for-loops (from outer to inner).
  225. LCDeclInfo isLoopControlVariable(ValueDecl *D);
  226. /// \brief Check if the specified variable is a loop control variable for
  227. /// parent region.
  228. /// \return The index of the loop control variable in the list of associated
  229. /// for-loops (from outer to inner).
  230. LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
  231. /// \brief Get the loop control variable for the I-th loop (or nullptr) in
  232. /// parent directive.
  233. ValueDecl *getParentLoopControlVariable(unsigned I);
  234. /// \brief Adds explicit data sharing attribute to the specified declaration.
  235. void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  236. DeclRefExpr *PrivateCopy = nullptr);
  237. /// Adds additional information for the reduction items with the reduction id
  238. /// represented as an operator.
  239. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  240. BinaryOperatorKind BOK);
  241. /// Adds additional information for the reduction items with the reduction id
  242. /// represented as reduction identifier.
  243. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  244. const Expr *ReductionRef);
  245. /// Returns the location and reduction operation from the innermost parent
  246. /// region for the given \p D.
  247. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  248. BinaryOperatorKind &BOK,
  249. Expr *&TaskgroupDescriptor);
  250. /// Returns the location and reduction operation from the innermost parent
  251. /// region for the given \p D.
  252. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  253. const Expr *&ReductionRef,
  254. Expr *&TaskgroupDescriptor);
  255. /// Return reduction reference expression for the current taskgroup.
  256. Expr *getTaskgroupReductionRef() const {
  257. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  258. "taskgroup reference expression requested for non taskgroup "
  259. "directive.");
  260. return Stack.back().first.back().TaskgroupReductionRef;
  261. }
  262. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  263. /// descriptor variable at the \p Level of OpenMP regions.
  264. bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
  265. return Stack.back().first[Level].TaskgroupReductionRef &&
  266. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  267. ->getDecl() == VD;
  268. }
  269. /// \brief Returns data sharing attributes from top of the stack for the
  270. /// specified declaration.
  271. DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  272. /// \brief Returns data-sharing attributes for the specified declaration.
  273. DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
  274. /// \brief Checks if the specified variables has data-sharing attributes which
  275. /// match specified \a CPred predicate in any directive which matches \a DPred
  276. /// predicate.
  277. DSAVarData hasDSA(ValueDecl *D,
  278. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  279. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  280. bool FromParent);
  281. /// \brief Checks if the specified variables has data-sharing attributes which
  282. /// match specified \a CPred predicate in any innermost directive which
  283. /// matches \a DPred predicate.
  284. DSAVarData
  285. hasInnermostDSA(ValueDecl *D,
  286. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  287. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  288. bool FromParent);
  289. /// \brief Checks if the specified variables has explicit data-sharing
  290. /// attributes which match specified \a CPred predicate at the specified
  291. /// OpenMP region.
  292. bool hasExplicitDSA(ValueDecl *D,
  293. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  294. unsigned Level, bool NotLastprivate = false);
  295. /// \brief Returns true if the directive at level \Level matches in the
  296. /// specified \a DPred predicate.
  297. bool hasExplicitDirective(
  298. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  299. unsigned Level);
  300. /// \brief Finds a directive which matches specified \a DPred predicate.
  301. bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
  302. const DeclarationNameInfo &,
  303. SourceLocation)> &DPred,
  304. bool FromParent);
  305. /// \brief Returns currently analyzed directive.
  306. OpenMPDirectiveKind getCurrentDirective() const {
  307. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  308. }
  309. /// \brief Returns directive kind at specified level.
  310. OpenMPDirectiveKind getDirective(unsigned Level) const {
  311. assert(!isStackEmpty() && "No directive at specified level.");
  312. return Stack.back().first[Level].Directive;
  313. }
  314. /// \brief Returns parent directive.
  315. OpenMPDirectiveKind getParentDirective() const {
  316. if (isStackEmpty() || Stack.back().first.size() == 1)
  317. return OMPD_unknown;
  318. return std::next(Stack.back().first.rbegin())->Directive;
  319. }
  320. /// \brief Set default data sharing attribute to none.
  321. void setDefaultDSANone(SourceLocation Loc) {
  322. assert(!isStackEmpty());
  323. Stack.back().first.back().DefaultAttr = DSA_none;
  324. Stack.back().first.back().DefaultAttrLoc = Loc;
  325. }
  326. /// \brief Set default data sharing attribute to shared.
  327. void setDefaultDSAShared(SourceLocation Loc) {
  328. assert(!isStackEmpty());
  329. Stack.back().first.back().DefaultAttr = DSA_shared;
  330. Stack.back().first.back().DefaultAttrLoc = Loc;
  331. }
  332. /// Set default data mapping attribute to 'tofrom:scalar'.
  333. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  334. assert(!isStackEmpty());
  335. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  336. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  337. }
  338. DefaultDataSharingAttributes getDefaultDSA() const {
  339. return isStackEmpty() ? DSA_unspecified
  340. : Stack.back().first.back().DefaultAttr;
  341. }
  342. SourceLocation getDefaultDSALocation() const {
  343. return isStackEmpty() ? SourceLocation()
  344. : Stack.back().first.back().DefaultAttrLoc;
  345. }
  346. DefaultMapAttributes getDefaultDMA() const {
  347. return isStackEmpty() ? DMA_unspecified
  348. : Stack.back().first.back().DefaultMapAttr;
  349. }
  350. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  351. return Stack.back().first[Level].DefaultMapAttr;
  352. }
  353. SourceLocation getDefaultDMALocation() const {
  354. return isStackEmpty() ? SourceLocation()
  355. : Stack.back().first.back().DefaultMapAttrLoc;
  356. }
  357. /// \brief Checks if the specified variable is a threadprivate.
  358. bool isThreadPrivate(VarDecl *D) {
  359. DSAVarData DVar = getTopDSA(D, false);
  360. return isOpenMPThreadPrivate(DVar.CKind);
  361. }
  362. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  363. void setOrderedRegion(bool IsOrdered, Expr *Param) {
  364. assert(!isStackEmpty());
  365. Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
  366. Stack.back().first.back().OrderedRegion.setPointer(Param);
  367. }
  368. /// \brief Returns true, if parent region is ordered (has associated
  369. /// 'ordered' clause), false - otherwise.
  370. bool isParentOrderedRegion() const {
  371. if (isStackEmpty() || Stack.back().first.size() == 1)
  372. return false;
  373. return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
  374. }
  375. /// \brief Returns optional parameter for the ordered region.
  376. Expr *getParentOrderedRegionParam() const {
  377. if (isStackEmpty() || Stack.back().first.size() == 1)
  378. return nullptr;
  379. return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
  380. }
  381. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  382. void setNowaitRegion(bool IsNowait = true) {
  383. assert(!isStackEmpty());
  384. Stack.back().first.back().NowaitRegion = IsNowait;
  385. }
  386. /// \brief Returns true, if parent region is nowait (has associated
  387. /// 'nowait' clause), false - otherwise.
  388. bool isParentNowaitRegion() const {
  389. if (isStackEmpty() || Stack.back().first.size() == 1)
  390. return false;
  391. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  392. }
  393. /// \brief Marks parent region as cancel region.
  394. void setParentCancelRegion(bool Cancel = true) {
  395. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  396. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  397. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  398. }
  399. }
  400. /// \brief Return true if current region has inner cancel construct.
  401. bool isCancelRegion() const {
  402. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  403. }
  404. /// \brief Set collapse value for the region.
  405. void setAssociatedLoops(unsigned Val) {
  406. assert(!isStackEmpty());
  407. Stack.back().first.back().AssociatedLoops = Val;
  408. }
  409. /// \brief Return collapse value for region.
  410. unsigned getAssociatedLoops() const {
  411. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  412. }
  413. /// \brief Marks current target region as one with closely nested teams
  414. /// region.
  415. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  416. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  417. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  418. TeamsRegionLoc;
  419. }
  420. }
  421. /// \brief Returns true, if current region has closely nested teams region.
  422. bool hasInnerTeamsRegion() const {
  423. return getInnerTeamsRegionLoc().isValid();
  424. }
  425. /// \brief Returns location of the nested teams region (if any).
  426. SourceLocation getInnerTeamsRegionLoc() const {
  427. return isStackEmpty() ? SourceLocation()
  428. : Stack.back().first.back().InnerTeamsRegionLoc;
  429. }
  430. Scope *getCurScope() const {
  431. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  432. }
  433. Scope *getCurScope() {
  434. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  435. }
  436. SourceLocation getConstructLoc() {
  437. return isStackEmpty() ? SourceLocation()
  438. : Stack.back().first.back().ConstructLoc;
  439. }
  440. /// Do the check specified in \a Check to all component lists and return true
  441. /// if any issue is found.
  442. bool checkMappableExprComponentListsForDecl(
  443. ValueDecl *VD, bool CurrentRegionOnly,
  444. const llvm::function_ref<
  445. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  446. OpenMPClauseKind)> &Check) {
  447. if (isStackEmpty())
  448. return false;
  449. auto SI = Stack.back().first.rbegin();
  450. auto SE = Stack.back().first.rend();
  451. if (SI == SE)
  452. return false;
  453. if (CurrentRegionOnly) {
  454. SE = std::next(SI);
  455. } else {
  456. ++SI;
  457. }
  458. for (; SI != SE; ++SI) {
  459. auto MI = SI->MappedExprComponents.find(VD);
  460. if (MI != SI->MappedExprComponents.end())
  461. for (auto &L : MI->second.Components)
  462. if (Check(L, MI->second.Kind))
  463. return true;
  464. }
  465. return false;
  466. }
  467. /// Do the check specified in \a Check to all component lists at a given level
  468. /// and return true if any issue is found.
  469. bool checkMappableExprComponentListsForDeclAtLevel(
  470. ValueDecl *VD, unsigned Level,
  471. const llvm::function_ref<
  472. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  473. OpenMPClauseKind)> &Check) {
  474. if (isStackEmpty())
  475. return false;
  476. auto StartI = Stack.back().first.begin();
  477. auto EndI = Stack.back().first.end();
  478. if (std::distance(StartI, EndI) <= (int)Level)
  479. return false;
  480. std::advance(StartI, Level);
  481. auto MI = StartI->MappedExprComponents.find(VD);
  482. if (MI != StartI->MappedExprComponents.end())
  483. for (auto &L : MI->second.Components)
  484. if (Check(L, MI->second.Kind))
  485. return true;
  486. return false;
  487. }
  488. /// Create a new mappable expression component list associated with a given
  489. /// declaration and initialize it with the provided list of components.
  490. void addMappableExpressionComponents(
  491. ValueDecl *VD,
  492. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  493. OpenMPClauseKind WhereFoundClauseKind) {
  494. assert(!isStackEmpty() &&
  495. "Not expecting to retrieve components from a empty stack!");
  496. auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
  497. // Create new entry and append the new components there.
  498. MEC.Components.resize(MEC.Components.size() + 1);
  499. MEC.Components.back().append(Components.begin(), Components.end());
  500. MEC.Kind = WhereFoundClauseKind;
  501. }
  502. unsigned getNestingLevel() const {
  503. assert(!isStackEmpty());
  504. return Stack.back().first.size() - 1;
  505. }
  506. void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
  507. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  508. auto &StackElem = *std::next(Stack.back().first.rbegin());
  509. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  510. StackElem.DoacrossDepends.insert({C, OpsOffs});
  511. }
  512. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  513. getDoacrossDependClauses() const {
  514. assert(!isStackEmpty());
  515. auto &StackElem = Stack.back().first.back();
  516. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  517. auto &Ref = StackElem.DoacrossDepends;
  518. return llvm::make_range(Ref.begin(), Ref.end());
  519. }
  520. return llvm::make_range(StackElem.DoacrossDepends.end(),
  521. StackElem.DoacrossDepends.end());
  522. }
  523. };
  524. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  525. return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
  526. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  527. }
  528. } // namespace
  529. static Expr *getExprAsWritten(Expr *E) {
  530. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  531. E = ExprTemp->getSubExpr();
  532. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  533. E = MTE->GetTemporaryExpr();
  534. while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  535. E = Binder->getSubExpr();
  536. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  537. E = ICE->getSubExprAsWritten();
  538. return E->IgnoreParens();
  539. }
  540. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  541. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  542. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  543. D = ME->getMemberDecl();
  544. auto *VD = dyn_cast<VarDecl>(D);
  545. auto *FD = dyn_cast<FieldDecl>(D);
  546. if (VD != nullptr) {
  547. VD = VD->getCanonicalDecl();
  548. D = VD;
  549. } else {
  550. assert(FD);
  551. FD = FD->getCanonicalDecl();
  552. D = FD;
  553. }
  554. return D;
  555. }
  556. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
  557. ValueDecl *D) {
  558. D = getCanonicalDecl(D);
  559. auto *VD = dyn_cast<VarDecl>(D);
  560. auto *FD = dyn_cast<FieldDecl>(D);
  561. DSAVarData DVar;
  562. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  563. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  564. // in a region but not in construct]
  565. // File-scope or namespace-scope variables referenced in called routines
  566. // in the region are shared unless they appear in a threadprivate
  567. // directive.
  568. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  569. DVar.CKind = OMPC_shared;
  570. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  571. // in a region but not in construct]
  572. // Variables with static storage duration that are declared in called
  573. // routines in the region are shared.
  574. if (VD && VD->hasGlobalStorage())
  575. DVar.CKind = OMPC_shared;
  576. // Non-static data members are shared by default.
  577. if (FD)
  578. DVar.CKind = OMPC_shared;
  579. return DVar;
  580. }
  581. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  582. // in a Construct, C/C++, predetermined, p.1]
  583. // Variables with automatic storage duration that are declared in a scope
  584. // inside the construct are private.
  585. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  586. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  587. DVar.CKind = OMPC_private;
  588. return DVar;
  589. }
  590. DVar.DKind = Iter->Directive;
  591. // Explicitly specified attributes and local variables with predetermined
  592. // attributes.
  593. if (Iter->SharingMap.count(D)) {
  594. DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
  595. DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
  596. DVar.CKind = Iter->SharingMap[D].Attributes;
  597. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  598. return DVar;
  599. }
  600. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  601. // in a Construct, C/C++, implicitly determined, p.1]
  602. // In a parallel or task construct, the data-sharing attributes of these
  603. // variables are determined by the default clause, if present.
  604. switch (Iter->DefaultAttr) {
  605. case DSA_shared:
  606. DVar.CKind = OMPC_shared;
  607. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  608. return DVar;
  609. case DSA_none:
  610. return DVar;
  611. case DSA_unspecified:
  612. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  613. // in a Construct, implicitly determined, p.2]
  614. // In a parallel construct, if no default clause is present, these
  615. // variables are shared.
  616. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  617. if (isOpenMPParallelDirective(DVar.DKind) ||
  618. isOpenMPTeamsDirective(DVar.DKind)) {
  619. DVar.CKind = OMPC_shared;
  620. return DVar;
  621. }
  622. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  623. // in a Construct, implicitly determined, p.4]
  624. // In a task construct, if no default clause is present, a variable that in
  625. // the enclosing context is determined to be shared by all implicit tasks
  626. // bound to the current team is shared.
  627. if (isOpenMPTaskingDirective(DVar.DKind)) {
  628. DSAVarData DVarTemp;
  629. auto I = Iter, E = Stack.back().first.rend();
  630. do {
  631. ++I;
  632. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  633. // Referenced in a Construct, implicitly determined, p.6]
  634. // In a task construct, if no default clause is present, a variable
  635. // whose data-sharing attribute is not determined by the rules above is
  636. // firstprivate.
  637. DVarTemp = getDSA(I, D);
  638. if (DVarTemp.CKind != OMPC_shared) {
  639. DVar.RefExpr = nullptr;
  640. DVar.CKind = OMPC_firstprivate;
  641. return DVar;
  642. }
  643. } while (I != E && !isParallelOrTaskRegion(I->Directive));
  644. DVar.CKind =
  645. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  646. return DVar;
  647. }
  648. }
  649. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  650. // in a Construct, implicitly determined, p.3]
  651. // For constructs other than task, if no default clause is present, these
  652. // variables inherit their data-sharing attributes from the enclosing
  653. // context.
  654. return getDSA(++Iter, D);
  655. }
  656. Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
  657. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  658. D = getCanonicalDecl(D);
  659. auto &StackElem = Stack.back().first.back();
  660. auto It = StackElem.AlignedMap.find(D);
  661. if (It == StackElem.AlignedMap.end()) {
  662. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  663. StackElem.AlignedMap[D] = NewDE;
  664. return nullptr;
  665. } else {
  666. assert(It->second && "Unexpected nullptr expr in the aligned map");
  667. return It->second;
  668. }
  669. return nullptr;
  670. }
  671. void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
  672. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  673. D = getCanonicalDecl(D);
  674. auto &StackElem = Stack.back().first.back();
  675. StackElem.LCVMap.insert(
  676. {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
  677. }
  678. DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
  679. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  680. D = getCanonicalDecl(D);
  681. auto &StackElem = Stack.back().first.back();
  682. auto It = StackElem.LCVMap.find(D);
  683. if (It != StackElem.LCVMap.end())
  684. return It->second;
  685. return {0, nullptr};
  686. }
  687. DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
  688. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  689. "Data-sharing attributes stack is empty");
  690. D = getCanonicalDecl(D);
  691. auto &StackElem = *std::next(Stack.back().first.rbegin());
  692. auto It = StackElem.LCVMap.find(D);
  693. if (It != StackElem.LCVMap.end())
  694. return It->second;
  695. return {0, nullptr};
  696. }
  697. ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
  698. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  699. "Data-sharing attributes stack is empty");
  700. auto &StackElem = *std::next(Stack.back().first.rbegin());
  701. if (StackElem.LCVMap.size() < I)
  702. return nullptr;
  703. for (auto &Pair : StackElem.LCVMap)
  704. if (Pair.second.first == I)
  705. return Pair.first;
  706. return nullptr;
  707. }
  708. void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  709. DeclRefExpr *PrivateCopy) {
  710. D = getCanonicalDecl(D);
  711. if (A == OMPC_threadprivate) {
  712. auto &Data = Threadprivates[D];
  713. Data.Attributes = A;
  714. Data.RefExpr.setPointer(E);
  715. Data.PrivateCopy = nullptr;
  716. } else {
  717. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  718. auto &Data = Stack.back().first.back().SharingMap[D];
  719. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  720. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  721. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  722. (isLoopControlVariable(D).first && A == OMPC_private));
  723. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  724. Data.RefExpr.setInt(/*IntVal=*/true);
  725. return;
  726. }
  727. const bool IsLastprivate =
  728. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  729. Data.Attributes = A;
  730. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  731. Data.PrivateCopy = PrivateCopy;
  732. if (PrivateCopy) {
  733. auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  734. Data.Attributes = A;
  735. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  736. Data.PrivateCopy = nullptr;
  737. }
  738. }
  739. }
  740. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  741. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  742. StringRef Name, const AttrVec *Attrs = nullptr) {
  743. DeclContext *DC = SemaRef.CurContext;
  744. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  745. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  746. VarDecl *Decl =
  747. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  748. if (Attrs) {
  749. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  750. I != E; ++I)
  751. Decl->addAttr(*I);
  752. }
  753. Decl->setImplicit();
  754. return Decl;
  755. }
  756. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  757. SourceLocation Loc,
  758. bool RefersToCapture = false) {
  759. D->setReferenced();
  760. D->markUsed(S.Context);
  761. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  762. SourceLocation(), D, RefersToCapture, Loc, Ty,
  763. VK_LValue);
  764. }
  765. void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  766. BinaryOperatorKind BOK) {
  767. D = getCanonicalDecl(D);
  768. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  769. assert(
  770. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  771. "Additional reduction info may be specified only for reduction items.");
  772. auto &ReductionData = Stack.back().first.back().ReductionMap[D];
  773. assert(ReductionData.ReductionRange.isInvalid() &&
  774. Stack.back().first.back().Directive == OMPD_taskgroup &&
  775. "Additional reduction info may be specified only once for reduction "
  776. "items.");
  777. ReductionData.set(BOK, SR);
  778. Expr *&TaskgroupReductionRef =
  779. Stack.back().first.back().TaskgroupReductionRef;
  780. if (!TaskgroupReductionRef) {
  781. auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
  782. SemaRef.Context.VoidPtrTy, ".task_red.");
  783. TaskgroupReductionRef =
  784. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  785. }
  786. }
  787. void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  788. const Expr *ReductionRef) {
  789. D = getCanonicalDecl(D);
  790. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  791. assert(
  792. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  793. "Additional reduction info may be specified only for reduction items.");
  794. auto &ReductionData = Stack.back().first.back().ReductionMap[D];
  795. assert(ReductionData.ReductionRange.isInvalid() &&
  796. Stack.back().first.back().Directive == OMPD_taskgroup &&
  797. "Additional reduction info may be specified only once for reduction "
  798. "items.");
  799. ReductionData.set(ReductionRef, SR);
  800. Expr *&TaskgroupReductionRef =
  801. Stack.back().first.back().TaskgroupReductionRef;
  802. if (!TaskgroupReductionRef) {
  803. auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
  804. ".task_red.");
  805. TaskgroupReductionRef =
  806. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  807. }
  808. }
  809. DSAStackTy::DSAVarData
  810. DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  811. BinaryOperatorKind &BOK,
  812. Expr *&TaskgroupDescriptor) {
  813. D = getCanonicalDecl(D);
  814. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  815. if (Stack.back().first.empty())
  816. return DSAVarData();
  817. for (auto I = std::next(Stack.back().first.rbegin(), 1),
  818. E = Stack.back().first.rend();
  819. I != E; std::advance(I, 1)) {
  820. auto &Data = I->SharingMap[D];
  821. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  822. continue;
  823. auto &ReductionData = I->ReductionMap[D];
  824. if (!ReductionData.ReductionOp ||
  825. ReductionData.ReductionOp.is<const Expr *>())
  826. return DSAVarData();
  827. SR = ReductionData.ReductionRange;
  828. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  829. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  830. "expression for the descriptor is not "
  831. "set.");
  832. TaskgroupDescriptor = I->TaskgroupReductionRef;
  833. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  834. Data.PrivateCopy, I->DefaultAttrLoc);
  835. }
  836. return DSAVarData();
  837. }
  838. DSAStackTy::DSAVarData
  839. DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  840. const Expr *&ReductionRef,
  841. Expr *&TaskgroupDescriptor) {
  842. D = getCanonicalDecl(D);
  843. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  844. if (Stack.back().first.empty())
  845. return DSAVarData();
  846. for (auto I = std::next(Stack.back().first.rbegin(), 1),
  847. E = Stack.back().first.rend();
  848. I != E; std::advance(I, 1)) {
  849. auto &Data = I->SharingMap[D];
  850. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  851. continue;
  852. auto &ReductionData = I->ReductionMap[D];
  853. if (!ReductionData.ReductionOp ||
  854. !ReductionData.ReductionOp.is<const Expr *>())
  855. return DSAVarData();
  856. SR = ReductionData.ReductionRange;
  857. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  858. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  859. "expression for the descriptor is not "
  860. "set.");
  861. TaskgroupDescriptor = I->TaskgroupReductionRef;
  862. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  863. Data.PrivateCopy, I->DefaultAttrLoc);
  864. }
  865. return DSAVarData();
  866. }
  867. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  868. D = D->getCanonicalDecl();
  869. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  870. reverse_iterator I = Iter, E = Stack.back().first.rend();
  871. Scope *TopScope = nullptr;
  872. while (I != E && !isParallelOrTaskRegion(I->Directive))
  873. ++I;
  874. if (I == E)
  875. return false;
  876. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  877. Scope *CurScope = getCurScope();
  878. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  879. CurScope = CurScope->getParent();
  880. return CurScope != TopScope;
  881. }
  882. return false;
  883. }
  884. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
  885. D = getCanonicalDecl(D);
  886. DSAVarData DVar;
  887. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  888. // in a Construct, C/C++, predetermined, p.1]
  889. // Variables appearing in threadprivate directives are threadprivate.
  890. auto *VD = dyn_cast<VarDecl>(D);
  891. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  892. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  893. SemaRef.getLangOpts().OpenMPUseTLS &&
  894. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  895. (VD && VD->getStorageClass() == SC_Register &&
  896. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  897. addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  898. D->getLocation()),
  899. OMPC_threadprivate);
  900. }
  901. auto TI = Threadprivates.find(D);
  902. if (TI != Threadprivates.end()) {
  903. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  904. DVar.CKind = OMPC_threadprivate;
  905. return DVar;
  906. } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  907. DVar.RefExpr = buildDeclRefExpr(
  908. SemaRef, VD, D->getType().getNonReferenceType(),
  909. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  910. DVar.CKind = OMPC_threadprivate;
  911. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  912. }
  913. if (isStackEmpty())
  914. // Not in OpenMP execution region and top scope was already checked.
  915. return DVar;
  916. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  917. // in a Construct, C/C++, predetermined, p.4]
  918. // Static data members are shared.
  919. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  920. // in a Construct, C/C++, predetermined, p.7]
  921. // Variables with static storage duration that are declared in a scope
  922. // inside the construct are shared.
  923. auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
  924. if (VD && VD->isStaticDataMember()) {
  925. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  926. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  927. return DVar;
  928. DVar.CKind = OMPC_shared;
  929. return DVar;
  930. }
  931. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  932. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  933. Type = SemaRef.getASTContext().getBaseElementType(Type);
  934. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  935. // in a Construct, C/C++, predetermined, p.6]
  936. // Variables with const qualified type having no mutable member are
  937. // shared.
  938. CXXRecordDecl *RD =
  939. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  940. if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  941. if (auto *CTD = CTSD->getSpecializedTemplate())
  942. RD = CTD->getTemplatedDecl();
  943. if (IsConstant &&
  944. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  945. RD->hasMutableFields())) {
  946. // Variables with const-qualified type having no mutable member may be
  947. // listed in a firstprivate clause, even if they are static data members.
  948. DSAVarData DVarTemp = hasDSA(
  949. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
  950. MatchesAlways, FromParent);
  951. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  952. return DVar;
  953. DVar.CKind = OMPC_shared;
  954. return DVar;
  955. }
  956. // Explicitly specified attributes and local variables with predetermined
  957. // attributes.
  958. auto I = Stack.back().first.rbegin();
  959. auto EndI = Stack.back().first.rend();
  960. if (FromParent && I != EndI)
  961. std::advance(I, 1);
  962. if (I->SharingMap.count(D)) {
  963. DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
  964. DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
  965. DVar.CKind = I->SharingMap[D].Attributes;
  966. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  967. DVar.DKind = I->Directive;
  968. }
  969. return DVar;
  970. }
  971. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  972. bool FromParent) {
  973. if (isStackEmpty()) {
  974. StackTy::reverse_iterator I;
  975. return getDSA(I, D);
  976. }
  977. D = getCanonicalDecl(D);
  978. auto StartI = Stack.back().first.rbegin();
  979. auto EndI = Stack.back().first.rend();
  980. if (FromParent && StartI != EndI)
  981. std::advance(StartI, 1);
  982. return getDSA(StartI, D);
  983. }
  984. DSAStackTy::DSAVarData
  985. DSAStackTy::hasDSA(ValueDecl *D,
  986. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  987. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  988. bool FromParent) {
  989. if (isStackEmpty())
  990. return {};
  991. D = getCanonicalDecl(D);
  992. auto I = Stack.back().first.rbegin();
  993. auto EndI = Stack.back().first.rend();
  994. if (FromParent && I != EndI)
  995. std::advance(I, 1);
  996. for (; I != EndI; std::advance(I, 1)) {
  997. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  998. continue;
  999. auto NewI = I;
  1000. DSAVarData DVar = getDSA(NewI, D);
  1001. if (I == NewI && CPred(DVar.CKind))
  1002. return DVar;
  1003. }
  1004. return {};
  1005. }
  1006. DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1007. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  1008. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1009. bool FromParent) {
  1010. if (isStackEmpty())
  1011. return {};
  1012. D = getCanonicalDecl(D);
  1013. auto StartI = Stack.back().first.rbegin();
  1014. auto EndI = Stack.back().first.rend();
  1015. if (FromParent && StartI != EndI)
  1016. std::advance(StartI, 1);
  1017. if (StartI == EndI || !DPred(StartI->Directive))
  1018. return {};
  1019. auto NewI = StartI;
  1020. DSAVarData DVar = getDSA(NewI, D);
  1021. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1022. }
  1023. bool DSAStackTy::hasExplicitDSA(
  1024. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  1025. unsigned Level, bool NotLastprivate) {
  1026. if (isStackEmpty())
  1027. return false;
  1028. D = getCanonicalDecl(D);
  1029. auto StartI = Stack.back().first.begin();
  1030. auto EndI = Stack.back().first.end();
  1031. if (std::distance(StartI, EndI) <= (int)Level)
  1032. return false;
  1033. std::advance(StartI, Level);
  1034. return (StartI->SharingMap.count(D) > 0) &&
  1035. StartI->SharingMap[D].RefExpr.getPointer() &&
  1036. CPred(StartI->SharingMap[D].Attributes) &&
  1037. (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
  1038. }
  1039. bool DSAStackTy::hasExplicitDirective(
  1040. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1041. unsigned Level) {
  1042. if (isStackEmpty())
  1043. return false;
  1044. auto StartI = Stack.back().first.begin();
  1045. auto EndI = Stack.back().first.end();
  1046. if (std::distance(StartI, EndI) <= (int)Level)
  1047. return false;
  1048. std::advance(StartI, Level);
  1049. return DPred(StartI->Directive);
  1050. }
  1051. bool DSAStackTy::hasDirective(
  1052. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1053. const DeclarationNameInfo &, SourceLocation)>
  1054. &DPred,
  1055. bool FromParent) {
  1056. // We look only in the enclosing region.
  1057. if (isStackEmpty())
  1058. return false;
  1059. auto StartI = std::next(Stack.back().first.rbegin());
  1060. auto EndI = Stack.back().first.rend();
  1061. if (FromParent && StartI != EndI)
  1062. StartI = std::next(StartI);
  1063. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1064. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1065. return true;
  1066. }
  1067. return false;
  1068. }
  1069. void Sema::InitDataSharingAttributesStack() {
  1070. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1071. }
  1072. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1073. void Sema::pushOpenMPFunctionRegion() {
  1074. DSAStack->pushFunction();
  1075. }
  1076. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1077. DSAStack->popFunction(OldFSI);
  1078. }
  1079. bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
  1080. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1081. auto &Ctx = getASTContext();
  1082. bool IsByRef = true;
  1083. // Find the directive that is associated with the provided scope.
  1084. D = cast<ValueDecl>(D->getCanonicalDecl());
  1085. auto Ty = D->getType();
  1086. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1087. // This table summarizes how a given variable should be passed to the device
  1088. // given its type and the clauses where it appears. This table is based on
  1089. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1090. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1091. //
  1092. // =========================================================================
  1093. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1094. // | |(tofrom:scalar)| | pvt | | | |
  1095. // =========================================================================
  1096. // | scl | | | | - | | bycopy|
  1097. // | scl | | - | x | - | - | bycopy|
  1098. // | scl | | x | - | - | - | null |
  1099. // | scl | x | | | - | | byref |
  1100. // | scl | x | - | x | - | - | bycopy|
  1101. // | scl | x | x | - | - | - | null |
  1102. // | scl | | - | - | - | x | byref |
  1103. // | scl | x | - | - | - | x | byref |
  1104. //
  1105. // | agg | n.a. | | | - | | byref |
  1106. // | agg | n.a. | - | x | - | - | byref |
  1107. // | agg | n.a. | x | - | - | - | null |
  1108. // | agg | n.a. | - | - | - | x | byref |
  1109. // | agg | n.a. | - | - | - | x[] | byref |
  1110. //
  1111. // | ptr | n.a. | | | - | | bycopy|
  1112. // | ptr | n.a. | - | x | - | - | bycopy|
  1113. // | ptr | n.a. | x | - | - | - | null |
  1114. // | ptr | n.a. | - | - | - | x | byref |
  1115. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1116. // | ptr | n.a. | - | - | x | | bycopy|
  1117. // | ptr | n.a. | - | - | x | x | bycopy|
  1118. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1119. // =========================================================================
  1120. // Legend:
  1121. // scl - scalar
  1122. // ptr - pointer
  1123. // agg - aggregate
  1124. // x - applies
  1125. // - - invalid in this combination
  1126. // [] - mapped with an array section
  1127. // byref - should be mapped by reference
  1128. // byval - should be mapped by value
  1129. // null - initialize a local variable to null on the device
  1130. //
  1131. // Observations:
  1132. // - All scalar declarations that show up in a map clause have to be passed
  1133. // by reference, because they may have been mapped in the enclosing data
  1134. // environment.
  1135. // - If the scalar value does not fit the size of uintptr, it has to be
  1136. // passed by reference, regardless the result in the table above.
  1137. // - For pointers mapped by value that have either an implicit map or an
  1138. // array section, the runtime library may pass the NULL value to the
  1139. // device instead of the value passed to it by the compiler.
  1140. if (Ty->isReferenceType())
  1141. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1142. // Locate map clauses and see if the variable being captured is referred to
  1143. // in any of those clauses. Here we only care about variables, not fields,
  1144. // because fields are part of aggregates.
  1145. bool IsVariableUsedInMapClause = false;
  1146. bool IsVariableAssociatedWithSection = false;
  1147. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1148. D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1149. MapExprComponents,
  1150. OpenMPClauseKind WhereFoundClauseKind) {
  1151. // Only the map clause information influences how a variable is
  1152. // captured. E.g. is_device_ptr does not require changing the default
  1153. // behavior.
  1154. if (WhereFoundClauseKind != OMPC_map)
  1155. return false;
  1156. auto EI = MapExprComponents.rbegin();
  1157. auto EE = MapExprComponents.rend();
  1158. assert(EI != EE && "Invalid map expression!");
  1159. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1160. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1161. ++EI;
  1162. if (EI == EE)
  1163. return false;
  1164. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1165. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1166. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1167. IsVariableAssociatedWithSection = true;
  1168. // There is nothing more we need to know about this variable.
  1169. return true;
  1170. }
  1171. // Keep looking for more map info.
  1172. return false;
  1173. });
  1174. if (IsVariableUsedInMapClause) {
  1175. // If variable is identified in a map clause it is always captured by
  1176. // reference except if it is a pointer that is dereferenced somehow.
  1177. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1178. } else {
  1179. // By default, all the data that has a scalar type is mapped by copy
  1180. // (except for reduction variables).
  1181. IsByRef =
  1182. !Ty->isScalarType() ||
  1183. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1184. DSAStack->hasExplicitDSA(
  1185. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1186. }
  1187. }
  1188. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1189. IsByRef = !DSAStack->hasExplicitDSA(
  1190. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1191. Level, /*NotLastprivate=*/true);
  1192. }
  1193. // When passing data by copy, we need to make sure it fits the uintptr size
  1194. // and alignment, because the runtime library only deals with uintptr types.
  1195. // If it does not fit the uintptr size, we need to pass the data by reference
  1196. // instead.
  1197. if (!IsByRef &&
  1198. (Ctx.getTypeSizeInChars(Ty) >
  1199. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1200. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1201. IsByRef = true;
  1202. }
  1203. return IsByRef;
  1204. }
  1205. unsigned Sema::getOpenMPNestingLevel() const {
  1206. assert(getLangOpts().OpenMP);
  1207. return DSAStack->getNestingLevel();
  1208. }
  1209. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1210. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1211. !DSAStack->isClauseParsingMode()) ||
  1212. DSAStack->hasDirective(
  1213. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1214. SourceLocation) -> bool {
  1215. return isOpenMPTargetExecutionDirective(K);
  1216. },
  1217. false);
  1218. }
  1219. VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
  1220. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1221. D = getCanonicalDecl(D);
  1222. // If we are attempting to capture a global variable in a directive with
  1223. // 'target' we return true so that this global is also mapped to the device.
  1224. //
  1225. // FIXME: If the declaration is enclosed in a 'declare target' directive,
  1226. // then it should not be captured. Therefore, an extra check has to be
  1227. // inserted here once support for 'declare target' is added.
  1228. //
  1229. auto *VD = dyn_cast<VarDecl>(D);
  1230. if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
  1231. return VD;
  1232. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1233. (!DSAStack->isClauseParsingMode() ||
  1234. DSAStack->getParentDirective() != OMPD_unknown)) {
  1235. auto &&Info = DSAStack->isLoopControlVariable(D);
  1236. if (Info.first ||
  1237. (VD && VD->hasLocalStorage() &&
  1238. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1239. (VD && DSAStack->isForceVarCapturing()))
  1240. return VD ? VD : Info.second;
  1241. auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1242. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1243. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1244. DVarPrivate = DSAStack->hasDSA(
  1245. D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  1246. DSAStack->isClauseParsingMode());
  1247. if (DVarPrivate.CKind != OMPC_unknown)
  1248. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1249. }
  1250. return nullptr;
  1251. }
  1252. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1253. unsigned Level) const {
  1254. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1255. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1256. FunctionScopesIndex -= Regions.size();
  1257. }
  1258. bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
  1259. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1260. return DSAStack->hasExplicitDSA(
  1261. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
  1262. Level) ||
  1263. (DSAStack->isClauseParsingMode() &&
  1264. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1265. // Consider taskgroup reduction descriptor variable a private to avoid
  1266. // possible capture in the region.
  1267. (DSAStack->hasExplicitDirective(
  1268. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1269. Level) &&
  1270. DSAStack->isTaskgroupReductionRef(D, Level));
  1271. }
  1272. void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
  1273. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1274. D = getCanonicalDecl(D);
  1275. OpenMPClauseKind OMPC = OMPC_unknown;
  1276. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1277. const unsigned NewLevel = I - 1;
  1278. if (DSAStack->hasExplicitDSA(D,
  1279. [&OMPC](const OpenMPClauseKind K) {
  1280. if (isOpenMPPrivate(K)) {
  1281. OMPC = K;
  1282. return true;
  1283. }
  1284. return false;
  1285. },
  1286. NewLevel))
  1287. break;
  1288. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1289. D, NewLevel,
  1290. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1291. OpenMPClauseKind) { return true; })) {
  1292. OMPC = OMPC_map;
  1293. break;
  1294. }
  1295. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1296. NewLevel)) {
  1297. OMPC = OMPC_firstprivate;
  1298. break;
  1299. }
  1300. }
  1301. if (OMPC != OMPC_unknown)
  1302. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1303. }
  1304. bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
  1305. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1306. // Return true if the current level is no longer enclosed in a target region.
  1307. auto *VD = dyn_cast<VarDecl>(D);
  1308. return VD && !VD->hasLocalStorage() &&
  1309. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1310. Level);
  1311. }
  1312. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1313. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1314. const DeclarationNameInfo &DirName,
  1315. Scope *CurScope, SourceLocation Loc) {
  1316. DSAStack->push(DKind, DirName, CurScope, Loc);
  1317. PushExpressionEvaluationContext(
  1318. ExpressionEvaluationContext::PotentiallyEvaluated);
  1319. }
  1320. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1321. DSAStack->setClauseParsingMode(K);
  1322. }
  1323. void Sema::EndOpenMPClause() {
  1324. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1325. }
  1326. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1327. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1328. // A variable of class type (or array thereof) that appears in a lastprivate
  1329. // clause requires an accessible, unambiguous default constructor for the
  1330. // class type, unless the list item is also specified in a firstprivate
  1331. // clause.
  1332. if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1333. for (auto *C : D->clauses()) {
  1334. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1335. SmallVector<Expr *, 8> PrivateCopies;
  1336. for (auto *DE : Clause->varlists()) {
  1337. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1338. PrivateCopies.push_back(nullptr);
  1339. continue;
  1340. }
  1341. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1342. VarDecl *VD = cast<VarDecl>(DRE->getDecl());
  1343. QualType Type = VD->getType().getNonReferenceType();
  1344. auto DVar = DSAStack->getTopDSA(VD, false);
  1345. if (DVar.CKind == OMPC_lastprivate) {
  1346. // Generate helper private variable and initialize it with the
  1347. // default value. The address of the original variable is replaced
  1348. // by the address of the new private variable in CodeGen. This new
  1349. // variable is not added to IdResolver, so the code in the OpenMP
  1350. // region uses original variable for proper diagnostics.
  1351. auto *VDPrivate = buildVarDecl(
  1352. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1353. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  1354. ActOnUninitializedDecl(VDPrivate);
  1355. if (VDPrivate->isInvalidDecl())
  1356. continue;
  1357. PrivateCopies.push_back(buildDeclRefExpr(
  1358. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1359. } else {
  1360. // The variable is also a firstprivate, so initialization sequence
  1361. // for private copy is generated already.
  1362. PrivateCopies.push_back(nullptr);
  1363. }
  1364. }
  1365. // Set initializers to private copies if no errors were found.
  1366. if (PrivateCopies.size() == Clause->varlist_size())
  1367. Clause->setPrivateCopies(PrivateCopies);
  1368. }
  1369. }
  1370. }
  1371. DSAStack->pop();
  1372. DiscardCleanupsInEvaluationContext();
  1373. PopExpressionEvaluationContext();
  1374. }
  1375. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1376. Expr *NumIterations, Sema &SemaRef,
  1377. Scope *S, DSAStackTy *Stack);
  1378. namespace {
  1379. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  1380. private:
  1381. Sema &SemaRef;
  1382. public:
  1383. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1384. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1385. NamedDecl *ND = Candidate.getCorrectionDecl();
  1386. if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1387. return VD->hasGlobalStorage() &&
  1388. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1389. SemaRef.getCurScope());
  1390. }
  1391. return false;
  1392. }
  1393. };
  1394. class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
  1395. private:
  1396. Sema &SemaRef;
  1397. public:
  1398. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1399. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1400. NamedDecl *ND = Candidate.getCorrectionDecl();
  1401. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1402. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1403. SemaRef.getCurScope());
  1404. }
  1405. return false;
  1406. }
  1407. };
  1408. } // namespace
  1409. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1410. CXXScopeSpec &ScopeSpec,
  1411. const DeclarationNameInfo &Id) {
  1412. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1413. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1414. if (Lookup.isAmbiguous())
  1415. return ExprError();
  1416. VarDecl *VD;
  1417. if (!Lookup.isSingleResult()) {
  1418. if (TypoCorrection Corrected = CorrectTypo(
  1419. Id, LookupOrdinaryName, CurScope, nullptr,
  1420. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1421. diagnoseTypo(Corrected,
  1422. PDiag(Lookup.empty()
  1423. ? diag::err_undeclared_var_use_suggest
  1424. : diag::err_omp_expected_var_arg_suggest)
  1425. << Id.getName());
  1426. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1427. } else {
  1428. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1429. : diag::err_omp_expected_var_arg)
  1430. << Id.getName();
  1431. return ExprError();
  1432. }
  1433. } else {
  1434. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1435. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1436. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1437. return ExprError();
  1438. }
  1439. }
  1440. Lookup.suppressDiagnostics();
  1441. // OpenMP [2.9.2, Syntax, C/C++]
  1442. // Variables must be file-scope, namespace-scope, or static block-scope.
  1443. if (!VD->hasGlobalStorage()) {
  1444. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1445. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1446. bool IsDecl =
  1447. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1448. Diag(VD->getLocation(),
  1449. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1450. << VD;
  1451. return ExprError();
  1452. }
  1453. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1454. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1455. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1456. // A threadprivate directive for file-scope variables must appear outside
  1457. // any definition or declaration.
  1458. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1459. !getCurLexicalContext()->isTranslationUnit()) {
  1460. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1461. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1462. bool IsDecl =
  1463. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1464. Diag(VD->getLocation(),
  1465. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1466. << VD;
  1467. return ExprError();
  1468. }
  1469. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1470. // A threadprivate directive for static class member variables must appear
  1471. // in the class definition, in the same scope in which the member
  1472. // variables are declared.
  1473. if (CanonicalVD->isStaticDataMember() &&
  1474. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1475. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1476. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1477. bool IsDecl =
  1478. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1479. Diag(VD->getLocation(),
  1480. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1481. << VD;
  1482. return ExprError();
  1483. }
  1484. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1485. // A threadprivate directive for namespace-scope variables must appear
  1486. // outside any definition or declaration other than the namespace
  1487. // definition itself.
  1488. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1489. (!getCurLexicalContext()->isFileContext() ||
  1490. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1491. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1492. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1493. bool IsDecl =
  1494. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1495. Diag(VD->getLocation(),
  1496. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1497. << VD;
  1498. return ExprError();
  1499. }
  1500. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1501. // A threadprivate directive for static block-scope variables must appear
  1502. // in the scope of the variable and not in a nested scope.
  1503. if (CanonicalVD->isStaticLocal() && CurScope &&
  1504. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1505. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1506. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1507. bool IsDecl =
  1508. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1509. Diag(VD->getLocation(),
  1510. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1511. << VD;
  1512. return ExprError();
  1513. }
  1514. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1515. // A threadprivate directive must lexically precede all references to any
  1516. // of the variables in its list.
  1517. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1518. Diag(Id.getLoc(), diag::err_omp_var_used)
  1519. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1520. return ExprError();
  1521. }
  1522. QualType ExprType = VD->getType().getNonReferenceType();
  1523. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1524. SourceLocation(), VD,
  1525. /*RefersToEnclosingVariableOrCapture=*/false,
  1526. Id.getLoc(), ExprType, VK_LValue);
  1527. }
  1528. Sema::DeclGroupPtrTy
  1529. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1530. ArrayRef<Expr *> VarList) {
  1531. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1532. CurContext->addDecl(D);
  1533. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1534. }
  1535. return nullptr;
  1536. }
  1537. namespace {
  1538. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1539. Sema &SemaRef;
  1540. public:
  1541. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1542. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1543. if (VD->hasLocalStorage()) {
  1544. SemaRef.Diag(E->getLocStart(),
  1545. diag::err_omp_local_var_in_threadprivate_init)
  1546. << E->getSourceRange();
  1547. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1548. << VD << VD->getSourceRange();
  1549. return true;
  1550. }
  1551. }
  1552. return false;
  1553. }
  1554. bool VisitStmt(const Stmt *S) {
  1555. for (auto Child : S->children()) {
  1556. if (Child && Visit(Child))
  1557. return true;
  1558. }
  1559. return false;
  1560. }
  1561. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1562. };
  1563. } // namespace
  1564. OMPThreadPrivateDecl *
  1565. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1566. SmallVector<Expr *, 8> Vars;
  1567. for (auto &RefExpr : VarList) {
  1568. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1569. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1570. SourceLocation ILoc = DE->getExprLoc();
  1571. // Mark variable as used.
  1572. VD->setReferenced();
  1573. VD->markUsed(Context);
  1574. QualType QType = VD->getType();
  1575. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1576. // It will be analyzed later.
  1577. Vars.push_back(DE);
  1578. continue;
  1579. }
  1580. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1581. // A threadprivate variable must not have an incomplete type.
  1582. if (RequireCompleteType(ILoc, VD->getType(),
  1583. diag::err_omp_threadprivate_incomplete_type)) {
  1584. continue;
  1585. }
  1586. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1587. // A threadprivate variable must not have a reference type.
  1588. if (VD->getType()->isReferenceType()) {
  1589. Diag(ILoc, diag::err_omp_ref_type_arg)
  1590. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1591. bool IsDecl =
  1592. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1593. Diag(VD->getLocation(),
  1594. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1595. << VD;
  1596. continue;
  1597. }
  1598. // Check if this is a TLS variable. If TLS is not being supported, produce
  1599. // the corresponding diagnostic.
  1600. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1601. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1602. getLangOpts().OpenMPUseTLS &&
  1603. getASTContext().getTargetInfo().isTLSSupported())) ||
  1604. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1605. !VD->isLocalVarDecl())) {
  1606. Diag(ILoc, diag::err_omp_var_thread_local)
  1607. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1608. bool IsDecl =
  1609. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1610. Diag(VD->getLocation(),
  1611. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1612. << VD;
  1613. continue;
  1614. }
  1615. // Check if initial value of threadprivate variable reference variable with
  1616. // local storage (it is not supported by runtime).
  1617. if (auto Init = VD->getAnyInitializer()) {
  1618. LocalVarRefChecker Checker(*this);
  1619. if (Checker.Visit(Init))
  1620. continue;
  1621. }
  1622. Vars.push_back(RefExpr);
  1623. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1624. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1625. Context, SourceRange(Loc, Loc)));
  1626. if (auto *ML = Context.getASTMutationListener())
  1627. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1628. }
  1629. OMPThreadPrivateDecl *D = nullptr;
  1630. if (!Vars.empty()) {
  1631. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1632. Vars);
  1633. D->setAccess(AS_public);
  1634. }
  1635. return D;
  1636. }
  1637. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1638. const ValueDecl *D, DSAStackTy::DSAVarData DVar,
  1639. bool IsLoopIterVar = false) {
  1640. if (DVar.RefExpr) {
  1641. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1642. << getOpenMPClauseName(DVar.CKind);
  1643. return;
  1644. }
  1645. enum {
  1646. PDSA_StaticMemberShared,
  1647. PDSA_StaticLocalVarShared,
  1648. PDSA_LoopIterVarPrivate,
  1649. PDSA_LoopIterVarLinear,
  1650. PDSA_LoopIterVarLastprivate,
  1651. PDSA_ConstVarShared,
  1652. PDSA_GlobalVarShared,
  1653. PDSA_TaskVarFirstprivate,
  1654. PDSA_LocalVarPrivate,
  1655. PDSA_Implicit
  1656. } Reason = PDSA_Implicit;
  1657. bool ReportHint = false;
  1658. auto ReportLoc = D->getLocation();
  1659. auto *VD = dyn_cast<VarDecl>(D);
  1660. if (IsLoopIterVar) {
  1661. if (DVar.CKind == OMPC_private)
  1662. Reason = PDSA_LoopIterVarPrivate;
  1663. else if (DVar.CKind == OMPC_lastprivate)
  1664. Reason = PDSA_LoopIterVarLastprivate;
  1665. else
  1666. Reason = PDSA_LoopIterVarLinear;
  1667. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1668. DVar.CKind == OMPC_firstprivate) {
  1669. Reason = PDSA_TaskVarFirstprivate;
  1670. ReportLoc = DVar.ImplicitDSALoc;
  1671. } else if (VD && VD->isStaticLocal())
  1672. Reason = PDSA_StaticLocalVarShared;
  1673. else if (VD && VD->isStaticDataMember())
  1674. Reason = PDSA_StaticMemberShared;
  1675. else if (VD && VD->isFileVarDecl())
  1676. Reason = PDSA_GlobalVarShared;
  1677. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1678. Reason = PDSA_ConstVarShared;
  1679. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1680. ReportHint = true;
  1681. Reason = PDSA_LocalVarPrivate;
  1682. }
  1683. if (Reason != PDSA_Implicit) {
  1684. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1685. << Reason << ReportHint
  1686. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1687. } else if (DVar.ImplicitDSALoc.isValid()) {
  1688. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1689. << getOpenMPClauseName(DVar.CKind);
  1690. }
  1691. }
  1692. namespace {
  1693. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1694. DSAStackTy *Stack;
  1695. Sema &SemaRef;
  1696. bool ErrorFound;
  1697. CapturedStmt *CS;
  1698. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1699. llvm::SmallVector<Expr *, 8> ImplicitMap;
  1700. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  1701. llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
  1702. public:
  1703. void VisitDeclRefExpr(DeclRefExpr *E) {
  1704. if (E->isTypeDependent() || E->isValueDependent() ||
  1705. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1706. return;
  1707. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1708. VD = VD->getCanonicalDecl();
  1709. // Skip internally declared variables.
  1710. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  1711. return;
  1712. auto DVar = Stack->getTopDSA(VD, false);
  1713. // Check if the variable has explicit DSA set and stop analysis if it so.
  1714. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  1715. return;
  1716. // Skip internally declared static variables.
  1717. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
  1718. return;
  1719. auto ELoc = E->getExprLoc();
  1720. auto DKind = Stack->getCurrentDirective();
  1721. // The default(none) clause requires that each variable that is referenced
  1722. // in the construct, and does not have a predetermined data-sharing
  1723. // attribute, must have its data-sharing attribute explicitly determined
  1724. // by being listed in a data-sharing attribute clause.
  1725. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1726. isParallelOrTaskRegion(DKind) &&
  1727. VarsWithInheritedDSA.count(VD) == 0) {
  1728. VarsWithInheritedDSA[VD] = E;
  1729. return;
  1730. }
  1731. if (isOpenMPTargetExecutionDirective(DKind) &&
  1732. !Stack->isLoopControlVariable(VD).first) {
  1733. if (!Stack->checkMappableExprComponentListsForDecl(
  1734. VD, /*CurrentRegionOnly=*/true,
  1735. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1736. StackComponents,
  1737. OpenMPClauseKind) {
  1738. // Variable is used if it has been marked as an array, array
  1739. // section or the variable iself.
  1740. return StackComponents.size() == 1 ||
  1741. std::all_of(
  1742. std::next(StackComponents.rbegin()),
  1743. StackComponents.rend(),
  1744. [](const OMPClauseMappableExprCommon::
  1745. MappableComponent &MC) {
  1746. return MC.getAssociatedDeclaration() ==
  1747. nullptr &&
  1748. (isa<OMPArraySectionExpr>(
  1749. MC.getAssociatedExpression()) ||
  1750. isa<ArraySubscriptExpr>(
  1751. MC.getAssociatedExpression()));
  1752. });
  1753. })) {
  1754. bool IsFirstprivate = false;
  1755. // By default lambdas are captured as firstprivates.
  1756. if (const auto *RD =
  1757. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  1758. IsFirstprivate = RD->isLambda();
  1759. IsFirstprivate =
  1760. IsFirstprivate ||
  1761. (VD->getType().getNonReferenceType()->isScalarType() &&
  1762. Stack->getDefaultDMA() != DMA_tofrom_scalar);
  1763. if (IsFirstprivate)
  1764. ImplicitFirstprivate.emplace_back(E);
  1765. else
  1766. ImplicitMap.emplace_back(E);
  1767. return;
  1768. }
  1769. }
  1770. // OpenMP [2.9.3.6, Restrictions, p.2]
  1771. // A list item that appears in a reduction clause of the innermost
  1772. // enclosing worksharing or parallel construct may not be accessed in an
  1773. // explicit task.
  1774. DVar = Stack->hasInnermostDSA(
  1775. VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1776. [](OpenMPDirectiveKind K) -> bool {
  1777. return isOpenMPParallelDirective(K) ||
  1778. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1779. },
  1780. /*FromParent=*/true);
  1781. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1782. ErrorFound = true;
  1783. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1784. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1785. return;
  1786. }
  1787. // Define implicit data-sharing attributes for task.
  1788. DVar = Stack->getImplicitDSA(VD, false);
  1789. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1790. !Stack->isLoopControlVariable(VD).first)
  1791. ImplicitFirstprivate.push_back(E);
  1792. }
  1793. }
  1794. void VisitMemberExpr(MemberExpr *E) {
  1795. if (E->isTypeDependent() || E->isValueDependent() ||
  1796. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1797. return;
  1798. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  1799. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  1800. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  1801. if (!FD)
  1802. return;
  1803. auto DVar = Stack->getTopDSA(FD, false);
  1804. // Check if the variable has explicit DSA set and stop analysis if it
  1805. // so.
  1806. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  1807. return;
  1808. if (isOpenMPTargetExecutionDirective(DKind) &&
  1809. !Stack->isLoopControlVariable(FD).first &&
  1810. !Stack->checkMappableExprComponentListsForDecl(
  1811. FD, /*CurrentRegionOnly=*/true,
  1812. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1813. StackComponents,
  1814. OpenMPClauseKind) {
  1815. return isa<CXXThisExpr>(
  1816. cast<MemberExpr>(
  1817. StackComponents.back().getAssociatedExpression())
  1818. ->getBase()
  1819. ->IgnoreParens());
  1820. })) {
  1821. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  1822. // A bit-field cannot appear in a map clause.
  1823. //
  1824. if (FD->isBitField())
  1825. return;
  1826. ImplicitMap.emplace_back(E);
  1827. return;
  1828. }
  1829. auto ELoc = E->getExprLoc();
  1830. // OpenMP [2.9.3.6, Restrictions, p.2]
  1831. // A list item that appears in a reduction clause of the innermost
  1832. // enclosing worksharing or parallel construct may not be accessed in
  1833. // an explicit task.
  1834. DVar = Stack->hasInnermostDSA(
  1835. FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1836. [](OpenMPDirectiveKind K) -> bool {
  1837. return isOpenMPParallelDirective(K) ||
  1838. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1839. },
  1840. /*FromParent=*/true);
  1841. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1842. ErrorFound = true;
  1843. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1844. ReportOriginalDSA(SemaRef, Stack, FD, DVar);
  1845. return;
  1846. }
  1847. // Define implicit data-sharing attributes for task.
  1848. DVar = Stack->getImplicitDSA(FD, false);
  1849. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1850. !Stack->isLoopControlVariable(FD).first)
  1851. ImplicitFirstprivate.push_back(E);
  1852. return;
  1853. }
  1854. if (isOpenMPTargetExecutionDirective(DKind)) {
  1855. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  1856. if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  1857. /*NoDiagnose=*/true))
  1858. return;
  1859. auto *VD = cast<ValueDecl>(
  1860. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  1861. if (!Stack->checkMappableExprComponentListsForDecl(
  1862. VD, /*CurrentRegionOnly=*/true,
  1863. [&CurComponents](
  1864. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1865. StackComponents,
  1866. OpenMPClauseKind) {
  1867. auto CCI = CurComponents.rbegin();
  1868. auto CCE = CurComponents.rend();
  1869. for (const auto &SC : llvm::reverse(StackComponents)) {
  1870. // Do both expressions have the same kind?
  1871. if (CCI->getAssociatedExpression()->getStmtClass() !=
  1872. SC.getAssociatedExpression()->getStmtClass())
  1873. if (!(isa<OMPArraySectionExpr>(
  1874. SC.getAssociatedExpression()) &&
  1875. isa<ArraySubscriptExpr>(
  1876. CCI->getAssociatedExpression())))
  1877. return false;
  1878. Decl *CCD = CCI->getAssociatedDeclaration();
  1879. Decl *SCD = SC.getAssociatedDeclaration();
  1880. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  1881. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  1882. if (SCD != CCD)
  1883. return false;
  1884. std::advance(CCI, 1);
  1885. if (CCI == CCE)
  1886. break;
  1887. }
  1888. return true;
  1889. })) {
  1890. Visit(E->getBase());
  1891. }
  1892. } else
  1893. Visit(E->getBase());
  1894. }
  1895. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1896. for (auto *C : S->clauses()) {
  1897. // Skip analysis of arguments of implicitly defined firstprivate clause
  1898. // for task|target directives.
  1899. // Skip analysis of arguments of implicitly defined map clause for target
  1900. // directives.
  1901. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  1902. C->isImplicit())) {
  1903. for (auto *CC : C->children()) {
  1904. if (CC)
  1905. Visit(CC);
  1906. }
  1907. }
  1908. }
  1909. }
  1910. void VisitStmt(Stmt *S) {
  1911. for (auto *C : S->children()) {
  1912. if (C && !isa<OMPExecutableDirective>(C))
  1913. Visit(C);
  1914. }
  1915. }
  1916. bool isErrorFound() { return ErrorFound; }
  1917. ArrayRef<Expr *> getImplicitFirstprivate() const {
  1918. return ImplicitFirstprivate;
  1919. }
  1920. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  1921. llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
  1922. return VarsWithInheritedDSA;
  1923. }
  1924. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1925. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1926. };
  1927. } // namespace
  1928. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1929. switch (DKind) {
  1930. case OMPD_parallel:
  1931. case OMPD_parallel_for:
  1932. case OMPD_parallel_for_simd:
  1933. case OMPD_parallel_sections:
  1934. case OMPD_teams:
  1935. case OMPD_teams_distribute:
  1936. case OMPD_teams_distribute_simd: {
  1937. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1938. QualType KmpInt32PtrTy =
  1939. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1940. Sema::CapturedParamNameType Params[] = {
  1941. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1942. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1943. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1944. };
  1945. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1946. Params);
  1947. break;
  1948. }
  1949. case OMPD_target_teams:
  1950. case OMPD_target_parallel:
  1951. case OMPD_target_parallel_for:
  1952. case OMPD_target_parallel_for_simd:
  1953. case OMPD_target_teams_distribute:
  1954. case OMPD_target_teams_distribute_simd: {
  1955. Sema::CapturedParamNameType ParamsTarget[] = {
  1956. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1957. };
  1958. // Start a captured region for 'target' with no implicit parameters.
  1959. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1960. ParamsTarget);
  1961. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1962. QualType KmpInt32PtrTy =
  1963. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1964. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  1965. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1966. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1967. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1968. };
  1969. // Start a captured region for 'teams' or 'parallel'. Both regions have
  1970. // the same implicit parameters.
  1971. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1972. ParamsTeamsOrParallel);
  1973. break;
  1974. }
  1975. case OMPD_simd:
  1976. case OMPD_for:
  1977. case OMPD_for_simd:
  1978. case OMPD_sections:
  1979. case OMPD_section:
  1980. case OMPD_single:
  1981. case OMPD_master:
  1982. case OMPD_critical:
  1983. case OMPD_taskgroup:
  1984. case OMPD_distribute:
  1985. case OMPD_distribute_simd:
  1986. case OMPD_ordered:
  1987. case OMPD_atomic:
  1988. case OMPD_target_data:
  1989. case OMPD_target:
  1990. case OMPD_target_simd: {
  1991. Sema::CapturedParamNameType Params[] = {
  1992. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1993. };
  1994. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1995. Params);
  1996. break;
  1997. }
  1998. case OMPD_task: {
  1999. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2000. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2001. FunctionProtoType::ExtProtoInfo EPI;
  2002. EPI.Variadic = true;
  2003. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2004. Sema::CapturedParamNameType Params[] = {
  2005. std::make_pair(".global_tid.", KmpInt32Ty),
  2006. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2007. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  2008. std::make_pair(".copy_fn.",
  2009. Context.getPointerType(CopyFnType).withConst()),
  2010. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2011. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2012. };
  2013. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2014. Params);
  2015. // Mark this captured region as inlined, because we don't use outlined
  2016. // function directly.
  2017. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2018. AlwaysInlineAttr::CreateImplicit(
  2019. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2020. break;
  2021. }
  2022. case OMPD_taskloop:
  2023. case OMPD_taskloop_simd: {
  2024. QualType KmpInt32Ty =
  2025. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  2026. QualType KmpUInt64Ty =
  2027. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  2028. QualType KmpInt64Ty =
  2029. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  2030. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2031. FunctionProtoType::ExtProtoInfo EPI;
  2032. EPI.Variadic = true;
  2033. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2034. Sema::CapturedParamNameType Params[] = {
  2035. std::make_pair(".global_tid.", KmpInt32Ty),
  2036. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2037. std::make_pair(".privates.",
  2038. Context.VoidPtrTy.withConst().withRestrict()),
  2039. std::make_pair(
  2040. ".copy_fn.",
  2041. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2042. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2043. std::make_pair(".lb.", KmpUInt64Ty),
  2044. std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
  2045. std::make_pair(".liter.", KmpInt32Ty),
  2046. std::make_pair(".reductions.",
  2047. Context.VoidPtrTy.withConst().withRestrict()),
  2048. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2049. };
  2050. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2051. Params);
  2052. // Mark this captured region as inlined, because we don't use outlined
  2053. // function directly.
  2054. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2055. AlwaysInlineAttr::CreateImplicit(
  2056. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2057. break;
  2058. }
  2059. case OMPD_distribute_parallel_for_simd:
  2060. case OMPD_distribute_parallel_for:
  2061. case OMPD_target_teams_distribute_parallel_for:
  2062. case OMPD_target_teams_distribute_parallel_for_simd: {
  2063. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2064. QualType KmpInt32PtrTy =
  2065. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2066. Sema::CapturedParamNameType Params[] = {
  2067. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2068. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2069. std::make_pair(".previous.lb.", Context.getSizeType()),
  2070. std::make_pair(".previous.ub.", Context.getSizeType()),
  2071. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2072. };
  2073. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2074. Params);
  2075. break;
  2076. }
  2077. case OMPD_teams_distribute_parallel_for:
  2078. case OMPD_teams_distribute_parallel_for_simd: {
  2079. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2080. QualType KmpInt32PtrTy =
  2081. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2082. Sema::CapturedParamNameType ParamsTeams[] = {
  2083. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2084. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2085. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2086. };
  2087. // Start a captured region for 'target' with no implicit parameters.
  2088. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2089. ParamsTeams);
  2090. Sema::CapturedParamNameType ParamsParallel[] = {
  2091. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2092. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2093. std::make_pair(".previous.lb.", Context.getSizeType()),
  2094. std::make_pair(".previous.ub.", Context.getSizeType()),
  2095. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2096. };
  2097. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2098. // the same implicit parameters.
  2099. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2100. ParamsParallel);
  2101. break;
  2102. }
  2103. case OMPD_target_update:
  2104. case OMPD_target_enter_data:
  2105. case OMPD_target_exit_data: {
  2106. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2107. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2108. FunctionProtoType::ExtProtoInfo EPI;
  2109. EPI.Variadic = true;
  2110. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2111. Sema::CapturedParamNameType Params[] = {
  2112. std::make_pair(".global_tid.", KmpInt32Ty),
  2113. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2114. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  2115. std::make_pair(".copy_fn.",
  2116. Context.getPointerType(CopyFnType).withConst()),
  2117. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2118. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2119. };
  2120. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2121. Params);
  2122. // Mark this captured region as inlined, because we don't use outlined
  2123. // function directly.
  2124. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2125. AlwaysInlineAttr::CreateImplicit(
  2126. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2127. break;
  2128. }
  2129. case OMPD_threadprivate:
  2130. case OMPD_taskyield:
  2131. case OMPD_barrier:
  2132. case OMPD_taskwait:
  2133. case OMPD_cancellation_point:
  2134. case OMPD_cancel:
  2135. case OMPD_flush:
  2136. case OMPD_declare_reduction:
  2137. case OMPD_declare_simd:
  2138. case OMPD_declare_target:
  2139. case OMPD_end_declare_target:
  2140. llvm_unreachable("OpenMP Directive is not allowed");
  2141. case OMPD_unknown:
  2142. llvm_unreachable("Unknown OpenMP directive");
  2143. }
  2144. }
  2145. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2146. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2147. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2148. return CaptureRegions.size();
  2149. }
  2150. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2151. Expr *CaptureExpr, bool WithInit,
  2152. bool AsExpression) {
  2153. assert(CaptureExpr);
  2154. ASTContext &C = S.getASTContext();
  2155. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2156. QualType Ty = Init->getType();
  2157. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2158. if (S.getLangOpts().CPlusPlus)
  2159. Ty = C.getLValueReferenceType(Ty);
  2160. else {
  2161. Ty = C.getPointerType(Ty);
  2162. ExprResult Res =
  2163. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2164. if (!Res.isUsable())
  2165. return nullptr;
  2166. Init = Res.get();
  2167. }
  2168. WithInit = true;
  2169. }
  2170. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2171. CaptureExpr->getLocStart());
  2172. if (!WithInit)
  2173. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
  2174. S.CurContext->addHiddenDecl(CED);
  2175. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2176. return CED;
  2177. }
  2178. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2179. bool WithInit) {
  2180. OMPCapturedExprDecl *CD;
  2181. if (auto *VD = S.IsOpenMPCapturedDecl(D))
  2182. CD = cast<OMPCapturedExprDecl>(VD);
  2183. else
  2184. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2185. /*AsExpression=*/false);
  2186. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2187. CaptureExpr->getExprLoc());
  2188. }
  2189. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2190. if (!Ref) {
  2191. auto *CD =
  2192. buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
  2193. CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
  2194. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2195. CaptureExpr->getExprLoc());
  2196. }
  2197. ExprResult Res = Ref;
  2198. if (!S.getLangOpts().CPlusPlus &&
  2199. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2200. Ref->getType()->isPointerType())
  2201. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2202. if (!Res.isUsable())
  2203. return ExprError();
  2204. return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
  2205. }
  2206. namespace {
  2207. // OpenMP directives parsed in this section are represented as a
  2208. // CapturedStatement with an associated statement. If a syntax error
  2209. // is detected during the parsing of the associated statement, the
  2210. // compiler must abort processing and close the CapturedStatement.
  2211. //
  2212. // Combined directives such as 'target parallel' have more than one
  2213. // nested CapturedStatements. This RAII ensures that we unwind out
  2214. // of all the nested CapturedStatements when an error is found.
  2215. class CaptureRegionUnwinderRAII {
  2216. private:
  2217. Sema &S;
  2218. bool &ErrorFound;
  2219. OpenMPDirectiveKind DKind;
  2220. public:
  2221. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2222. OpenMPDirectiveKind DKind)
  2223. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2224. ~CaptureRegionUnwinderRAII() {
  2225. if (ErrorFound) {
  2226. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2227. while (--ThisCaptureLevel >= 0)
  2228. S.ActOnCapturedRegionError();
  2229. }
  2230. }
  2231. };
  2232. } // namespace
  2233. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2234. ArrayRef<OMPClause *> Clauses) {
  2235. bool ErrorFound = false;
  2236. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2237. *this, ErrorFound, DSAStack->getCurrentDirective());
  2238. if (!S.isUsable()) {
  2239. ErrorFound = true;
  2240. return StmtError();
  2241. }
  2242. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2243. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2244. OMPOrderedClause *OC = nullptr;
  2245. OMPScheduleClause *SC = nullptr;
  2246. SmallVector<OMPLinearClause *, 4> LCs;
  2247. SmallVector<OMPClauseWithPreInit *, 8> PICs;
  2248. // This is required for proper codegen.
  2249. for (auto *Clause : Clauses) {
  2250. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2251. Clause->getClauseKind() == OMPC_in_reduction) {
  2252. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2253. // with the corresponding in_reduction items.
  2254. auto *IRC = cast<OMPInReductionClause>(Clause);
  2255. for (auto *E : IRC->taskgroup_descriptors())
  2256. if (E)
  2257. MarkDeclarationsReferencedInExpr(E);
  2258. }
  2259. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2260. Clause->getClauseKind() == OMPC_copyprivate ||
  2261. (getLangOpts().OpenMPUseTLS &&
  2262. getASTContext().getTargetInfo().isTLSSupported() &&
  2263. Clause->getClauseKind() == OMPC_copyin)) {
  2264. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2265. // Mark all variables in private list clauses as used in inner region.
  2266. for (auto *VarRef : Clause->children()) {
  2267. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2268. MarkDeclarationsReferencedInExpr(E);
  2269. }
  2270. }
  2271. DSAStack->setForceVarCapturing(/*V=*/false);
  2272. } else if (CaptureRegions.size() > 1 ||
  2273. CaptureRegions.back() != OMPD_unknown) {
  2274. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2275. PICs.push_back(C);
  2276. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2277. if (auto *E = C->getPostUpdateExpr())
  2278. MarkDeclarationsReferencedInExpr(E);
  2279. }
  2280. }
  2281. if (Clause->getClauseKind() == OMPC_schedule)
  2282. SC = cast<OMPScheduleClause>(Clause);
  2283. else if (Clause->getClauseKind() == OMPC_ordered)
  2284. OC = cast<OMPOrderedClause>(Clause);
  2285. else if (Clause->getClauseKind() == OMPC_linear)
  2286. LCs.push_back(cast<OMPLinearClause>(Clause));
  2287. }
  2288. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2289. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2290. // specified.
  2291. if (SC &&
  2292. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2293. SC->getSecondScheduleModifier() ==
  2294. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2295. OC) {
  2296. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2297. ? SC->getFirstScheduleModifierLoc()
  2298. : SC->getSecondScheduleModifierLoc(),
  2299. diag::err_omp_schedule_nonmonotonic_ordered)
  2300. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2301. ErrorFound = true;
  2302. }
  2303. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2304. for (auto *C : LCs) {
  2305. Diag(C->getLocStart(), diag::err_omp_linear_ordered)
  2306. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2307. }
  2308. ErrorFound = true;
  2309. }
  2310. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2311. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2312. OC->getNumForLoops()) {
  2313. Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
  2314. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2315. ErrorFound = true;
  2316. }
  2317. if (ErrorFound) {
  2318. return StmtError();
  2319. }
  2320. StmtResult SR = S;
  2321. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2322. // Mark all variables in private list clauses as used in inner region.
  2323. // Required for proper codegen of combined directives.
  2324. // TODO: add processing for other clauses.
  2325. if (ThisCaptureRegion != OMPD_unknown) {
  2326. for (auto *C : PICs) {
  2327. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2328. // Find the particular capture region for the clause if the
  2329. // directive is a combined one with multiple capture regions.
  2330. // If the directive is not a combined one, the capture region
  2331. // associated with the clause is OMPD_unknown and is generated
  2332. // only once.
  2333. if (CaptureRegion == ThisCaptureRegion ||
  2334. CaptureRegion == OMPD_unknown) {
  2335. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2336. for (auto *D : DS->decls())
  2337. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2338. }
  2339. }
  2340. }
  2341. }
  2342. SR = ActOnCapturedRegionEnd(SR.get());
  2343. }
  2344. return SR;
  2345. }
  2346. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2347. OpenMPDirectiveKind CancelRegion,
  2348. SourceLocation StartLoc) {
  2349. // CancelRegion is only needed for cancel and cancellation_point.
  2350. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2351. return false;
  2352. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2353. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2354. return false;
  2355. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2356. << getOpenMPDirectiveName(CancelRegion);
  2357. return true;
  2358. }
  2359. static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  2360. OpenMPDirectiveKind CurrentRegion,
  2361. const DeclarationNameInfo &CurrentName,
  2362. OpenMPDirectiveKind CancelRegion,
  2363. SourceLocation StartLoc) {
  2364. if (Stack->getCurScope()) {
  2365. auto ParentRegion = Stack->getParentDirective();
  2366. auto OffendingRegion = ParentRegion;
  2367. bool NestingProhibited = false;
  2368. bool CloseNesting = true;
  2369. bool OrphanSeen = false;
  2370. enum {
  2371. NoRecommend,
  2372. ShouldBeInParallelRegion,
  2373. ShouldBeInOrderedRegion,
  2374. ShouldBeInTargetRegion,
  2375. ShouldBeInTeamsRegion
  2376. } Recommend = NoRecommend;
  2377. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2378. // OpenMP [2.16, Nesting of Regions]
  2379. // OpenMP constructs may not be nested inside a simd region.
  2380. // OpenMP [2.8.1,simd Construct, Restrictions]
  2381. // An ordered construct with the simd clause is the only OpenMP
  2382. // construct that can appear in the simd region.
  2383. // Allowing a SIMD construct nested in another SIMD construct is an
  2384. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2385. // message.
  2386. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2387. ? diag::err_omp_prohibited_region_simd
  2388. : diag::warn_omp_nesting_simd);
  2389. return CurrentRegion != OMPD_simd;
  2390. }
  2391. if (ParentRegion == OMPD_atomic) {
  2392. // OpenMP [2.16, Nesting of Regions]
  2393. // OpenMP constructs may not be nested inside an atomic region.
  2394. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2395. return true;
  2396. }
  2397. if (CurrentRegion == OMPD_section) {
  2398. // OpenMP [2.7.2, sections Construct, Restrictions]
  2399. // Orphaned section directives are prohibited. That is, the section
  2400. // directives must appear within the sections construct and must not be
  2401. // encountered elsewhere in the sections region.
  2402. if (ParentRegion != OMPD_sections &&
  2403. ParentRegion != OMPD_parallel_sections) {
  2404. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2405. << (ParentRegion != OMPD_unknown)
  2406. << getOpenMPDirectiveName(ParentRegion);
  2407. return true;
  2408. }
  2409. return false;
  2410. }
  2411. // Allow some constructs (except teams) to be orphaned (they could be
  2412. // used in functions, called from OpenMP regions with the required
  2413. // preconditions).
  2414. if (ParentRegion == OMPD_unknown &&
  2415. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2416. return false;
  2417. if (CurrentRegion == OMPD_cancellation_point ||
  2418. CurrentRegion == OMPD_cancel) {
  2419. // OpenMP [2.16, Nesting of Regions]
  2420. // A cancellation point construct for which construct-type-clause is
  2421. // taskgroup must be nested inside a task construct. A cancellation
  2422. // point construct for which construct-type-clause is not taskgroup must
  2423. // be closely nested inside an OpenMP construct that matches the type
  2424. // specified in construct-type-clause.
  2425. // A cancel construct for which construct-type-clause is taskgroup must be
  2426. // nested inside a task construct. A cancel construct for which
  2427. // construct-type-clause is not taskgroup must be closely nested inside an
  2428. // OpenMP construct that matches the type specified in
  2429. // construct-type-clause.
  2430. NestingProhibited =
  2431. !((CancelRegion == OMPD_parallel &&
  2432. (ParentRegion == OMPD_parallel ||
  2433. ParentRegion == OMPD_target_parallel)) ||
  2434. (CancelRegion == OMPD_for &&
  2435. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2436. ParentRegion == OMPD_target_parallel_for ||
  2437. ParentRegion == OMPD_distribute_parallel_for ||
  2438. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2439. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2440. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2441. (CancelRegion == OMPD_sections &&
  2442. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2443. ParentRegion == OMPD_parallel_sections)));
  2444. } else if (CurrentRegion == OMPD_master) {
  2445. // OpenMP [2.16, Nesting of Regions]
  2446. // A master region may not be closely nested inside a worksharing,
  2447. // atomic, or explicit task region.
  2448. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2449. isOpenMPTaskingDirective(ParentRegion);
  2450. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2451. // OpenMP [2.16, Nesting of Regions]
  2452. // A critical region may not be nested (closely or otherwise) inside a
  2453. // critical region with the same name. Note that this restriction is not
  2454. // sufficient to prevent deadlock.
  2455. SourceLocation PreviousCriticalLoc;
  2456. bool DeadLock = Stack->hasDirective(
  2457. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2458. const DeclarationNameInfo &DNI,
  2459. SourceLocation Loc) -> bool {
  2460. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2461. PreviousCriticalLoc = Loc;
  2462. return true;
  2463. } else
  2464. return false;
  2465. },
  2466. false /* skip top directive */);
  2467. if (DeadLock) {
  2468. SemaRef.Diag(StartLoc,
  2469. diag::err_omp_prohibited_region_critical_same_name)
  2470. << CurrentName.getName();
  2471. if (PreviousCriticalLoc.isValid())
  2472. SemaRef.Diag(PreviousCriticalLoc,
  2473. diag::note_omp_previous_critical_region);
  2474. return true;
  2475. }
  2476. } else if (CurrentRegion == OMPD_barrier) {
  2477. // OpenMP [2.16, Nesting of Regions]
  2478. // A barrier region may not be closely nested inside a worksharing,
  2479. // explicit task, critical, ordered, atomic, or master region.
  2480. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2481. isOpenMPTaskingDirective(ParentRegion) ||
  2482. ParentRegion == OMPD_master ||
  2483. ParentRegion == OMPD_critical ||
  2484. ParentRegion == OMPD_ordered;
  2485. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2486. !isOpenMPParallelDirective(CurrentRegion) &&
  2487. !isOpenMPTeamsDirective(CurrentRegion)) {
  2488. // OpenMP [2.16, Nesting of Regions]
  2489. // A worksharing region may not be closely nested inside a worksharing,
  2490. // explicit task, critical, ordered, atomic, or master region.
  2491. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2492. isOpenMPTaskingDirective(ParentRegion) ||
  2493. ParentRegion == OMPD_master ||
  2494. ParentRegion == OMPD_critical ||
  2495. ParentRegion == OMPD_ordered;
  2496. Recommend = ShouldBeInParallelRegion;
  2497. } else if (CurrentRegion == OMPD_ordered) {
  2498. // OpenMP [2.16, Nesting of Regions]
  2499. // An ordered region may not be closely nested inside a critical,
  2500. // atomic, or explicit task region.
  2501. // An ordered region must be closely nested inside a loop region (or
  2502. // parallel loop region) with an ordered clause.
  2503. // OpenMP [2.8.1,simd Construct, Restrictions]
  2504. // An ordered construct with the simd clause is the only OpenMP construct
  2505. // that can appear in the simd region.
  2506. NestingProhibited = ParentRegion == OMPD_critical ||
  2507. isOpenMPTaskingDirective(ParentRegion) ||
  2508. !(isOpenMPSimdDirective(ParentRegion) ||
  2509. Stack->isParentOrderedRegion());
  2510. Recommend = ShouldBeInOrderedRegion;
  2511. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2512. // OpenMP [2.16, Nesting of Regions]
  2513. // If specified, a teams construct must be contained within a target
  2514. // construct.
  2515. NestingProhibited = ParentRegion != OMPD_target;
  2516. OrphanSeen = ParentRegion == OMPD_unknown;
  2517. Recommend = ShouldBeInTargetRegion;
  2518. }
  2519. if (!NestingProhibited &&
  2520. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2521. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2522. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2523. // OpenMP [2.16, Nesting of Regions]
  2524. // distribute, parallel, parallel sections, parallel workshare, and the
  2525. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2526. // constructs that can be closely nested in the teams region.
  2527. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2528. !isOpenMPDistributeDirective(CurrentRegion);
  2529. Recommend = ShouldBeInParallelRegion;
  2530. }
  2531. if (!NestingProhibited &&
  2532. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2533. // OpenMP 4.5 [2.17 Nesting of Regions]
  2534. // The region associated with the distribute construct must be strictly
  2535. // nested inside a teams region
  2536. NestingProhibited =
  2537. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2538. Recommend = ShouldBeInTeamsRegion;
  2539. }
  2540. if (!NestingProhibited &&
  2541. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2542. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2543. // OpenMP 4.5 [2.17 Nesting of Regions]
  2544. // If a target, target update, target data, target enter data, or
  2545. // target exit data construct is encountered during execution of a
  2546. // target region, the behavior is unspecified.
  2547. NestingProhibited = Stack->hasDirective(
  2548. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2549. SourceLocation) -> bool {
  2550. if (isOpenMPTargetExecutionDirective(K)) {
  2551. OffendingRegion = K;
  2552. return true;
  2553. } else
  2554. return false;
  2555. },
  2556. false /* don't skip top directive */);
  2557. CloseNesting = false;
  2558. }
  2559. if (NestingProhibited) {
  2560. if (OrphanSeen) {
  2561. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2562. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2563. } else {
  2564. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2565. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  2566. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  2567. }
  2568. return true;
  2569. }
  2570. }
  2571. return false;
  2572. }
  2573. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  2574. ArrayRef<OMPClause *> Clauses,
  2575. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  2576. bool ErrorFound = false;
  2577. unsigned NamedModifiersNumber = 0;
  2578. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  2579. OMPD_unknown + 1);
  2580. SmallVector<SourceLocation, 4> NameModifierLoc;
  2581. for (const auto *C : Clauses) {
  2582. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  2583. // At most one if clause without a directive-name-modifier can appear on
  2584. // the directive.
  2585. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  2586. if (FoundNameModifiers[CurNM]) {
  2587. S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  2588. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  2589. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  2590. ErrorFound = true;
  2591. } else if (CurNM != OMPD_unknown) {
  2592. NameModifierLoc.push_back(IC->getNameModifierLoc());
  2593. ++NamedModifiersNumber;
  2594. }
  2595. FoundNameModifiers[CurNM] = IC;
  2596. if (CurNM == OMPD_unknown)
  2597. continue;
  2598. // Check if the specified name modifier is allowed for the current
  2599. // directive.
  2600. // At most one if clause with the particular directive-name-modifier can
  2601. // appear on the directive.
  2602. bool MatchFound = false;
  2603. for (auto NM : AllowedNameModifiers) {
  2604. if (CurNM == NM) {
  2605. MatchFound = true;
  2606. break;
  2607. }
  2608. }
  2609. if (!MatchFound) {
  2610. S.Diag(IC->getNameModifierLoc(),
  2611. diag::err_omp_wrong_if_directive_name_modifier)
  2612. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  2613. ErrorFound = true;
  2614. }
  2615. }
  2616. }
  2617. // If any if clause on the directive includes a directive-name-modifier then
  2618. // all if clauses on the directive must include a directive-name-modifier.
  2619. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  2620. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  2621. S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
  2622. diag::err_omp_no_more_if_clause);
  2623. } else {
  2624. std::string Values;
  2625. std::string Sep(", ");
  2626. unsigned AllowedCnt = 0;
  2627. unsigned TotalAllowedNum =
  2628. AllowedNameModifiers.size() - NamedModifiersNumber;
  2629. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  2630. ++Cnt) {
  2631. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  2632. if (!FoundNameModifiers[NM]) {
  2633. Values += "'";
  2634. Values += getOpenMPDirectiveName(NM);
  2635. Values += "'";
  2636. if (AllowedCnt + 2 == TotalAllowedNum)
  2637. Values += " or ";
  2638. else if (AllowedCnt + 1 != TotalAllowedNum)
  2639. Values += Sep;
  2640. ++AllowedCnt;
  2641. }
  2642. }
  2643. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
  2644. diag::err_omp_unnamed_if_clause)
  2645. << (TotalAllowedNum > 1) << Values;
  2646. }
  2647. for (auto Loc : NameModifierLoc) {
  2648. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  2649. }
  2650. ErrorFound = true;
  2651. }
  2652. return ErrorFound;
  2653. }
  2654. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2655. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2656. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2657. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2658. StmtResult Res = StmtError();
  2659. // First check CancelRegion which is then used in checkNestingOfRegions.
  2660. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  2661. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2662. StartLoc))
  2663. return StmtError();
  2664. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2665. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  2666. bool ErrorFound = false;
  2667. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2668. if (AStmt && !CurContext->isDependentContext()) {
  2669. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2670. // Check default data sharing attributes for referenced variables.
  2671. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2672. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  2673. Stmt *S = AStmt;
  2674. while (--ThisCaptureLevel >= 0)
  2675. S = cast<CapturedStmt>(S)->getCapturedStmt();
  2676. DSAChecker.Visit(S);
  2677. if (DSAChecker.isErrorFound())
  2678. return StmtError();
  2679. // Generate list of implicitly defined firstprivate variables.
  2680. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2681. SmallVector<Expr *, 4> ImplicitFirstprivates(
  2682. DSAChecker.getImplicitFirstprivate().begin(),
  2683. DSAChecker.getImplicitFirstprivate().end());
  2684. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  2685. DSAChecker.getImplicitMap().end());
  2686. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  2687. for (auto *C : Clauses) {
  2688. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  2689. for (auto *E : IRC->taskgroup_descriptors())
  2690. if (E)
  2691. ImplicitFirstprivates.emplace_back(E);
  2692. }
  2693. }
  2694. if (!ImplicitFirstprivates.empty()) {
  2695. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2696. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  2697. SourceLocation())) {
  2698. ClausesWithImplicit.push_back(Implicit);
  2699. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2700. ImplicitFirstprivates.size();
  2701. } else
  2702. ErrorFound = true;
  2703. }
  2704. if (!ImplicitMaps.empty()) {
  2705. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  2706. OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
  2707. SourceLocation(), SourceLocation(), ImplicitMaps,
  2708. SourceLocation(), SourceLocation(), SourceLocation())) {
  2709. ClausesWithImplicit.emplace_back(Implicit);
  2710. ErrorFound |=
  2711. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  2712. } else
  2713. ErrorFound = true;
  2714. }
  2715. }
  2716. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  2717. switch (Kind) {
  2718. case OMPD_parallel:
  2719. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2720. EndLoc);
  2721. AllowedNameModifiers.push_back(OMPD_parallel);
  2722. break;
  2723. case OMPD_simd:
  2724. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2725. VarsWithInheritedDSA);
  2726. break;
  2727. case OMPD_for:
  2728. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2729. VarsWithInheritedDSA);
  2730. break;
  2731. case OMPD_for_simd:
  2732. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2733. EndLoc, VarsWithInheritedDSA);
  2734. break;
  2735. case OMPD_sections:
  2736. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2737. EndLoc);
  2738. break;
  2739. case OMPD_section:
  2740. assert(ClausesWithImplicit.empty() &&
  2741. "No clauses are allowed for 'omp section' directive");
  2742. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2743. break;
  2744. case OMPD_single:
  2745. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2746. EndLoc);
  2747. break;
  2748. case OMPD_master:
  2749. assert(ClausesWithImplicit.empty() &&
  2750. "No clauses are allowed for 'omp master' directive");
  2751. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2752. break;
  2753. case OMPD_critical:
  2754. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  2755. StartLoc, EndLoc);
  2756. break;
  2757. case OMPD_parallel_for:
  2758. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2759. EndLoc, VarsWithInheritedDSA);
  2760. AllowedNameModifiers.push_back(OMPD_parallel);
  2761. break;
  2762. case OMPD_parallel_for_simd:
  2763. Res = ActOnOpenMPParallelForSimdDirective(
  2764. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2765. AllowedNameModifiers.push_back(OMPD_parallel);
  2766. break;
  2767. case OMPD_parallel_sections:
  2768. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2769. StartLoc, EndLoc);
  2770. AllowedNameModifiers.push_back(OMPD_parallel);
  2771. break;
  2772. case OMPD_task:
  2773. Res =
  2774. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2775. AllowedNameModifiers.push_back(OMPD_task);
  2776. break;
  2777. case OMPD_taskyield:
  2778. assert(ClausesWithImplicit.empty() &&
  2779. "No clauses are allowed for 'omp taskyield' directive");
  2780. assert(AStmt == nullptr &&
  2781. "No associated statement allowed for 'omp taskyield' directive");
  2782. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2783. break;
  2784. case OMPD_barrier:
  2785. assert(ClausesWithImplicit.empty() &&
  2786. "No clauses are allowed for 'omp barrier' directive");
  2787. assert(AStmt == nullptr &&
  2788. "No associated statement allowed for 'omp barrier' directive");
  2789. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2790. break;
  2791. case OMPD_taskwait:
  2792. assert(ClausesWithImplicit.empty() &&
  2793. "No clauses are allowed for 'omp taskwait' directive");
  2794. assert(AStmt == nullptr &&
  2795. "No associated statement allowed for 'omp taskwait' directive");
  2796. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2797. break;
  2798. case OMPD_taskgroup:
  2799. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  2800. EndLoc);
  2801. break;
  2802. case OMPD_flush:
  2803. assert(AStmt == nullptr &&
  2804. "No associated statement allowed for 'omp flush' directive");
  2805. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2806. break;
  2807. case OMPD_ordered:
  2808. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  2809. EndLoc);
  2810. break;
  2811. case OMPD_atomic:
  2812. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2813. EndLoc);
  2814. break;
  2815. case OMPD_teams:
  2816. Res =
  2817. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2818. break;
  2819. case OMPD_target:
  2820. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2821. EndLoc);
  2822. AllowedNameModifiers.push_back(OMPD_target);
  2823. break;
  2824. case OMPD_target_parallel:
  2825. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  2826. StartLoc, EndLoc);
  2827. AllowedNameModifiers.push_back(OMPD_target);
  2828. AllowedNameModifiers.push_back(OMPD_parallel);
  2829. break;
  2830. case OMPD_target_parallel_for:
  2831. Res = ActOnOpenMPTargetParallelForDirective(
  2832. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2833. AllowedNameModifiers.push_back(OMPD_target);
  2834. AllowedNameModifiers.push_back(OMPD_parallel);
  2835. break;
  2836. case OMPD_cancellation_point:
  2837. assert(ClausesWithImplicit.empty() &&
  2838. "No clauses are allowed for 'omp cancellation point' directive");
  2839. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2840. "cancellation point' directive");
  2841. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2842. break;
  2843. case OMPD_cancel:
  2844. assert(AStmt == nullptr &&
  2845. "No associated statement allowed for 'omp cancel' directive");
  2846. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  2847. CancelRegion);
  2848. AllowedNameModifiers.push_back(OMPD_cancel);
  2849. break;
  2850. case OMPD_target_data:
  2851. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  2852. EndLoc);
  2853. AllowedNameModifiers.push_back(OMPD_target_data);
  2854. break;
  2855. case OMPD_target_enter_data:
  2856. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  2857. EndLoc, AStmt);
  2858. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  2859. break;
  2860. case OMPD_target_exit_data:
  2861. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  2862. EndLoc, AStmt);
  2863. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  2864. break;
  2865. case OMPD_taskloop:
  2866. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  2867. EndLoc, VarsWithInheritedDSA);
  2868. AllowedNameModifiers.push_back(OMPD_taskloop);
  2869. break;
  2870. case OMPD_taskloop_simd:
  2871. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2872. EndLoc, VarsWithInheritedDSA);
  2873. AllowedNameModifiers.push_back(OMPD_taskloop);
  2874. break;
  2875. case OMPD_distribute:
  2876. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  2877. EndLoc, VarsWithInheritedDSA);
  2878. break;
  2879. case OMPD_target_update:
  2880. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  2881. EndLoc, AStmt);
  2882. AllowedNameModifiers.push_back(OMPD_target_update);
  2883. break;
  2884. case OMPD_distribute_parallel_for:
  2885. Res = ActOnOpenMPDistributeParallelForDirective(
  2886. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2887. AllowedNameModifiers.push_back(OMPD_parallel);
  2888. break;
  2889. case OMPD_distribute_parallel_for_simd:
  2890. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  2891. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2892. AllowedNameModifiers.push_back(OMPD_parallel);
  2893. break;
  2894. case OMPD_distribute_simd:
  2895. Res = ActOnOpenMPDistributeSimdDirective(
  2896. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2897. break;
  2898. case OMPD_target_parallel_for_simd:
  2899. Res = ActOnOpenMPTargetParallelForSimdDirective(
  2900. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2901. AllowedNameModifiers.push_back(OMPD_target);
  2902. AllowedNameModifiers.push_back(OMPD_parallel);
  2903. break;
  2904. case OMPD_target_simd:
  2905. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2906. EndLoc, VarsWithInheritedDSA);
  2907. AllowedNameModifiers.push_back(OMPD_target);
  2908. break;
  2909. case OMPD_teams_distribute:
  2910. Res = ActOnOpenMPTeamsDistributeDirective(
  2911. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2912. break;
  2913. case OMPD_teams_distribute_simd:
  2914. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  2915. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2916. break;
  2917. case OMPD_teams_distribute_parallel_for_simd:
  2918. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  2919. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2920. AllowedNameModifiers.push_back(OMPD_parallel);
  2921. break;
  2922. case OMPD_teams_distribute_parallel_for:
  2923. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  2924. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2925. AllowedNameModifiers.push_back(OMPD_parallel);
  2926. break;
  2927. case OMPD_target_teams:
  2928. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2929. EndLoc);
  2930. AllowedNameModifiers.push_back(OMPD_target);
  2931. break;
  2932. case OMPD_target_teams_distribute:
  2933. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  2934. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2935. AllowedNameModifiers.push_back(OMPD_target);
  2936. break;
  2937. case OMPD_target_teams_distribute_parallel_for:
  2938. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  2939. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2940. AllowedNameModifiers.push_back(OMPD_target);
  2941. AllowedNameModifiers.push_back(OMPD_parallel);
  2942. break;
  2943. case OMPD_target_teams_distribute_parallel_for_simd:
  2944. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  2945. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2946. AllowedNameModifiers.push_back(OMPD_target);
  2947. AllowedNameModifiers.push_back(OMPD_parallel);
  2948. break;
  2949. case OMPD_target_teams_distribute_simd:
  2950. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  2951. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2952. AllowedNameModifiers.push_back(OMPD_target);
  2953. break;
  2954. case OMPD_declare_target:
  2955. case OMPD_end_declare_target:
  2956. case OMPD_threadprivate:
  2957. case OMPD_declare_reduction:
  2958. case OMPD_declare_simd:
  2959. llvm_unreachable("OpenMP Directive is not allowed");
  2960. case OMPD_unknown:
  2961. llvm_unreachable("Unknown OpenMP directive");
  2962. }
  2963. for (auto P : VarsWithInheritedDSA) {
  2964. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2965. << P.first << P.second->getSourceRange();
  2966. }
  2967. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  2968. if (!AllowedNameModifiers.empty())
  2969. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  2970. ErrorFound;
  2971. if (ErrorFound)
  2972. return StmtError();
  2973. return Res;
  2974. }
  2975. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  2976. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  2977. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  2978. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  2979. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  2980. assert(Aligneds.size() == Alignments.size());
  2981. assert(Linears.size() == LinModifiers.size());
  2982. assert(Linears.size() == Steps.size());
  2983. if (!DG || DG.get().isNull())
  2984. return DeclGroupPtrTy();
  2985. if (!DG.get().isSingleDecl()) {
  2986. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  2987. return DG;
  2988. }
  2989. auto *ADecl = DG.get().getSingleDecl();
  2990. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  2991. ADecl = FTD->getTemplatedDecl();
  2992. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  2993. if (!FD) {
  2994. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  2995. return DeclGroupPtrTy();
  2996. }
  2997. // OpenMP [2.8.2, declare simd construct, Description]
  2998. // The parameter of the simdlen clause must be a constant positive integer
  2999. // expression.
  3000. ExprResult SL;
  3001. if (Simdlen)
  3002. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3003. // OpenMP [2.8.2, declare simd construct, Description]
  3004. // The special this pointer can be used as if was one of the arguments to the
  3005. // function in any of the linear, aligned, or uniform clauses.
  3006. // The uniform clause declares one or more arguments to have an invariant
  3007. // value for all concurrent invocations of the function in the execution of a
  3008. // single SIMD loop.
  3009. llvm::DenseMap<Decl *, Expr *> UniformedArgs;
  3010. Expr *UniformedLinearThis = nullptr;
  3011. for (auto *E : Uniforms) {
  3012. E = E->IgnoreParenImpCasts();
  3013. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3014. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3015. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3016. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3017. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3018. UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
  3019. continue;
  3020. }
  3021. if (isa<CXXThisExpr>(E)) {
  3022. UniformedLinearThis = E;
  3023. continue;
  3024. }
  3025. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3026. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3027. }
  3028. // OpenMP [2.8.2, declare simd construct, Description]
  3029. // The aligned clause declares that the object to which each list item points
  3030. // is aligned to the number of bytes expressed in the optional parameter of
  3031. // the aligned clause.
  3032. // The special this pointer can be used as if was one of the arguments to the
  3033. // function in any of the linear, aligned, or uniform clauses.
  3034. // The type of list items appearing in the aligned clause must be array,
  3035. // pointer, reference to array, or reference to pointer.
  3036. llvm::DenseMap<Decl *, Expr *> AlignedArgs;
  3037. Expr *AlignedThis = nullptr;
  3038. for (auto *E : Aligneds) {
  3039. E = E->IgnoreParenImpCasts();
  3040. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3041. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3042. auto *CanonPVD = PVD->getCanonicalDecl();
  3043. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3044. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3045. ->getCanonicalDecl() == CanonPVD) {
  3046. // OpenMP [2.8.1, simd construct, Restrictions]
  3047. // A list-item cannot appear in more than one aligned clause.
  3048. if (AlignedArgs.count(CanonPVD) > 0) {
  3049. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3050. << 1 << E->getSourceRange();
  3051. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3052. diag::note_omp_explicit_dsa)
  3053. << getOpenMPClauseName(OMPC_aligned);
  3054. continue;
  3055. }
  3056. AlignedArgs[CanonPVD] = E;
  3057. QualType QTy = PVD->getType()
  3058. .getNonReferenceType()
  3059. .getUnqualifiedType()
  3060. .getCanonicalType();
  3061. const Type *Ty = QTy.getTypePtrOrNull();
  3062. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3063. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3064. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3065. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3066. }
  3067. continue;
  3068. }
  3069. }
  3070. if (isa<CXXThisExpr>(E)) {
  3071. if (AlignedThis) {
  3072. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3073. << 2 << E->getSourceRange();
  3074. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3075. << getOpenMPClauseName(OMPC_aligned);
  3076. }
  3077. AlignedThis = E;
  3078. continue;
  3079. }
  3080. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3081. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3082. }
  3083. // The optional parameter of the aligned clause, alignment, must be a constant
  3084. // positive integer expression. If no optional parameter is specified,
  3085. // implementation-defined default alignments for SIMD instructions on the
  3086. // target platforms are assumed.
  3087. SmallVector<Expr *, 4> NewAligns;
  3088. for (auto *E : Alignments) {
  3089. ExprResult Align;
  3090. if (E)
  3091. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3092. NewAligns.push_back(Align.get());
  3093. }
  3094. // OpenMP [2.8.2, declare simd construct, Description]
  3095. // The linear clause declares one or more list items to be private to a SIMD
  3096. // lane and to have a linear relationship with respect to the iteration space
  3097. // of a loop.
  3098. // The special this pointer can be used as if was one of the arguments to the
  3099. // function in any of the linear, aligned, or uniform clauses.
  3100. // When a linear-step expression is specified in a linear clause it must be
  3101. // either a constant integer expression or an integer-typed parameter that is
  3102. // specified in a uniform clause on the directive.
  3103. llvm::DenseMap<Decl *, Expr *> LinearArgs;
  3104. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3105. auto MI = LinModifiers.begin();
  3106. for (auto *E : Linears) {
  3107. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3108. ++MI;
  3109. E = E->IgnoreParenImpCasts();
  3110. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3111. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3112. auto *CanonPVD = PVD->getCanonicalDecl();
  3113. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3114. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3115. ->getCanonicalDecl() == CanonPVD) {
  3116. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3117. // A list-item cannot appear in more than one linear clause.
  3118. if (LinearArgs.count(CanonPVD) > 0) {
  3119. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3120. << getOpenMPClauseName(OMPC_linear)
  3121. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3122. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3123. diag::note_omp_explicit_dsa)
  3124. << getOpenMPClauseName(OMPC_linear);
  3125. continue;
  3126. }
  3127. // Each argument can appear in at most one uniform or linear clause.
  3128. if (UniformedArgs.count(CanonPVD) > 0) {
  3129. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3130. << getOpenMPClauseName(OMPC_linear)
  3131. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3132. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3133. diag::note_omp_explicit_dsa)
  3134. << getOpenMPClauseName(OMPC_uniform);
  3135. continue;
  3136. }
  3137. LinearArgs[CanonPVD] = E;
  3138. if (E->isValueDependent() || E->isTypeDependent() ||
  3139. E->isInstantiationDependent() ||
  3140. E->containsUnexpandedParameterPack())
  3141. continue;
  3142. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3143. PVD->getOriginalType());
  3144. continue;
  3145. }
  3146. }
  3147. if (isa<CXXThisExpr>(E)) {
  3148. if (UniformedLinearThis) {
  3149. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3150. << getOpenMPClauseName(OMPC_linear)
  3151. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3152. << E->getSourceRange();
  3153. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3154. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3155. : OMPC_linear);
  3156. continue;
  3157. }
  3158. UniformedLinearThis = E;
  3159. if (E->isValueDependent() || E->isTypeDependent() ||
  3160. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3161. continue;
  3162. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3163. E->getType());
  3164. continue;
  3165. }
  3166. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3167. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3168. }
  3169. Expr *Step = nullptr;
  3170. Expr *NewStep = nullptr;
  3171. SmallVector<Expr *, 4> NewSteps;
  3172. for (auto *E : Steps) {
  3173. // Skip the same step expression, it was checked already.
  3174. if (Step == E || !E) {
  3175. NewSteps.push_back(E ? NewStep : nullptr);
  3176. continue;
  3177. }
  3178. Step = E;
  3179. if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3180. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3181. auto *CanonPVD = PVD->getCanonicalDecl();
  3182. if (UniformedArgs.count(CanonPVD) == 0) {
  3183. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3184. << Step->getSourceRange();
  3185. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3186. E->isInstantiationDependent() ||
  3187. E->containsUnexpandedParameterPack() ||
  3188. CanonPVD->getType()->hasIntegerRepresentation())
  3189. NewSteps.push_back(Step);
  3190. else {
  3191. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3192. << Step->getSourceRange();
  3193. }
  3194. continue;
  3195. }
  3196. NewStep = Step;
  3197. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3198. !Step->isInstantiationDependent() &&
  3199. !Step->containsUnexpandedParameterPack()) {
  3200. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3201. .get();
  3202. if (NewStep)
  3203. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3204. }
  3205. NewSteps.push_back(NewStep);
  3206. }
  3207. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3208. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3209. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3210. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3211. const_cast<Expr **>(Linears.data()), Linears.size(),
  3212. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3213. NewSteps.data(), NewSteps.size(), SR);
  3214. ADecl->addAttr(NewAttr);
  3215. return ConvertDeclToDeclGroup(ADecl);
  3216. }
  3217. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3218. Stmt *AStmt,
  3219. SourceLocation StartLoc,
  3220. SourceLocation EndLoc) {
  3221. if (!AStmt)
  3222. return StmtError();
  3223. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3224. // 1.2.2 OpenMP Language Terminology
  3225. // Structured block - An executable statement with a single entry at the
  3226. // top and a single exit at the bottom.
  3227. // The point of exit cannot be a branch out of the structured block.
  3228. // longjmp() and throw() must not violate the entry/exit criteria.
  3229. CS->getCapturedDecl()->setNothrow();
  3230. getCurFunction()->setHasBranchProtectedScope();
  3231. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3232. DSAStack->isCancelRegion());
  3233. }
  3234. namespace {
  3235. /// \brief Helper class for checking canonical form of the OpenMP loops and
  3236. /// extracting iteration space of each loop in the loop nest, that will be used
  3237. /// for IR generation.
  3238. class OpenMPIterationSpaceChecker {
  3239. /// \brief Reference to Sema.
  3240. Sema &SemaRef;
  3241. /// \brief A location for diagnostics (when there is no some better location).
  3242. SourceLocation DefaultLoc;
  3243. /// \brief A location for diagnostics (when increment is not compatible).
  3244. SourceLocation ConditionLoc;
  3245. /// \brief A source location for referring to loop init later.
  3246. SourceRange InitSrcRange;
  3247. /// \brief A source location for referring to condition later.
  3248. SourceRange ConditionSrcRange;
  3249. /// \brief A source location for referring to increment later.
  3250. SourceRange IncrementSrcRange;
  3251. /// \brief Loop variable.
  3252. ValueDecl *LCDecl = nullptr;
  3253. /// \brief Reference to loop variable.
  3254. Expr *LCRef = nullptr;
  3255. /// \brief Lower bound (initializer for the var).
  3256. Expr *LB = nullptr;
  3257. /// \brief Upper bound.
  3258. Expr *UB = nullptr;
  3259. /// \brief Loop step (increment).
  3260. Expr *Step = nullptr;
  3261. /// \brief This flag is true when condition is one of:
  3262. /// Var < UB
  3263. /// Var <= UB
  3264. /// UB > Var
  3265. /// UB >= Var
  3266. bool TestIsLessOp = false;
  3267. /// \brief This flag is true when condition is strict ( < or > ).
  3268. bool TestIsStrictOp = false;
  3269. /// \brief This flag is true when step is subtracted on each iteration.
  3270. bool SubtractStep = false;
  3271. public:
  3272. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3273. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3274. /// \brief Check init-expr for canonical loop form and save loop counter
  3275. /// variable - #Var and its initialization value - #LB.
  3276. bool CheckInit(Stmt *S, bool EmitDiags = true);
  3277. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  3278. /// for less/greater and for strict/non-strict comparison.
  3279. bool CheckCond(Expr *S);
  3280. /// \brief Check incr-expr for canonical loop form and return true if it
  3281. /// does not conform, otherwise save loop step (#Step).
  3282. bool CheckInc(Expr *S);
  3283. /// \brief Return the loop counter variable.
  3284. ValueDecl *GetLoopDecl() const { return LCDecl; }
  3285. /// \brief Return the reference expression to loop counter variable.
  3286. Expr *GetLoopDeclRefExpr() const { return LCRef; }
  3287. /// \brief Source range of the loop init.
  3288. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  3289. /// \brief Source range of the loop condition.
  3290. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  3291. /// \brief Source range of the loop increment.
  3292. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  3293. /// \brief True if the step should be subtracted.
  3294. bool ShouldSubtractStep() const { return SubtractStep; }
  3295. /// \brief Build the expression to calculate the number of iterations.
  3296. Expr *
  3297. BuildNumIterations(Scope *S, const bool LimitedType,
  3298. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3299. /// \brief Build the precondition expression for the loops.
  3300. Expr *BuildPreCond(Scope *S, Expr *Cond,
  3301. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3302. /// \brief Build reference expression to the counter be used for codegen.
  3303. DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
  3304. DSAStackTy &DSA) const;
  3305. /// \brief Build reference expression to the private counter be used for
  3306. /// codegen.
  3307. Expr *BuildPrivateCounterVar() const;
  3308. /// \brief Build initialization of the counter be used for codegen.
  3309. Expr *BuildCounterInit() const;
  3310. /// \brief Build step of the counter be used for codegen.
  3311. Expr *BuildCounterStep() const;
  3312. /// \brief Return true if any expression is dependent.
  3313. bool Dependent() const;
  3314. private:
  3315. /// \brief Check the right-hand side of an assignment in the increment
  3316. /// expression.
  3317. bool CheckIncRHS(Expr *RHS);
  3318. /// \brief Helper to set loop counter variable and its initializer.
  3319. bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3320. /// \brief Helper to set upper bound.
  3321. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  3322. SourceLocation SL);
  3323. /// \brief Helper to set loop increment.
  3324. bool SetStep(Expr *NewStep, bool Subtract);
  3325. };
  3326. bool OpenMPIterationSpaceChecker::Dependent() const {
  3327. if (!LCDecl) {
  3328. assert(!LB && !UB && !Step);
  3329. return false;
  3330. }
  3331. return LCDecl->getType()->isDependentType() ||
  3332. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3333. (Step && Step->isValueDependent());
  3334. }
  3335. bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
  3336. Expr *NewLCRefExpr,
  3337. Expr *NewLB) {
  3338. // State consistency checking to ensure correct usage.
  3339. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3340. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3341. if (!NewLCDecl || !NewLB)
  3342. return true;
  3343. LCDecl = getCanonicalDecl(NewLCDecl);
  3344. LCRef = NewLCRefExpr;
  3345. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3346. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3347. if ((Ctor->isCopyOrMoveConstructor() ||
  3348. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3349. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3350. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3351. LB = NewLB;
  3352. return false;
  3353. }
  3354. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  3355. SourceRange SR, SourceLocation SL) {
  3356. // State consistency checking to ensure correct usage.
  3357. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3358. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3359. if (!NewUB)
  3360. return true;
  3361. UB = NewUB;
  3362. TestIsLessOp = LessOp;
  3363. TestIsStrictOp = StrictOp;
  3364. ConditionSrcRange = SR;
  3365. ConditionLoc = SL;
  3366. return false;
  3367. }
  3368. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  3369. // State consistency checking to ensure correct usage.
  3370. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3371. if (!NewStep)
  3372. return true;
  3373. if (!NewStep->isValueDependent()) {
  3374. // Check that the step is integer expression.
  3375. SourceLocation StepLoc = NewStep->getLocStart();
  3376. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3377. StepLoc, getExprAsWritten(NewStep));
  3378. if (Val.isInvalid())
  3379. return true;
  3380. NewStep = Val.get();
  3381. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3382. // If test-expr is of form var relational-op b and relational-op is < or
  3383. // <= then incr-expr must cause var to increase on each iteration of the
  3384. // loop. If test-expr is of form var relational-op b and relational-op is
  3385. // > or >= then incr-expr must cause var to decrease on each iteration of
  3386. // the loop.
  3387. // If test-expr is of form b relational-op var and relational-op is < or
  3388. // <= then incr-expr must cause var to decrease on each iteration of the
  3389. // loop. If test-expr is of form b relational-op var and relational-op is
  3390. // > or >= then incr-expr must cause var to increase on each iteration of
  3391. // the loop.
  3392. llvm::APSInt Result;
  3393. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3394. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3395. bool IsConstNeg =
  3396. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3397. bool IsConstPos =
  3398. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3399. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3400. if (UB && (IsConstZero ||
  3401. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  3402. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  3403. SemaRef.Diag(NewStep->getExprLoc(),
  3404. diag::err_omp_loop_incr_not_compatible)
  3405. << LCDecl << TestIsLessOp << NewStep->getSourceRange();
  3406. SemaRef.Diag(ConditionLoc,
  3407. diag::note_omp_loop_cond_requres_compatible_incr)
  3408. << TestIsLessOp << ConditionSrcRange;
  3409. return true;
  3410. }
  3411. if (TestIsLessOp == Subtract) {
  3412. NewStep =
  3413. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3414. .get();
  3415. Subtract = !Subtract;
  3416. }
  3417. }
  3418. Step = NewStep;
  3419. SubtractStep = Subtract;
  3420. return false;
  3421. }
  3422. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  3423. // Check init-expr for canonical loop form and save loop counter
  3424. // variable - #Var and its initialization value - #LB.
  3425. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3426. // var = lb
  3427. // integer-type var = lb
  3428. // random-access-iterator-type var = lb
  3429. // pointer-type var = lb
  3430. //
  3431. if (!S) {
  3432. if (EmitDiags) {
  3433. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3434. }
  3435. return true;
  3436. }
  3437. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3438. if (!ExprTemp->cleanupsHaveSideEffects())
  3439. S = ExprTemp->getSubExpr();
  3440. InitSrcRange = S->getSourceRange();
  3441. if (Expr *E = dyn_cast<Expr>(S))
  3442. S = E->IgnoreParens();
  3443. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3444. if (BO->getOpcode() == BO_Assign) {
  3445. auto *LHS = BO->getLHS()->IgnoreParens();
  3446. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3447. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3448. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3449. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3450. return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3451. }
  3452. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3453. if (ME->isArrow() &&
  3454. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3455. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3456. }
  3457. }
  3458. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3459. if (DS->isSingleDecl()) {
  3460. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3461. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3462. // Accept non-canonical init form here but emit ext. warning.
  3463. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3464. SemaRef.Diag(S->getLocStart(),
  3465. diag::ext_omp_loop_not_canonical_init)
  3466. << S->getSourceRange();
  3467. return SetLCDeclAndLB(Var, nullptr, Var->getInit());
  3468. }
  3469. }
  3470. }
  3471. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3472. if (CE->getOperator() == OO_Equal) {
  3473. auto *LHS = CE->getArg(0);
  3474. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3475. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3476. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3477. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3478. return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3479. }
  3480. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3481. if (ME->isArrow() &&
  3482. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3483. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3484. }
  3485. }
  3486. }
  3487. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3488. return false;
  3489. if (EmitDiags) {
  3490. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  3491. << S->getSourceRange();
  3492. }
  3493. return true;
  3494. }
  3495. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  3496. /// variable (which may be the loop variable) if possible.
  3497. static const ValueDecl *GetInitLCDecl(Expr *E) {
  3498. if (!E)
  3499. return nullptr;
  3500. E = getExprAsWritten(E);
  3501. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3502. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3503. if ((Ctor->isCopyOrMoveConstructor() ||
  3504. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3505. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3506. E = CE->getArg(0)->IgnoreParenImpCasts();
  3507. if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3508. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3509. return getCanonicalDecl(VD);
  3510. }
  3511. if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3512. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3513. return getCanonicalDecl(ME->getMemberDecl());
  3514. return nullptr;
  3515. }
  3516. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  3517. // Check test-expr for canonical form, save upper-bound UB, flags for
  3518. // less/greater and for strict/non-strict comparison.
  3519. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3520. // var relational-op b
  3521. // b relational-op var
  3522. //
  3523. if (!S) {
  3524. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3525. return true;
  3526. }
  3527. S = getExprAsWritten(S);
  3528. SourceLocation CondLoc = S->getLocStart();
  3529. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3530. if (BO->isRelationalOp()) {
  3531. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3532. return SetUB(BO->getRHS(),
  3533. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3534. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3535. BO->getSourceRange(), BO->getOperatorLoc());
  3536. if (GetInitLCDecl(BO->getRHS()) == LCDecl)
  3537. return SetUB(BO->getLHS(),
  3538. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3539. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3540. BO->getSourceRange(), BO->getOperatorLoc());
  3541. }
  3542. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3543. if (CE->getNumArgs() == 2) {
  3544. auto Op = CE->getOperator();
  3545. switch (Op) {
  3546. case OO_Greater:
  3547. case OO_GreaterEqual:
  3548. case OO_Less:
  3549. case OO_LessEqual:
  3550. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3551. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  3552. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3553. CE->getOperatorLoc());
  3554. if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3555. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  3556. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3557. CE->getOperatorLoc());
  3558. break;
  3559. default:
  3560. break;
  3561. }
  3562. }
  3563. }
  3564. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3565. return false;
  3566. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  3567. << S->getSourceRange() << LCDecl;
  3568. return true;
  3569. }
  3570. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  3571. // RHS of canonical loop form increment can be:
  3572. // var + incr
  3573. // incr + var
  3574. // var - incr
  3575. //
  3576. RHS = RHS->IgnoreParenImpCasts();
  3577. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  3578. if (BO->isAdditiveOp()) {
  3579. bool IsAdd = BO->getOpcode() == BO_Add;
  3580. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3581. return SetStep(BO->getRHS(), !IsAdd);
  3582. if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
  3583. return SetStep(BO->getLHS(), false);
  3584. }
  3585. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  3586. bool IsAdd = CE->getOperator() == OO_Plus;
  3587. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  3588. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3589. return SetStep(CE->getArg(1), !IsAdd);
  3590. if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3591. return SetStep(CE->getArg(0), false);
  3592. }
  3593. }
  3594. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3595. return false;
  3596. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3597. << RHS->getSourceRange() << LCDecl;
  3598. return true;
  3599. }
  3600. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  3601. // Check incr-expr for canonical loop form and return true if it
  3602. // does not conform.
  3603. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3604. // ++var
  3605. // var++
  3606. // --var
  3607. // var--
  3608. // var += incr
  3609. // var -= incr
  3610. // var = var + incr
  3611. // var = incr + var
  3612. // var = var - incr
  3613. //
  3614. if (!S) {
  3615. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  3616. return true;
  3617. }
  3618. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3619. if (!ExprTemp->cleanupsHaveSideEffects())
  3620. S = ExprTemp->getSubExpr();
  3621. IncrementSrcRange = S->getSourceRange();
  3622. S = S->IgnoreParens();
  3623. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  3624. if (UO->isIncrementDecrementOp() &&
  3625. GetInitLCDecl(UO->getSubExpr()) == LCDecl)
  3626. return SetStep(SemaRef
  3627. .ActOnIntegerConstant(UO->getLocStart(),
  3628. (UO->isDecrementOp() ? -1 : 1))
  3629. .get(),
  3630. false);
  3631. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3632. switch (BO->getOpcode()) {
  3633. case BO_AddAssign:
  3634. case BO_SubAssign:
  3635. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3636. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  3637. break;
  3638. case BO_Assign:
  3639. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3640. return CheckIncRHS(BO->getRHS());
  3641. break;
  3642. default:
  3643. break;
  3644. }
  3645. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3646. switch (CE->getOperator()) {
  3647. case OO_PlusPlus:
  3648. case OO_MinusMinus:
  3649. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3650. return SetStep(SemaRef
  3651. .ActOnIntegerConstant(
  3652. CE->getLocStart(),
  3653. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  3654. .get(),
  3655. false);
  3656. break;
  3657. case OO_PlusEqual:
  3658. case OO_MinusEqual:
  3659. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3660. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  3661. break;
  3662. case OO_Equal:
  3663. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3664. return CheckIncRHS(CE->getArg(1));
  3665. break;
  3666. default:
  3667. break;
  3668. }
  3669. }
  3670. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3671. return false;
  3672. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3673. << S->getSourceRange() << LCDecl;
  3674. return true;
  3675. }
  3676. static ExprResult
  3677. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  3678. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3679. if (SemaRef.CurContext->isDependentContext())
  3680. return ExprResult(Capture);
  3681. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  3682. return SemaRef.PerformImplicitConversion(
  3683. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  3684. /*AllowExplicit=*/true);
  3685. auto I = Captures.find(Capture);
  3686. if (I != Captures.end())
  3687. return buildCapture(SemaRef, Capture, I->second);
  3688. DeclRefExpr *Ref = nullptr;
  3689. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  3690. Captures[Capture] = Ref;
  3691. return Res;
  3692. }
  3693. /// \brief Build the expression to calculate the number of iterations.
  3694. Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
  3695. Scope *S, const bool LimitedType,
  3696. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3697. ExprResult Diff;
  3698. auto VarType = LCDecl->getType().getNonReferenceType();
  3699. if (VarType->isIntegerType() || VarType->isPointerType() ||
  3700. SemaRef.getLangOpts().CPlusPlus) {
  3701. // Upper - Lower
  3702. auto *UBExpr = TestIsLessOp ? UB : LB;
  3703. auto *LBExpr = TestIsLessOp ? LB : UB;
  3704. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  3705. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  3706. if (!Upper || !Lower)
  3707. return nullptr;
  3708. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  3709. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  3710. // BuildBinOp already emitted error, this one is to point user to upper
  3711. // and lower bound, and to tell what is passed to 'operator-'.
  3712. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  3713. << Upper->getSourceRange() << Lower->getSourceRange();
  3714. return nullptr;
  3715. }
  3716. }
  3717. if (!Diff.isUsable())
  3718. return nullptr;
  3719. // Upper - Lower [- 1]
  3720. if (TestIsStrictOp)
  3721. Diff = SemaRef.BuildBinOp(
  3722. S, DefaultLoc, BO_Sub, Diff.get(),
  3723. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3724. if (!Diff.isUsable())
  3725. return nullptr;
  3726. // Upper - Lower [- 1] + Step
  3727. auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
  3728. if (!NewStep.isUsable())
  3729. return nullptr;
  3730. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  3731. if (!Diff.isUsable())
  3732. return nullptr;
  3733. // Parentheses (for dumping/debugging purposes only).
  3734. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  3735. if (!Diff.isUsable())
  3736. return nullptr;
  3737. // (Upper - Lower [- 1] + Step) / Step
  3738. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  3739. if (!Diff.isUsable())
  3740. return nullptr;
  3741. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  3742. QualType Type = Diff.get()->getType();
  3743. auto &C = SemaRef.Context;
  3744. bool UseVarType = VarType->hasIntegerRepresentation() &&
  3745. C.getTypeSize(Type) > C.getTypeSize(VarType);
  3746. if (!Type->isIntegerType() || UseVarType) {
  3747. unsigned NewSize =
  3748. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  3749. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  3750. : Type->hasSignedIntegerRepresentation();
  3751. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  3752. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  3753. Diff = SemaRef.PerformImplicitConversion(
  3754. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  3755. if (!Diff.isUsable())
  3756. return nullptr;
  3757. }
  3758. }
  3759. if (LimitedType) {
  3760. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  3761. if (NewSize != C.getTypeSize(Type)) {
  3762. if (NewSize < C.getTypeSize(Type)) {
  3763. assert(NewSize == 64 && "incorrect loop var size");
  3764. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3765. << InitSrcRange << ConditionSrcRange;
  3766. }
  3767. QualType NewType = C.getIntTypeForBitwidth(
  3768. NewSize, Type->hasSignedIntegerRepresentation() ||
  3769. C.getTypeSize(Type) < NewSize);
  3770. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  3771. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3772. Sema::AA_Converting, true);
  3773. if (!Diff.isUsable())
  3774. return nullptr;
  3775. }
  3776. }
  3777. }
  3778. return Diff.get();
  3779. }
  3780. Expr *OpenMPIterationSpaceChecker::BuildPreCond(
  3781. Scope *S, Expr *Cond,
  3782. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3783. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3784. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3785. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3786. auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
  3787. auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
  3788. if (!NewLB.isUsable() || !NewUB.isUsable())
  3789. return nullptr;
  3790. auto CondExpr = SemaRef.BuildBinOp(
  3791. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3792. : (TestIsStrictOp ? BO_GT : BO_GE),
  3793. NewLB.get(), NewUB.get());
  3794. if (CondExpr.isUsable()) {
  3795. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  3796. SemaRef.Context.BoolTy))
  3797. CondExpr = SemaRef.PerformImplicitConversion(
  3798. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3799. /*AllowExplicit=*/true);
  3800. }
  3801. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3802. // Otherwise use original loop conditon and evaluate it in runtime.
  3803. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3804. }
  3805. /// \brief Build reference expression to the counter be used for codegen.
  3806. DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
  3807. llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
  3808. auto *VD = dyn_cast<VarDecl>(LCDecl);
  3809. if (!VD) {
  3810. VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
  3811. auto *Ref = buildDeclRefExpr(
  3812. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  3813. DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  3814. // If the loop control decl is explicitly marked as private, do not mark it
  3815. // as captured again.
  3816. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  3817. Captures.insert(std::make_pair(LCRef, Ref));
  3818. return Ref;
  3819. }
  3820. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  3821. DefaultLoc);
  3822. }
  3823. Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
  3824. if (LCDecl && !LCDecl->isInvalidDecl()) {
  3825. auto Type = LCDecl->getType().getNonReferenceType();
  3826. auto *PrivateVar =
  3827. buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
  3828. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
  3829. if (PrivateVar->isInvalidDecl())
  3830. return nullptr;
  3831. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  3832. }
  3833. return nullptr;
  3834. }
  3835. /// \brief Build initialization of the counter to be used for codegen.
  3836. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3837. /// \brief Build step of the counter be used for codegen.
  3838. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3839. /// \brief Iteration space of a single for loop.
  3840. struct LoopIterationSpace final {
  3841. /// \brief Condition of the loop.
  3842. Expr *PreCond = nullptr;
  3843. /// \brief This expression calculates the number of iterations in the loop.
  3844. /// It is always possible to calculate it before starting the loop.
  3845. Expr *NumIterations = nullptr;
  3846. /// \brief The loop counter variable.
  3847. Expr *CounterVar = nullptr;
  3848. /// \brief Private loop counter variable.
  3849. Expr *PrivateCounterVar = nullptr;
  3850. /// \brief This is initializer for the initial value of #CounterVar.
  3851. Expr *CounterInit = nullptr;
  3852. /// \brief This is step for the #CounterVar used to generate its update:
  3853. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3854. Expr *CounterStep = nullptr;
  3855. /// \brief Should step be subtracted?
  3856. bool Subtract = false;
  3857. /// \brief Source range of the loop init.
  3858. SourceRange InitSrcRange;
  3859. /// \brief Source range of the loop condition.
  3860. SourceRange CondSrcRange;
  3861. /// \brief Source range of the loop increment.
  3862. SourceRange IncSrcRange;
  3863. };
  3864. } // namespace
  3865. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3866. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3867. assert(Init && "Expected loop in canonical form.");
  3868. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  3869. if (AssociatedLoops > 0 &&
  3870. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3871. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3872. if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
  3873. if (auto *D = ISC.GetLoopDecl()) {
  3874. auto *VD = dyn_cast<VarDecl>(D);
  3875. if (!VD) {
  3876. if (auto *Private = IsOpenMPCapturedDecl(D))
  3877. VD = Private;
  3878. else {
  3879. auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
  3880. /*WithInit=*/false);
  3881. VD = cast<VarDecl>(Ref->getDecl());
  3882. }
  3883. }
  3884. DSAStack->addLoopControlVariable(D, VD);
  3885. }
  3886. }
  3887. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  3888. }
  3889. }
  3890. /// \brief Called on a for stmt to check and extract its iteration space
  3891. /// for further processing (such as collapsing).
  3892. static bool CheckOpenMPIterationSpace(
  3893. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3894. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3895. Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
  3896. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3897. LoopIterationSpace &ResultIterSpace,
  3898. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3899. // OpenMP [2.6, Canonical Loop Form]
  3900. // for (init-expr; test-expr; incr-expr) structured-block
  3901. auto *For = dyn_cast_or_null<ForStmt>(S);
  3902. if (!For) {
  3903. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3904. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  3905. << getOpenMPDirectiveName(DKind) << NestedLoopCount
  3906. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  3907. if (NestedLoopCount > 1) {
  3908. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  3909. SemaRef.Diag(DSA.getConstructLoc(),
  3910. diag::note_omp_collapse_ordered_expr)
  3911. << 2 << CollapseLoopCountExpr->getSourceRange()
  3912. << OrderedLoopCountExpr->getSourceRange();
  3913. else if (CollapseLoopCountExpr)
  3914. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3915. diag::note_omp_collapse_ordered_expr)
  3916. << 0 << CollapseLoopCountExpr->getSourceRange();
  3917. else
  3918. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3919. diag::note_omp_collapse_ordered_expr)
  3920. << 1 << OrderedLoopCountExpr->getSourceRange();
  3921. }
  3922. return true;
  3923. }
  3924. assert(For->getBody());
  3925. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3926. // Check init.
  3927. auto Init = For->getInit();
  3928. if (ISC.CheckInit(Init))
  3929. return true;
  3930. bool HasErrors = false;
  3931. // Check loop variable's type.
  3932. if (auto *LCDecl = ISC.GetLoopDecl()) {
  3933. auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
  3934. // OpenMP [2.6, Canonical Loop Form]
  3935. // Var is one of the following:
  3936. // A variable of signed or unsigned integer type.
  3937. // For C++, a variable of a random access iterator type.
  3938. // For C, a variable of a pointer type.
  3939. auto VarType = LCDecl->getType().getNonReferenceType();
  3940. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3941. !VarType->isPointerType() &&
  3942. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3943. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3944. << SemaRef.getLangOpts().CPlusPlus;
  3945. HasErrors = true;
  3946. }
  3947. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  3948. // a Construct
  3949. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3950. // parallel for construct is (are) private.
  3951. // The loop iteration variable in the associated for-loop of a simd
  3952. // construct with just one associated for-loop is linear with a
  3953. // constant-linear-step that is the increment of the associated for-loop.
  3954. // Exclude loop var from the list of variables with implicitly defined data
  3955. // sharing attributes.
  3956. VarsWithImplicitDSA.erase(LCDecl);
  3957. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  3958. // in a Construct, C/C++].
  3959. // The loop iteration variable in the associated for-loop of a simd
  3960. // construct with just one associated for-loop may be listed in a linear
  3961. // clause with a constant-linear-step that is the increment of the
  3962. // associated for-loop.
  3963. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3964. // parallel for construct may be listed in a private or lastprivate clause.
  3965. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  3966. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3967. // declared in the loop and it is predetermined as a private.
  3968. auto PredeterminedCKind =
  3969. isOpenMPSimdDirective(DKind)
  3970. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3971. : OMPC_private;
  3972. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3973. DVar.CKind != PredeterminedCKind) ||
  3974. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  3975. isOpenMPDistributeDirective(DKind)) &&
  3976. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3977. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  3978. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  3979. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3980. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3981. << getOpenMPClauseName(PredeterminedCKind);
  3982. if (DVar.RefExpr == nullptr)
  3983. DVar.CKind = PredeterminedCKind;
  3984. ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  3985. HasErrors = true;
  3986. } else if (LoopDeclRefExpr != nullptr) {
  3987. // Make the loop iteration variable private (for worksharing constructs),
  3988. // linear (for simd directives with the only one associated loop) or
  3989. // lastprivate (for simd directives with several collapsed or ordered
  3990. // loops).
  3991. if (DVar.CKind == OMPC_unknown)
  3992. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  3993. [](OpenMPDirectiveKind) -> bool { return true; },
  3994. /*FromParent=*/false);
  3995. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  3996. }
  3997. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3998. // Check test-expr.
  3999. HasErrors |= ISC.CheckCond(For->getCond());
  4000. // Check incr-expr.
  4001. HasErrors |= ISC.CheckInc(For->getInc());
  4002. }
  4003. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  4004. return HasErrors;
  4005. // Build the loop's iteration space representation.
  4006. ResultIterSpace.PreCond =
  4007. ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4008. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  4009. DSA.getCurScope(),
  4010. (isOpenMPWorksharingDirective(DKind) ||
  4011. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4012. Captures);
  4013. ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
  4014. ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
  4015. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  4016. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  4017. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  4018. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  4019. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  4020. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  4021. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4022. ResultIterSpace.NumIterations == nullptr ||
  4023. ResultIterSpace.CounterVar == nullptr ||
  4024. ResultIterSpace.PrivateCounterVar == nullptr ||
  4025. ResultIterSpace.CounterInit == nullptr ||
  4026. ResultIterSpace.CounterStep == nullptr);
  4027. return HasErrors;
  4028. }
  4029. /// \brief Build 'VarRef = Start.
  4030. static ExprResult
  4031. BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4032. ExprResult Start,
  4033. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4034. // Build 'VarRef = Start.
  4035. auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4036. if (!NewStart.isUsable())
  4037. return ExprError();
  4038. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4039. VarRef.get()->getType())) {
  4040. NewStart = SemaRef.PerformImplicitConversion(
  4041. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4042. /*AllowExplicit=*/true);
  4043. if (!NewStart.isUsable())
  4044. return ExprError();
  4045. }
  4046. auto Init =
  4047. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4048. return Init;
  4049. }
  4050. /// \brief Build 'VarRef = Start + Iter * Step'.
  4051. static ExprResult
  4052. BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
  4053. ExprResult VarRef, ExprResult Start, ExprResult Iter,
  4054. ExprResult Step, bool Subtract,
  4055. llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
  4056. // Add parentheses (for debugging purposes only).
  4057. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4058. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4059. !Step.isUsable())
  4060. return ExprError();
  4061. ExprResult NewStep = Step;
  4062. if (Captures)
  4063. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4064. if (NewStep.isInvalid())
  4065. return ExprError();
  4066. ExprResult Update =
  4067. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4068. if (!Update.isUsable())
  4069. return ExprError();
  4070. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4071. // 'VarRef = Start (+|-) Iter * Step'.
  4072. ExprResult NewStart = Start;
  4073. if (Captures)
  4074. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4075. if (NewStart.isInvalid())
  4076. return ExprError();
  4077. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4078. ExprResult SavedUpdate = Update;
  4079. ExprResult UpdateVal;
  4080. if (VarRef.get()->getType()->isOverloadableType() ||
  4081. NewStart.get()->getType()->isOverloadableType() ||
  4082. Update.get()->getType()->isOverloadableType()) {
  4083. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4084. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4085. Update =
  4086. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4087. if (Update.isUsable()) {
  4088. UpdateVal =
  4089. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4090. VarRef.get(), SavedUpdate.get());
  4091. if (UpdateVal.isUsable()) {
  4092. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4093. UpdateVal.get());
  4094. }
  4095. }
  4096. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4097. }
  4098. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4099. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4100. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4101. NewStart.get(), SavedUpdate.get());
  4102. if (!Update.isUsable())
  4103. return ExprError();
  4104. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4105. VarRef.get()->getType())) {
  4106. Update = SemaRef.PerformImplicitConversion(
  4107. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4108. if (!Update.isUsable())
  4109. return ExprError();
  4110. }
  4111. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4112. }
  4113. return Update;
  4114. }
  4115. /// \brief Convert integer expression \a E to make it have at least \a Bits
  4116. /// bits.
  4117. static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4118. if (E == nullptr)
  4119. return ExprError();
  4120. auto &C = SemaRef.Context;
  4121. QualType OldType = E->getType();
  4122. unsigned HasBits = C.getTypeSize(OldType);
  4123. if (HasBits >= Bits)
  4124. return ExprResult(E);
  4125. // OK to convert to signed, because new type has more bits than old.
  4126. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4127. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4128. true);
  4129. }
  4130. /// \brief Check if the given expression \a E is a constant integer that fits
  4131. /// into \a Bits bits.
  4132. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  4133. if (E == nullptr)
  4134. return false;
  4135. llvm::APSInt Result;
  4136. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4137. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4138. return false;
  4139. }
  4140. /// Build preinits statement for the given declarations.
  4141. static Stmt *buildPreInits(ASTContext &Context,
  4142. MutableArrayRef<Decl *> PreInits) {
  4143. if (!PreInits.empty()) {
  4144. return new (Context) DeclStmt(
  4145. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4146. SourceLocation(), SourceLocation());
  4147. }
  4148. return nullptr;
  4149. }
  4150. /// Build preinits statement for the given declarations.
  4151. static Stmt *
  4152. buildPreInits(ASTContext &Context,
  4153. const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4154. if (!Captures.empty()) {
  4155. SmallVector<Decl *, 16> PreInits;
  4156. for (auto &Pair : Captures)
  4157. PreInits.push_back(Pair.second->getDecl());
  4158. return buildPreInits(Context, PreInits);
  4159. }
  4160. return nullptr;
  4161. }
  4162. /// Build postupdate expression for the given list of postupdates expressions.
  4163. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4164. Expr *PostUpdate = nullptr;
  4165. if (!PostUpdates.empty()) {
  4166. for (auto *E : PostUpdates) {
  4167. Expr *ConvE = S.BuildCStyleCastExpr(
  4168. E->getExprLoc(),
  4169. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4170. E->getExprLoc(), E)
  4171. .get();
  4172. PostUpdate = PostUpdate
  4173. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4174. PostUpdate, ConvE)
  4175. .get()
  4176. : ConvE;
  4177. }
  4178. }
  4179. return PostUpdate;
  4180. }
  4181. /// \brief Called on a for stmt to check itself and nested loops (if any).
  4182. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4183. /// number of collapsed loops otherwise.
  4184. static unsigned
  4185. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4186. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4187. DSAStackTy &DSA,
  4188. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  4189. OMPLoopDirective::HelperExprs &Built) {
  4190. unsigned NestedLoopCount = 1;
  4191. if (CollapseLoopCountExpr) {
  4192. // Found 'collapse' clause - calculate collapse number.
  4193. llvm::APSInt Result;
  4194. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4195. NestedLoopCount = Result.getLimitedValue();
  4196. }
  4197. if (OrderedLoopCountExpr) {
  4198. // Found 'ordered' clause - calculate collapse number.
  4199. llvm::APSInt Result;
  4200. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  4201. if (Result.getLimitedValue() < NestedLoopCount) {
  4202. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4203. diag::err_omp_wrong_ordered_loop_count)
  4204. << OrderedLoopCountExpr->getSourceRange();
  4205. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4206. diag::note_collapse_loop_count)
  4207. << CollapseLoopCountExpr->getSourceRange();
  4208. }
  4209. NestedLoopCount = Result.getLimitedValue();
  4210. }
  4211. }
  4212. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4213. // 'for simd', etc.).
  4214. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  4215. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4216. IterSpaces.resize(NestedLoopCount);
  4217. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4218. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4219. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  4220. NestedLoopCount, CollapseLoopCountExpr,
  4221. OrderedLoopCountExpr, VarsWithImplicitDSA,
  4222. IterSpaces[Cnt], Captures))
  4223. return 0;
  4224. // Move on to the next nested for loop, or to the loop body.
  4225. // OpenMP [2.8.1, simd construct, Restrictions]
  4226. // All loops associated with the construct must be perfectly nested; that
  4227. // is, there must be no intervening code nor any OpenMP directive between
  4228. // any two loops.
  4229. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4230. }
  4231. Built.clear(/* size */ NestedLoopCount);
  4232. if (SemaRef.CurContext->isDependentContext())
  4233. return NestedLoopCount;
  4234. // An example of what is generated for the following code:
  4235. //
  4236. // #pragma omp simd collapse(2) ordered(2)
  4237. // for (i = 0; i < NI; ++i)
  4238. // for (k = 0; k < NK; ++k)
  4239. // for (j = J0; j < NJ; j+=2) {
  4240. // <loop body>
  4241. // }
  4242. //
  4243. // We generate the code below.
  4244. // Note: the loop body may be outlined in CodeGen.
  4245. // Note: some counters may be C++ classes, operator- is used to find number of
  4246. // iterations and operator+= to calculate counter value.
  4247. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4248. // or i64 is currently supported).
  4249. //
  4250. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4251. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4252. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4253. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4254. // // similar updates for vars in clauses (e.g. 'linear')
  4255. // <loop body (using local i and j)>
  4256. // }
  4257. // i = NI; // assign final values of counters
  4258. // j = NJ;
  4259. //
  4260. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4261. // the iteration counts of the collapsed for loops.
  4262. // Precondition tests if there is at least one iteration (all conditions are
  4263. // true).
  4264. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4265. auto N0 = IterSpaces[0].NumIterations;
  4266. ExprResult LastIteration32 = WidenIterationCount(
  4267. 32 /* Bits */, SemaRef
  4268. .PerformImplicitConversion(
  4269. N0->IgnoreImpCasts(), N0->getType(),
  4270. Sema::AA_Converting, /*AllowExplicit=*/true)
  4271. .get(),
  4272. SemaRef);
  4273. ExprResult LastIteration64 = WidenIterationCount(
  4274. 64 /* Bits */, SemaRef
  4275. .PerformImplicitConversion(
  4276. N0->IgnoreImpCasts(), N0->getType(),
  4277. Sema::AA_Converting, /*AllowExplicit=*/true)
  4278. .get(),
  4279. SemaRef);
  4280. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4281. return NestedLoopCount;
  4282. auto &C = SemaRef.Context;
  4283. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4284. Scope *CurScope = DSA.getCurScope();
  4285. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4286. if (PreCond.isUsable()) {
  4287. PreCond =
  4288. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4289. PreCond.get(), IterSpaces[Cnt].PreCond);
  4290. }
  4291. auto N = IterSpaces[Cnt].NumIterations;
  4292. SourceLocation Loc = N->getExprLoc();
  4293. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4294. if (LastIteration32.isUsable())
  4295. LastIteration32 = SemaRef.BuildBinOp(
  4296. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4297. SemaRef
  4298. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4299. Sema::AA_Converting,
  4300. /*AllowExplicit=*/true)
  4301. .get());
  4302. if (LastIteration64.isUsable())
  4303. LastIteration64 = SemaRef.BuildBinOp(
  4304. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4305. SemaRef
  4306. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4307. Sema::AA_Converting,
  4308. /*AllowExplicit=*/true)
  4309. .get());
  4310. }
  4311. // Choose either the 32-bit or 64-bit version.
  4312. ExprResult LastIteration = LastIteration64;
  4313. if (LastIteration32.isUsable() &&
  4314. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4315. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4316. FitsInto(
  4317. 32 /* Bits */,
  4318. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4319. LastIteration64.get(), SemaRef)))
  4320. LastIteration = LastIteration32;
  4321. QualType VType = LastIteration.get()->getType();
  4322. QualType RealVType = VType;
  4323. QualType StrideVType = VType;
  4324. if (isOpenMPTaskLoopDirective(DKind)) {
  4325. VType =
  4326. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4327. StrideVType =
  4328. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4329. }
  4330. if (!LastIteration.isUsable())
  4331. return 0;
  4332. // Save the number of iterations.
  4333. ExprResult NumIterations = LastIteration;
  4334. {
  4335. LastIteration = SemaRef.BuildBinOp(
  4336. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4337. LastIteration.get(),
  4338. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4339. if (!LastIteration.isUsable())
  4340. return 0;
  4341. }
  4342. // Calculate the last iteration number beforehand instead of doing this on
  4343. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4344. llvm::APSInt Result;
  4345. bool IsConstant =
  4346. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4347. ExprResult CalcLastIteration;
  4348. if (!IsConstant) {
  4349. ExprResult SaveRef =
  4350. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4351. LastIteration = SaveRef;
  4352. // Prepare SaveRef + 1.
  4353. NumIterations = SemaRef.BuildBinOp(
  4354. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4355. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4356. if (!NumIterations.isUsable())
  4357. return 0;
  4358. }
  4359. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4360. // Build variables passed into runtime, necessary for worksharing directives.
  4361. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4362. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4363. isOpenMPDistributeDirective(DKind)) {
  4364. // Lower bound variable, initialized with zero.
  4365. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4366. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4367. SemaRef.AddInitializerToDecl(LBDecl,
  4368. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4369. /*DirectInit*/ false);
  4370. // Upper bound variable, initialized with last iteration number.
  4371. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4372. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4373. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4374. /*DirectInit*/ false);
  4375. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4376. // This will be used to implement clause 'lastprivate'.
  4377. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4378. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4379. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4380. SemaRef.AddInitializerToDecl(ILDecl,
  4381. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4382. /*DirectInit*/ false);
  4383. // Stride variable returned by runtime (we initialize it to 1 by default).
  4384. VarDecl *STDecl =
  4385. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4386. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4387. SemaRef.AddInitializerToDecl(STDecl,
  4388. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4389. /*DirectInit*/ false);
  4390. // Build expression: UB = min(UB, LastIteration)
  4391. // It is necessary for CodeGen of directives with static scheduling.
  4392. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4393. UB.get(), LastIteration.get());
  4394. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4395. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  4396. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4397. CondOp.get());
  4398. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  4399. // If we have a combined directive that combines 'distribute', 'for' or
  4400. // 'simd' we need to be able to access the bounds of the schedule of the
  4401. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  4402. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  4403. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4404. // Lower bound variable, initialized with zero.
  4405. VarDecl *CombLBDecl =
  4406. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  4407. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  4408. SemaRef.AddInitializerToDecl(
  4409. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4410. /*DirectInit*/ false);
  4411. // Upper bound variable, initialized with last iteration number.
  4412. VarDecl *CombUBDecl =
  4413. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  4414. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  4415. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  4416. /*DirectInit*/ false);
  4417. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  4418. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  4419. ExprResult CombCondOp =
  4420. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  4421. LastIteration.get(), CombUB.get());
  4422. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  4423. CombCondOp.get());
  4424. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  4425. auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  4426. // We expect to have at least 2 more parameters than the 'parallel'
  4427. // directive does - the lower and upper bounds of the previous schedule.
  4428. assert(CD->getNumParams() >= 4 &&
  4429. "Unexpected number of parameters in loop combined directive");
  4430. // Set the proper type for the bounds given what we learned from the
  4431. // enclosed loops.
  4432. auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  4433. auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  4434. // Previous lower and upper bounds are obtained from the region
  4435. // parameters.
  4436. PrevLB =
  4437. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  4438. PrevUB =
  4439. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  4440. }
  4441. }
  4442. // Build the iteration variable and its initialization before loop.
  4443. ExprResult IV;
  4444. ExprResult Init, CombInit;
  4445. {
  4446. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  4447. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  4448. Expr *RHS =
  4449. (isOpenMPWorksharingDirective(DKind) ||
  4450. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4451. ? LB.get()
  4452. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4453. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  4454. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  4455. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4456. Expr *CombRHS =
  4457. (isOpenMPWorksharingDirective(DKind) ||
  4458. isOpenMPTaskLoopDirective(DKind) ||
  4459. isOpenMPDistributeDirective(DKind))
  4460. ? CombLB.get()
  4461. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4462. CombInit =
  4463. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  4464. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  4465. }
  4466. }
  4467. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  4468. SourceLocation CondLoc;
  4469. ExprResult Cond =
  4470. (isOpenMPWorksharingDirective(DKind) ||
  4471. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4472. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  4473. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  4474. NumIterations.get());
  4475. ExprResult CombCond;
  4476. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4477. CombCond =
  4478. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  4479. }
  4480. // Loop increment (IV = IV + 1)
  4481. SourceLocation IncLoc;
  4482. ExprResult Inc =
  4483. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  4484. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  4485. if (!Inc.isUsable())
  4486. return 0;
  4487. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  4488. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  4489. if (!Inc.isUsable())
  4490. return 0;
  4491. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  4492. // Used for directives with static scheduling.
  4493. // In combined construct, add combined version that use CombLB and CombUB
  4494. // base variables for the update
  4495. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  4496. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4497. isOpenMPDistributeDirective(DKind)) {
  4498. // LB + ST
  4499. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  4500. if (!NextLB.isUsable())
  4501. return 0;
  4502. // LB = LB + ST
  4503. NextLB =
  4504. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  4505. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  4506. if (!NextLB.isUsable())
  4507. return 0;
  4508. // UB + ST
  4509. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  4510. if (!NextUB.isUsable())
  4511. return 0;
  4512. // UB = UB + ST
  4513. NextUB =
  4514. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  4515. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  4516. if (!NextUB.isUsable())
  4517. return 0;
  4518. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4519. CombNextLB =
  4520. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  4521. if (!NextLB.isUsable())
  4522. return 0;
  4523. // LB = LB + ST
  4524. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  4525. CombNextLB.get());
  4526. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  4527. if (!CombNextLB.isUsable())
  4528. return 0;
  4529. // UB + ST
  4530. CombNextUB =
  4531. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  4532. if (!CombNextUB.isUsable())
  4533. return 0;
  4534. // UB = UB + ST
  4535. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  4536. CombNextUB.get());
  4537. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  4538. if (!CombNextUB.isUsable())
  4539. return 0;
  4540. }
  4541. }
  4542. // Create increment expression for distribute loop when combined in a same
  4543. // directive with for as IV = IV + ST; ensure upper bound expression based
  4544. // on PrevUB instead of NumIterations - used to implement 'for' when found
  4545. // in combination with 'distribute', like in 'distribute parallel for'
  4546. SourceLocation DistIncLoc;
  4547. ExprResult DistCond, DistInc, PrevEUB;
  4548. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4549. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  4550. assert(DistCond.isUsable() && "distribute cond expr was not built");
  4551. DistInc =
  4552. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  4553. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4554. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  4555. DistInc.get());
  4556. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  4557. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4558. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  4559. // construct
  4560. SourceLocation DistEUBLoc;
  4561. ExprResult IsUBGreater =
  4562. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  4563. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4564. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  4565. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  4566. CondOp.get());
  4567. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  4568. }
  4569. // Build updates and final values of the loop counters.
  4570. bool HasErrors = false;
  4571. Built.Counters.resize(NestedLoopCount);
  4572. Built.Inits.resize(NestedLoopCount);
  4573. Built.Updates.resize(NestedLoopCount);
  4574. Built.Finals.resize(NestedLoopCount);
  4575. SmallVector<Expr *, 4> LoopMultipliers;
  4576. {
  4577. ExprResult Div;
  4578. // Go from inner nested loop to outer.
  4579. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4580. LoopIterationSpace &IS = IterSpaces[Cnt];
  4581. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  4582. // Build: Iter = (IV / Div) % IS.NumIters
  4583. // where Div is product of previous iterations' IS.NumIters.
  4584. ExprResult Iter;
  4585. if (Div.isUsable()) {
  4586. Iter =
  4587. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  4588. } else {
  4589. Iter = IV;
  4590. assert((Cnt == (int)NestedLoopCount - 1) &&
  4591. "unusable div expected on first iteration only");
  4592. }
  4593. if (Cnt != 0 && Iter.isUsable())
  4594. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  4595. IS.NumIterations);
  4596. if (!Iter.isUsable()) {
  4597. HasErrors = true;
  4598. break;
  4599. }
  4600. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  4601. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  4602. auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
  4603. IS.CounterVar->getExprLoc(),
  4604. /*RefersToCapture=*/true);
  4605. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  4606. IS.CounterInit, Captures);
  4607. if (!Init.isUsable()) {
  4608. HasErrors = true;
  4609. break;
  4610. }
  4611. ExprResult Update = BuildCounterUpdate(
  4612. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  4613. IS.CounterStep, IS.Subtract, &Captures);
  4614. if (!Update.isUsable()) {
  4615. HasErrors = true;
  4616. break;
  4617. }
  4618. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  4619. ExprResult Final = BuildCounterUpdate(
  4620. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  4621. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  4622. if (!Final.isUsable()) {
  4623. HasErrors = true;
  4624. break;
  4625. }
  4626. // Build Div for the next iteration: Div <- Div * IS.NumIters
  4627. if (Cnt != 0) {
  4628. if (Div.isUnset())
  4629. Div = IS.NumIterations;
  4630. else
  4631. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  4632. IS.NumIterations);
  4633. // Add parentheses (for debugging purposes only).
  4634. if (Div.isUsable())
  4635. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  4636. if (!Div.isUsable()) {
  4637. HasErrors = true;
  4638. break;
  4639. }
  4640. LoopMultipliers.push_back(Div.get());
  4641. }
  4642. if (!Update.isUsable() || !Final.isUsable()) {
  4643. HasErrors = true;
  4644. break;
  4645. }
  4646. // Save results
  4647. Built.Counters[Cnt] = IS.CounterVar;
  4648. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  4649. Built.Inits[Cnt] = Init.get();
  4650. Built.Updates[Cnt] = Update.get();
  4651. Built.Finals[Cnt] = Final.get();
  4652. }
  4653. }
  4654. if (HasErrors)
  4655. return 0;
  4656. // Save results
  4657. Built.IterationVarRef = IV.get();
  4658. Built.LastIteration = LastIteration.get();
  4659. Built.NumIterations = NumIterations.get();
  4660. Built.CalcLastIteration =
  4661. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  4662. Built.PreCond = PreCond.get();
  4663. Built.PreInits = buildPreInits(C, Captures);
  4664. Built.Cond = Cond.get();
  4665. Built.Init = Init.get();
  4666. Built.Inc = Inc.get();
  4667. Built.LB = LB.get();
  4668. Built.UB = UB.get();
  4669. Built.IL = IL.get();
  4670. Built.ST = ST.get();
  4671. Built.EUB = EUB.get();
  4672. Built.NLB = NextLB.get();
  4673. Built.NUB = NextUB.get();
  4674. Built.PrevLB = PrevLB.get();
  4675. Built.PrevUB = PrevUB.get();
  4676. Built.DistInc = DistInc.get();
  4677. Built.PrevEUB = PrevEUB.get();
  4678. Built.DistCombinedFields.LB = CombLB.get();
  4679. Built.DistCombinedFields.UB = CombUB.get();
  4680. Built.DistCombinedFields.EUB = CombEUB.get();
  4681. Built.DistCombinedFields.Init = CombInit.get();
  4682. Built.DistCombinedFields.Cond = CombCond.get();
  4683. Built.DistCombinedFields.NLB = CombNextLB.get();
  4684. Built.DistCombinedFields.NUB = CombNextUB.get();
  4685. Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
  4686. // Fill data for doacross depend clauses.
  4687. for (auto Pair : DSA.getDoacrossDependClauses()) {
  4688. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4689. Pair.first->setCounterValue(CounterVal);
  4690. else {
  4691. if (NestedLoopCount != Pair.second.size() ||
  4692. NestedLoopCount != LoopMultipliers.size() + 1) {
  4693. // Erroneous case - clause has some problems.
  4694. Pair.first->setCounterValue(CounterVal);
  4695. continue;
  4696. }
  4697. assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
  4698. auto I = Pair.second.rbegin();
  4699. auto IS = IterSpaces.rbegin();
  4700. auto ILM = LoopMultipliers.rbegin();
  4701. Expr *UpCounterVal = CounterVal;
  4702. Expr *Multiplier = nullptr;
  4703. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4704. if (I->first) {
  4705. assert(IS->CounterStep);
  4706. Expr *NormalizedOffset =
  4707. SemaRef
  4708. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
  4709. I->first, IS->CounterStep)
  4710. .get();
  4711. if (Multiplier) {
  4712. NormalizedOffset =
  4713. SemaRef
  4714. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
  4715. NormalizedOffset, Multiplier)
  4716. .get();
  4717. }
  4718. assert(I->second == OO_Plus || I->second == OO_Minus);
  4719. BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
  4720. UpCounterVal = SemaRef
  4721. .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
  4722. UpCounterVal, NormalizedOffset)
  4723. .get();
  4724. }
  4725. Multiplier = *ILM;
  4726. ++I;
  4727. ++IS;
  4728. ++ILM;
  4729. }
  4730. Pair.first->setCounterValue(UpCounterVal);
  4731. }
  4732. }
  4733. return NestedLoopCount;
  4734. }
  4735. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4736. auto CollapseClauses =
  4737. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  4738. if (CollapseClauses.begin() != CollapseClauses.end())
  4739. return (*CollapseClauses.begin())->getNumForLoops();
  4740. return nullptr;
  4741. }
  4742. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4743. auto OrderedClauses =
  4744. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  4745. if (OrderedClauses.begin() != OrderedClauses.end())
  4746. return (*OrderedClauses.begin())->getNumForLoops();
  4747. return nullptr;
  4748. }
  4749. static bool checkSimdlenSafelenSpecified(Sema &S,
  4750. const ArrayRef<OMPClause *> Clauses) {
  4751. OMPSafelenClause *Safelen = nullptr;
  4752. OMPSimdlenClause *Simdlen = nullptr;
  4753. for (auto *Clause : Clauses) {
  4754. if (Clause->getClauseKind() == OMPC_safelen)
  4755. Safelen = cast<OMPSafelenClause>(Clause);
  4756. else if (Clause->getClauseKind() == OMPC_simdlen)
  4757. Simdlen = cast<OMPSimdlenClause>(Clause);
  4758. if (Safelen && Simdlen)
  4759. break;
  4760. }
  4761. if (Simdlen && Safelen) {
  4762. llvm::APSInt SimdlenRes, SafelenRes;
  4763. auto SimdlenLength = Simdlen->getSimdlen();
  4764. auto SafelenLength = Safelen->getSafelen();
  4765. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  4766. SimdlenLength->isInstantiationDependent() ||
  4767. SimdlenLength->containsUnexpandedParameterPack())
  4768. return false;
  4769. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  4770. SafelenLength->isInstantiationDependent() ||
  4771. SafelenLength->containsUnexpandedParameterPack())
  4772. return false;
  4773. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  4774. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  4775. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  4776. // If both simdlen and safelen clauses are specified, the value of the
  4777. // simdlen parameter must be less than or equal to the value of the safelen
  4778. // parameter.
  4779. if (SimdlenRes > SafelenRes) {
  4780. S.Diag(SimdlenLength->getExprLoc(),
  4781. diag::err_omp_wrong_simdlen_safelen_values)
  4782. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  4783. return true;
  4784. }
  4785. }
  4786. return false;
  4787. }
  4788. StmtResult Sema::ActOnOpenMPSimdDirective(
  4789. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4790. SourceLocation EndLoc,
  4791. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4792. if (!AStmt)
  4793. return StmtError();
  4794. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4795. OMPLoopDirective::HelperExprs B;
  4796. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4797. // define the nested loops number.
  4798. unsigned NestedLoopCount = CheckOpenMPLoop(
  4799. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4800. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4801. if (NestedLoopCount == 0)
  4802. return StmtError();
  4803. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4804. "omp simd loop exprs were not built");
  4805. if (!CurContext->isDependentContext()) {
  4806. // Finalize the clauses that need pre-built expressions for CodeGen.
  4807. for (auto C : Clauses) {
  4808. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4809. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4810. B.NumIterations, *this, CurScope,
  4811. DSAStack))
  4812. return StmtError();
  4813. }
  4814. }
  4815. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4816. return StmtError();
  4817. getCurFunction()->setHasBranchProtectedScope();
  4818. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4819. Clauses, AStmt, B);
  4820. }
  4821. StmtResult Sema::ActOnOpenMPForDirective(
  4822. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4823. SourceLocation EndLoc,
  4824. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4825. if (!AStmt)
  4826. return StmtError();
  4827. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4828. OMPLoopDirective::HelperExprs B;
  4829. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4830. // define the nested loops number.
  4831. unsigned NestedLoopCount = CheckOpenMPLoop(
  4832. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4833. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4834. if (NestedLoopCount == 0)
  4835. return StmtError();
  4836. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4837. "omp for loop exprs were not built");
  4838. if (!CurContext->isDependentContext()) {
  4839. // Finalize the clauses that need pre-built expressions for CodeGen.
  4840. for (auto C : Clauses) {
  4841. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4842. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4843. B.NumIterations, *this, CurScope,
  4844. DSAStack))
  4845. return StmtError();
  4846. }
  4847. }
  4848. getCurFunction()->setHasBranchProtectedScope();
  4849. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4850. Clauses, AStmt, B, DSAStack->isCancelRegion());
  4851. }
  4852. StmtResult Sema::ActOnOpenMPForSimdDirective(
  4853. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4854. SourceLocation EndLoc,
  4855. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4856. if (!AStmt)
  4857. return StmtError();
  4858. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4859. OMPLoopDirective::HelperExprs B;
  4860. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4861. // define the nested loops number.
  4862. unsigned NestedLoopCount =
  4863. CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  4864. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4865. VarsWithImplicitDSA, B);
  4866. if (NestedLoopCount == 0)
  4867. return StmtError();
  4868. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4869. "omp for simd loop exprs were not built");
  4870. if (!CurContext->isDependentContext()) {
  4871. // Finalize the clauses that need pre-built expressions for CodeGen.
  4872. for (auto C : Clauses) {
  4873. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4874. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4875. B.NumIterations, *this, CurScope,
  4876. DSAStack))
  4877. return StmtError();
  4878. }
  4879. }
  4880. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4881. return StmtError();
  4882. getCurFunction()->setHasBranchProtectedScope();
  4883. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4884. Clauses, AStmt, B);
  4885. }
  4886. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4887. Stmt *AStmt,
  4888. SourceLocation StartLoc,
  4889. SourceLocation EndLoc) {
  4890. if (!AStmt)
  4891. return StmtError();
  4892. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4893. auto BaseStmt = AStmt;
  4894. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4895. BaseStmt = CS->getCapturedStmt();
  4896. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4897. auto S = C->children();
  4898. if (S.begin() == S.end())
  4899. return StmtError();
  4900. // All associated statements must be '#pragma omp section' except for
  4901. // the first one.
  4902. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4903. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4904. if (SectionStmt)
  4905. Diag(SectionStmt->getLocStart(),
  4906. diag::err_omp_sections_substmt_not_section);
  4907. return StmtError();
  4908. }
  4909. cast<OMPSectionDirective>(SectionStmt)
  4910. ->setHasCancel(DSAStack->isCancelRegion());
  4911. }
  4912. } else {
  4913. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  4914. return StmtError();
  4915. }
  4916. getCurFunction()->setHasBranchProtectedScope();
  4917. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4918. DSAStack->isCancelRegion());
  4919. }
  4920. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  4921. SourceLocation StartLoc,
  4922. SourceLocation EndLoc) {
  4923. if (!AStmt)
  4924. return StmtError();
  4925. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4926. getCurFunction()->setHasBranchProtectedScope();
  4927. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  4928. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  4929. DSAStack->isCancelRegion());
  4930. }
  4931. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  4932. Stmt *AStmt,
  4933. SourceLocation StartLoc,
  4934. SourceLocation EndLoc) {
  4935. if (!AStmt)
  4936. return StmtError();
  4937. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4938. getCurFunction()->setHasBranchProtectedScope();
  4939. // OpenMP [2.7.3, single Construct, Restrictions]
  4940. // The copyprivate clause must not be used with the nowait clause.
  4941. OMPClause *Nowait = nullptr;
  4942. OMPClause *Copyprivate = nullptr;
  4943. for (auto *Clause : Clauses) {
  4944. if (Clause->getClauseKind() == OMPC_nowait)
  4945. Nowait = Clause;
  4946. else if (Clause->getClauseKind() == OMPC_copyprivate)
  4947. Copyprivate = Clause;
  4948. if (Copyprivate && Nowait) {
  4949. Diag(Copyprivate->getLocStart(),
  4950. diag::err_omp_single_copyprivate_with_nowait);
  4951. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  4952. return StmtError();
  4953. }
  4954. }
  4955. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4956. }
  4957. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  4958. SourceLocation StartLoc,
  4959. SourceLocation EndLoc) {
  4960. if (!AStmt)
  4961. return StmtError();
  4962. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4963. getCurFunction()->setHasBranchProtectedScope();
  4964. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4965. }
  4966. StmtResult Sema::ActOnOpenMPCriticalDirective(
  4967. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  4968. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  4969. if (!AStmt)
  4970. return StmtError();
  4971. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4972. bool ErrorFound = false;
  4973. llvm::APSInt Hint;
  4974. SourceLocation HintLoc;
  4975. bool DependentHint = false;
  4976. for (auto *C : Clauses) {
  4977. if (C->getClauseKind() == OMPC_hint) {
  4978. if (!DirName.getName()) {
  4979. Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
  4980. ErrorFound = true;
  4981. }
  4982. Expr *E = cast<OMPHintClause>(C)->getHint();
  4983. if (E->isTypeDependent() || E->isValueDependent() ||
  4984. E->isInstantiationDependent())
  4985. DependentHint = true;
  4986. else {
  4987. Hint = E->EvaluateKnownConstInt(Context);
  4988. HintLoc = C->getLocStart();
  4989. }
  4990. }
  4991. }
  4992. if (ErrorFound)
  4993. return StmtError();
  4994. auto Pair = DSAStack->getCriticalWithHint(DirName);
  4995. if (Pair.first && DirName.getName() && !DependentHint) {
  4996. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  4997. Diag(StartLoc, diag::err_omp_critical_with_hint);
  4998. if (HintLoc.isValid()) {
  4999. Diag(HintLoc, diag::note_omp_critical_hint_here)
  5000. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  5001. } else
  5002. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  5003. if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  5004. Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
  5005. << 1
  5006. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  5007. /*Radix=*/10, /*Signed=*/false);
  5008. } else
  5009. Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
  5010. }
  5011. }
  5012. getCurFunction()->setHasBranchProtectedScope();
  5013. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5014. Clauses, AStmt);
  5015. if (!Pair.first && DirName.getName() && !DependentHint)
  5016. DSAStack->addCriticalWithHint(Dir, Hint);
  5017. return Dir;
  5018. }
  5019. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5020. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5021. SourceLocation EndLoc,
  5022. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5023. if (!AStmt)
  5024. return StmtError();
  5025. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5026. // 1.2.2 OpenMP Language Terminology
  5027. // Structured block - An executable statement with a single entry at the
  5028. // top and a single exit at the bottom.
  5029. // The point of exit cannot be a branch out of the structured block.
  5030. // longjmp() and throw() must not violate the entry/exit criteria.
  5031. CS->getCapturedDecl()->setNothrow();
  5032. OMPLoopDirective::HelperExprs B;
  5033. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5034. // define the nested loops number.
  5035. unsigned NestedLoopCount =
  5036. CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5037. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5038. VarsWithImplicitDSA, B);
  5039. if (NestedLoopCount == 0)
  5040. return StmtError();
  5041. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5042. "omp parallel for loop exprs were not built");
  5043. if (!CurContext->isDependentContext()) {
  5044. // Finalize the clauses that need pre-built expressions for CodeGen.
  5045. for (auto C : Clauses) {
  5046. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5047. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5048. B.NumIterations, *this, CurScope,
  5049. DSAStack))
  5050. return StmtError();
  5051. }
  5052. }
  5053. getCurFunction()->setHasBranchProtectedScope();
  5054. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5055. NestedLoopCount, Clauses, AStmt, B,
  5056. DSAStack->isCancelRegion());
  5057. }
  5058. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5059. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5060. SourceLocation EndLoc,
  5061. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5062. if (!AStmt)
  5063. return StmtError();
  5064. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5065. // 1.2.2 OpenMP Language Terminology
  5066. // Structured block - An executable statement with a single entry at the
  5067. // top and a single exit at the bottom.
  5068. // The point of exit cannot be a branch out of the structured block.
  5069. // longjmp() and throw() must not violate the entry/exit criteria.
  5070. CS->getCapturedDecl()->setNothrow();
  5071. OMPLoopDirective::HelperExprs B;
  5072. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5073. // define the nested loops number.
  5074. unsigned NestedLoopCount =
  5075. CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5076. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5077. VarsWithImplicitDSA, B);
  5078. if (NestedLoopCount == 0)
  5079. return StmtError();
  5080. if (!CurContext->isDependentContext()) {
  5081. // Finalize the clauses that need pre-built expressions for CodeGen.
  5082. for (auto C : Clauses) {
  5083. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5084. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5085. B.NumIterations, *this, CurScope,
  5086. DSAStack))
  5087. return StmtError();
  5088. }
  5089. }
  5090. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5091. return StmtError();
  5092. getCurFunction()->setHasBranchProtectedScope();
  5093. return OMPParallelForSimdDirective::Create(
  5094. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5095. }
  5096. StmtResult
  5097. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5098. Stmt *AStmt, SourceLocation StartLoc,
  5099. SourceLocation EndLoc) {
  5100. if (!AStmt)
  5101. return StmtError();
  5102. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5103. auto BaseStmt = AStmt;
  5104. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5105. BaseStmt = CS->getCapturedStmt();
  5106. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5107. auto S = C->children();
  5108. if (S.begin() == S.end())
  5109. return StmtError();
  5110. // All associated statements must be '#pragma omp section' except for
  5111. // the first one.
  5112. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5113. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5114. if (SectionStmt)
  5115. Diag(SectionStmt->getLocStart(),
  5116. diag::err_omp_parallel_sections_substmt_not_section);
  5117. return StmtError();
  5118. }
  5119. cast<OMPSectionDirective>(SectionStmt)
  5120. ->setHasCancel(DSAStack->isCancelRegion());
  5121. }
  5122. } else {
  5123. Diag(AStmt->getLocStart(),
  5124. diag::err_omp_parallel_sections_not_compound_stmt);
  5125. return StmtError();
  5126. }
  5127. getCurFunction()->setHasBranchProtectedScope();
  5128. return OMPParallelSectionsDirective::Create(
  5129. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5130. }
  5131. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5132. Stmt *AStmt, SourceLocation StartLoc,
  5133. SourceLocation EndLoc) {
  5134. if (!AStmt)
  5135. return StmtError();
  5136. auto *CS = cast<CapturedStmt>(AStmt);
  5137. // 1.2.2 OpenMP Language Terminology
  5138. // Structured block - An executable statement with a single entry at the
  5139. // top and a single exit at the bottom.
  5140. // The point of exit cannot be a branch out of the structured block.
  5141. // longjmp() and throw() must not violate the entry/exit criteria.
  5142. CS->getCapturedDecl()->setNothrow();
  5143. getCurFunction()->setHasBranchProtectedScope();
  5144. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5145. DSAStack->isCancelRegion());
  5146. }
  5147. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5148. SourceLocation EndLoc) {
  5149. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5150. }
  5151. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5152. SourceLocation EndLoc) {
  5153. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5154. }
  5155. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5156. SourceLocation EndLoc) {
  5157. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5158. }
  5159. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5160. Stmt *AStmt,
  5161. SourceLocation StartLoc,
  5162. SourceLocation EndLoc) {
  5163. if (!AStmt)
  5164. return StmtError();
  5165. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5166. getCurFunction()->setHasBranchProtectedScope();
  5167. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5168. AStmt,
  5169. DSAStack->getTaskgroupReductionRef());
  5170. }
  5171. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5172. SourceLocation StartLoc,
  5173. SourceLocation EndLoc) {
  5174. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5175. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5176. }
  5177. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5178. Stmt *AStmt,
  5179. SourceLocation StartLoc,
  5180. SourceLocation EndLoc) {
  5181. OMPClause *DependFound = nullptr;
  5182. OMPClause *DependSourceClause = nullptr;
  5183. OMPClause *DependSinkClause = nullptr;
  5184. bool ErrorFound = false;
  5185. OMPThreadsClause *TC = nullptr;
  5186. OMPSIMDClause *SC = nullptr;
  5187. for (auto *C : Clauses) {
  5188. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5189. DependFound = C;
  5190. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5191. if (DependSourceClause) {
  5192. Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  5193. << getOpenMPDirectiveName(OMPD_ordered)
  5194. << getOpenMPClauseName(OMPC_depend) << 2;
  5195. ErrorFound = true;
  5196. } else
  5197. DependSourceClause = C;
  5198. if (DependSinkClause) {
  5199. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5200. << 0;
  5201. ErrorFound = true;
  5202. }
  5203. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5204. if (DependSourceClause) {
  5205. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5206. << 1;
  5207. ErrorFound = true;
  5208. }
  5209. DependSinkClause = C;
  5210. }
  5211. } else if (C->getClauseKind() == OMPC_threads)
  5212. TC = cast<OMPThreadsClause>(C);
  5213. else if (C->getClauseKind() == OMPC_simd)
  5214. SC = cast<OMPSIMDClause>(C);
  5215. }
  5216. if (!ErrorFound && !SC &&
  5217. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5218. // OpenMP [2.8.1,simd Construct, Restrictions]
  5219. // An ordered construct with the simd clause is the only OpenMP construct
  5220. // that can appear in the simd region.
  5221. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5222. ErrorFound = true;
  5223. } else if (DependFound && (TC || SC)) {
  5224. Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
  5225. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5226. ErrorFound = true;
  5227. } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
  5228. Diag(DependFound->getLocStart(),
  5229. diag::err_omp_ordered_directive_without_param);
  5230. ErrorFound = true;
  5231. } else if (TC || Clauses.empty()) {
  5232. if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
  5233. SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
  5234. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5235. << (TC != nullptr);
  5236. Diag(Param->getLocStart(), diag::note_omp_ordered_param);
  5237. ErrorFound = true;
  5238. }
  5239. }
  5240. if ((!AStmt && !DependFound) || ErrorFound)
  5241. return StmtError();
  5242. if (AStmt) {
  5243. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5244. getCurFunction()->setHasBranchProtectedScope();
  5245. }
  5246. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5247. }
  5248. namespace {
  5249. /// \brief Helper class for checking expression in 'omp atomic [update]'
  5250. /// construct.
  5251. class OpenMPAtomicUpdateChecker {
  5252. /// \brief Error results for atomic update expressions.
  5253. enum ExprAnalysisErrorCode {
  5254. /// \brief A statement is not an expression statement.
  5255. NotAnExpression,
  5256. /// \brief Expression is not builtin binary or unary operation.
  5257. NotABinaryOrUnaryExpression,
  5258. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  5259. NotAnUnaryIncDecExpression,
  5260. /// \brief An expression is not of scalar type.
  5261. NotAScalarType,
  5262. /// \brief A binary operation is not an assignment operation.
  5263. NotAnAssignmentOp,
  5264. /// \brief RHS part of the binary operation is not a binary expression.
  5265. NotABinaryExpression,
  5266. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  5267. /// expression.
  5268. NotABinaryOperator,
  5269. /// \brief RHS binary operation does not have reference to the updated LHS
  5270. /// part.
  5271. NotAnUpdateExpression,
  5272. /// \brief No errors is found.
  5273. NoError
  5274. };
  5275. /// \brief Reference to Sema.
  5276. Sema &SemaRef;
  5277. /// \brief A location for note diagnostics (when error is found).
  5278. SourceLocation NoteLoc;
  5279. /// \brief 'x' lvalue part of the source atomic expression.
  5280. Expr *X;
  5281. /// \brief 'expr' rvalue part of the source atomic expression.
  5282. Expr *E;
  5283. /// \brief Helper expression of the form
  5284. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5285. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5286. Expr *UpdateExpr;
  5287. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  5288. /// important for non-associative operations.
  5289. bool IsXLHSInRHSPart;
  5290. BinaryOperatorKind Op;
  5291. SourceLocation OpLoc;
  5292. /// \brief true if the source expression is a postfix unary operation, false
  5293. /// if it is a prefix unary operation.
  5294. bool IsPostfixUpdate;
  5295. public:
  5296. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5297. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5298. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5299. /// \brief Check specified statement that it is suitable for 'atomic update'
  5300. /// constructs and extract 'x', 'expr' and Operation from the original
  5301. /// expression. If DiagId and NoteId == 0, then only check is performed
  5302. /// without error notification.
  5303. /// \param DiagId Diagnostic which should be emitted if error is found.
  5304. /// \param NoteId Diagnostic note for the main error message.
  5305. /// \return true if statement is not an update expression, false otherwise.
  5306. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5307. /// \brief Return the 'x' lvalue part of the source atomic expression.
  5308. Expr *getX() const { return X; }
  5309. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  5310. Expr *getExpr() const { return E; }
  5311. /// \brief Return the update expression used in calculation of the updated
  5312. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5313. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5314. Expr *getUpdateExpr() const { return UpdateExpr; }
  5315. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  5316. /// false otherwise.
  5317. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5318. /// \brief true if the source expression is a postfix unary operation, false
  5319. /// if it is a prefix unary operation.
  5320. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5321. private:
  5322. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5323. unsigned NoteId = 0);
  5324. };
  5325. } // namespace
  5326. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5327. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5328. ExprAnalysisErrorCode ErrorFound = NoError;
  5329. SourceLocation ErrorLoc, NoteLoc;
  5330. SourceRange ErrorRange, NoteRange;
  5331. // Allowed constructs are:
  5332. // x = x binop expr;
  5333. // x = expr binop x;
  5334. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5335. X = AtomicBinOp->getLHS();
  5336. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5337. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5338. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5339. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5340. AtomicInnerBinOp->isBitwiseOp()) {
  5341. Op = AtomicInnerBinOp->getOpcode();
  5342. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5343. auto *LHS = AtomicInnerBinOp->getLHS();
  5344. auto *RHS = AtomicInnerBinOp->getRHS();
  5345. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5346. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5347. /*Canonical=*/true);
  5348. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5349. /*Canonical=*/true);
  5350. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5351. /*Canonical=*/true);
  5352. if (XId == LHSId) {
  5353. E = RHS;
  5354. IsXLHSInRHSPart = true;
  5355. } else if (XId == RHSId) {
  5356. E = LHS;
  5357. IsXLHSInRHSPart = false;
  5358. } else {
  5359. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5360. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5361. NoteLoc = X->getExprLoc();
  5362. NoteRange = X->getSourceRange();
  5363. ErrorFound = NotAnUpdateExpression;
  5364. }
  5365. } else {
  5366. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5367. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5368. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5369. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5370. ErrorFound = NotABinaryOperator;
  5371. }
  5372. } else {
  5373. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5374. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5375. ErrorFound = NotABinaryExpression;
  5376. }
  5377. } else {
  5378. ErrorLoc = AtomicBinOp->getExprLoc();
  5379. ErrorRange = AtomicBinOp->getSourceRange();
  5380. NoteLoc = AtomicBinOp->getOperatorLoc();
  5381. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5382. ErrorFound = NotAnAssignmentOp;
  5383. }
  5384. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5385. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5386. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5387. return true;
  5388. } else if (SemaRef.CurContext->isDependentContext())
  5389. E = X = UpdateExpr = nullptr;
  5390. return ErrorFound != NoError;
  5391. }
  5392. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5393. unsigned NoteId) {
  5394. ExprAnalysisErrorCode ErrorFound = NoError;
  5395. SourceLocation ErrorLoc, NoteLoc;
  5396. SourceRange ErrorRange, NoteRange;
  5397. // Allowed constructs are:
  5398. // x++;
  5399. // x--;
  5400. // ++x;
  5401. // --x;
  5402. // x binop= expr;
  5403. // x = x binop expr;
  5404. // x = expr binop x;
  5405. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5406. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5407. if (AtomicBody->getType()->isScalarType() ||
  5408. AtomicBody->isInstantiationDependent()) {
  5409. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5410. AtomicBody->IgnoreParenImpCasts())) {
  5411. // Check for Compound Assignment Operation
  5412. Op = BinaryOperator::getOpForCompoundAssignment(
  5413. AtomicCompAssignOp->getOpcode());
  5414. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5415. E = AtomicCompAssignOp->getRHS();
  5416. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5417. IsXLHSInRHSPart = true;
  5418. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5419. AtomicBody->IgnoreParenImpCasts())) {
  5420. // Check for Binary Operation
  5421. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5422. return true;
  5423. } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5424. AtomicBody->IgnoreParenImpCasts())) {
  5425. // Check for Unary Operation
  5426. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5427. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5428. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5429. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5430. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5431. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5432. IsXLHSInRHSPart = true;
  5433. } else {
  5434. ErrorFound = NotAnUnaryIncDecExpression;
  5435. ErrorLoc = AtomicUnaryOp->getExprLoc();
  5436. ErrorRange = AtomicUnaryOp->getSourceRange();
  5437. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  5438. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5439. }
  5440. } else if (!AtomicBody->isInstantiationDependent()) {
  5441. ErrorFound = NotABinaryOrUnaryExpression;
  5442. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  5443. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  5444. }
  5445. } else {
  5446. ErrorFound = NotAScalarType;
  5447. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  5448. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5449. }
  5450. } else {
  5451. ErrorFound = NotAnExpression;
  5452. NoteLoc = ErrorLoc = S->getLocStart();
  5453. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5454. }
  5455. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5456. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5457. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5458. return true;
  5459. } else if (SemaRef.CurContext->isDependentContext())
  5460. E = X = UpdateExpr = nullptr;
  5461. if (ErrorFound == NoError && E && X) {
  5462. // Build an update expression of form 'OpaqueValueExpr(x) binop
  5463. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  5464. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  5465. auto *OVEX = new (SemaRef.getASTContext())
  5466. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  5467. auto *OVEExpr = new (SemaRef.getASTContext())
  5468. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  5469. auto Update =
  5470. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  5471. IsXLHSInRHSPart ? OVEExpr : OVEX);
  5472. if (Update.isInvalid())
  5473. return true;
  5474. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  5475. Sema::AA_Casting);
  5476. if (Update.isInvalid())
  5477. return true;
  5478. UpdateExpr = Update.get();
  5479. }
  5480. return ErrorFound != NoError;
  5481. }
  5482. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  5483. Stmt *AStmt,
  5484. SourceLocation StartLoc,
  5485. SourceLocation EndLoc) {
  5486. if (!AStmt)
  5487. return StmtError();
  5488. auto *CS = cast<CapturedStmt>(AStmt);
  5489. // 1.2.2 OpenMP Language Terminology
  5490. // Structured block - An executable statement with a single entry at the
  5491. // top and a single exit at the bottom.
  5492. // The point of exit cannot be a branch out of the structured block.
  5493. // longjmp() and throw() must not violate the entry/exit criteria.
  5494. OpenMPClauseKind AtomicKind = OMPC_unknown;
  5495. SourceLocation AtomicKindLoc;
  5496. for (auto *C : Clauses) {
  5497. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  5498. C->getClauseKind() == OMPC_update ||
  5499. C->getClauseKind() == OMPC_capture) {
  5500. if (AtomicKind != OMPC_unknown) {
  5501. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  5502. << SourceRange(C->getLocStart(), C->getLocEnd());
  5503. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  5504. << getOpenMPClauseName(AtomicKind);
  5505. } else {
  5506. AtomicKind = C->getClauseKind();
  5507. AtomicKindLoc = C->getLocStart();
  5508. }
  5509. }
  5510. }
  5511. auto Body = CS->getCapturedStmt();
  5512. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  5513. Body = EWC->getSubExpr();
  5514. Expr *X = nullptr;
  5515. Expr *V = nullptr;
  5516. Expr *E = nullptr;
  5517. Expr *UE = nullptr;
  5518. bool IsXLHSInRHSPart = false;
  5519. bool IsPostfixUpdate = false;
  5520. // OpenMP [2.12.6, atomic Construct]
  5521. // In the next expressions:
  5522. // * x and v (as applicable) are both l-value expressions with scalar type.
  5523. // * During the execution of an atomic region, multiple syntactic
  5524. // occurrences of x must designate the same storage location.
  5525. // * Neither of v and expr (as applicable) may access the storage location
  5526. // designated by x.
  5527. // * Neither of x and expr (as applicable) may access the storage location
  5528. // designated by v.
  5529. // * expr is an expression with scalar type.
  5530. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  5531. // * binop, binop=, ++, and -- are not overloaded operators.
  5532. // * The expression x binop expr must be numerically equivalent to x binop
  5533. // (expr). This requirement is satisfied if the operators in expr have
  5534. // precedence greater than binop, or by using parentheses around expr or
  5535. // subexpressions of expr.
  5536. // * The expression expr binop x must be numerically equivalent to (expr)
  5537. // binop x. This requirement is satisfied if the operators in expr have
  5538. // precedence equal to or greater than binop, or by using parentheses around
  5539. // expr or subexpressions of expr.
  5540. // * For forms that allow multiple occurrences of x, the number of times
  5541. // that x is evaluated is unspecified.
  5542. if (AtomicKind == OMPC_read) {
  5543. enum {
  5544. NotAnExpression,
  5545. NotAnAssignmentOp,
  5546. NotAScalarType,
  5547. NotAnLValue,
  5548. NoError
  5549. } ErrorFound = NoError;
  5550. SourceLocation ErrorLoc, NoteLoc;
  5551. SourceRange ErrorRange, NoteRange;
  5552. // If clause is read:
  5553. // v = x;
  5554. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5555. auto *AtomicBinOp =
  5556. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5557. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5558. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5559. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  5560. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5561. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  5562. if (!X->isLValue() || !V->isLValue()) {
  5563. auto NotLValueExpr = X->isLValue() ? V : X;
  5564. ErrorFound = NotAnLValue;
  5565. ErrorLoc = AtomicBinOp->getExprLoc();
  5566. ErrorRange = AtomicBinOp->getSourceRange();
  5567. NoteLoc = NotLValueExpr->getExprLoc();
  5568. NoteRange = NotLValueExpr->getSourceRange();
  5569. }
  5570. } else if (!X->isInstantiationDependent() ||
  5571. !V->isInstantiationDependent()) {
  5572. auto NotScalarExpr =
  5573. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5574. ? V
  5575. : X;
  5576. ErrorFound = NotAScalarType;
  5577. ErrorLoc = AtomicBinOp->getExprLoc();
  5578. ErrorRange = AtomicBinOp->getSourceRange();
  5579. NoteLoc = NotScalarExpr->getExprLoc();
  5580. NoteRange = NotScalarExpr->getSourceRange();
  5581. }
  5582. } else if (!AtomicBody->isInstantiationDependent()) {
  5583. ErrorFound = NotAnAssignmentOp;
  5584. ErrorLoc = AtomicBody->getExprLoc();
  5585. ErrorRange = AtomicBody->getSourceRange();
  5586. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5587. : AtomicBody->getExprLoc();
  5588. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5589. : AtomicBody->getSourceRange();
  5590. }
  5591. } else {
  5592. ErrorFound = NotAnExpression;
  5593. NoteLoc = ErrorLoc = Body->getLocStart();
  5594. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5595. }
  5596. if (ErrorFound != NoError) {
  5597. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  5598. << ErrorRange;
  5599. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5600. << NoteRange;
  5601. return StmtError();
  5602. } else if (CurContext->isDependentContext())
  5603. V = X = nullptr;
  5604. } else if (AtomicKind == OMPC_write) {
  5605. enum {
  5606. NotAnExpression,
  5607. NotAnAssignmentOp,
  5608. NotAScalarType,
  5609. NotAnLValue,
  5610. NoError
  5611. } ErrorFound = NoError;
  5612. SourceLocation ErrorLoc, NoteLoc;
  5613. SourceRange ErrorRange, NoteRange;
  5614. // If clause is write:
  5615. // x = expr;
  5616. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5617. auto *AtomicBinOp =
  5618. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5619. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5620. X = AtomicBinOp->getLHS();
  5621. E = AtomicBinOp->getRHS();
  5622. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5623. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  5624. if (!X->isLValue()) {
  5625. ErrorFound = NotAnLValue;
  5626. ErrorLoc = AtomicBinOp->getExprLoc();
  5627. ErrorRange = AtomicBinOp->getSourceRange();
  5628. NoteLoc = X->getExprLoc();
  5629. NoteRange = X->getSourceRange();
  5630. }
  5631. } else if (!X->isInstantiationDependent() ||
  5632. !E->isInstantiationDependent()) {
  5633. auto NotScalarExpr =
  5634. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5635. ? E
  5636. : X;
  5637. ErrorFound = NotAScalarType;
  5638. ErrorLoc = AtomicBinOp->getExprLoc();
  5639. ErrorRange = AtomicBinOp->getSourceRange();
  5640. NoteLoc = NotScalarExpr->getExprLoc();
  5641. NoteRange = NotScalarExpr->getSourceRange();
  5642. }
  5643. } else if (!AtomicBody->isInstantiationDependent()) {
  5644. ErrorFound = NotAnAssignmentOp;
  5645. ErrorLoc = AtomicBody->getExprLoc();
  5646. ErrorRange = AtomicBody->getSourceRange();
  5647. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5648. : AtomicBody->getExprLoc();
  5649. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5650. : AtomicBody->getSourceRange();
  5651. }
  5652. } else {
  5653. ErrorFound = NotAnExpression;
  5654. NoteLoc = ErrorLoc = Body->getLocStart();
  5655. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5656. }
  5657. if (ErrorFound != NoError) {
  5658. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  5659. << ErrorRange;
  5660. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5661. << NoteRange;
  5662. return StmtError();
  5663. } else if (CurContext->isDependentContext())
  5664. E = X = nullptr;
  5665. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  5666. // If clause is update:
  5667. // x++;
  5668. // x--;
  5669. // ++x;
  5670. // --x;
  5671. // x binop= expr;
  5672. // x = x binop expr;
  5673. // x = expr binop x;
  5674. OpenMPAtomicUpdateChecker Checker(*this);
  5675. if (Checker.checkStatement(
  5676. Body, (AtomicKind == OMPC_update)
  5677. ? diag::err_omp_atomic_update_not_expression_statement
  5678. : diag::err_omp_atomic_not_expression_statement,
  5679. diag::note_omp_atomic_update))
  5680. return StmtError();
  5681. if (!CurContext->isDependentContext()) {
  5682. E = Checker.getExpr();
  5683. X = Checker.getX();
  5684. UE = Checker.getUpdateExpr();
  5685. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5686. }
  5687. } else if (AtomicKind == OMPC_capture) {
  5688. enum {
  5689. NotAnAssignmentOp,
  5690. NotACompoundStatement,
  5691. NotTwoSubstatements,
  5692. NotASpecificExpression,
  5693. NoError
  5694. } ErrorFound = NoError;
  5695. SourceLocation ErrorLoc, NoteLoc;
  5696. SourceRange ErrorRange, NoteRange;
  5697. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5698. // If clause is a capture:
  5699. // v = x++;
  5700. // v = x--;
  5701. // v = ++x;
  5702. // v = --x;
  5703. // v = x binop= expr;
  5704. // v = x = x binop expr;
  5705. // v = x = expr binop x;
  5706. auto *AtomicBinOp =
  5707. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5708. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5709. V = AtomicBinOp->getLHS();
  5710. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5711. OpenMPAtomicUpdateChecker Checker(*this);
  5712. if (Checker.checkStatement(
  5713. Body, diag::err_omp_atomic_capture_not_expression_statement,
  5714. diag::note_omp_atomic_update))
  5715. return StmtError();
  5716. E = Checker.getExpr();
  5717. X = Checker.getX();
  5718. UE = Checker.getUpdateExpr();
  5719. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5720. IsPostfixUpdate = Checker.isPostfixUpdate();
  5721. } else if (!AtomicBody->isInstantiationDependent()) {
  5722. ErrorLoc = AtomicBody->getExprLoc();
  5723. ErrorRange = AtomicBody->getSourceRange();
  5724. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5725. : AtomicBody->getExprLoc();
  5726. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5727. : AtomicBody->getSourceRange();
  5728. ErrorFound = NotAnAssignmentOp;
  5729. }
  5730. if (ErrorFound != NoError) {
  5731. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  5732. << ErrorRange;
  5733. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5734. return StmtError();
  5735. } else if (CurContext->isDependentContext()) {
  5736. UE = V = E = X = nullptr;
  5737. }
  5738. } else {
  5739. // If clause is a capture:
  5740. // { v = x; x = expr; }
  5741. // { v = x; x++; }
  5742. // { v = x; x--; }
  5743. // { v = x; ++x; }
  5744. // { v = x; --x; }
  5745. // { v = x; x binop= expr; }
  5746. // { v = x; x = x binop expr; }
  5747. // { v = x; x = expr binop x; }
  5748. // { x++; v = x; }
  5749. // { x--; v = x; }
  5750. // { ++x; v = x; }
  5751. // { --x; v = x; }
  5752. // { x binop= expr; v = x; }
  5753. // { x = x binop expr; v = x; }
  5754. // { x = expr binop x; v = x; }
  5755. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  5756. // Check that this is { expr1; expr2; }
  5757. if (CS->size() == 2) {
  5758. auto *First = CS->body_front();
  5759. auto *Second = CS->body_back();
  5760. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  5761. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  5762. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  5763. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  5764. // Need to find what subexpression is 'v' and what is 'x'.
  5765. OpenMPAtomicUpdateChecker Checker(*this);
  5766. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  5767. BinaryOperator *BinOp = nullptr;
  5768. if (IsUpdateExprFound) {
  5769. BinOp = dyn_cast<BinaryOperator>(First);
  5770. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5771. }
  5772. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5773. // { v = x; x++; }
  5774. // { v = x; x--; }
  5775. // { v = x; ++x; }
  5776. // { v = x; --x; }
  5777. // { v = x; x binop= expr; }
  5778. // { v = x; x = x binop expr; }
  5779. // { v = x; x = expr binop x; }
  5780. // Check that the first expression has form v = x.
  5781. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5782. llvm::FoldingSetNodeID XId, PossibleXId;
  5783. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5784. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5785. IsUpdateExprFound = XId == PossibleXId;
  5786. if (IsUpdateExprFound) {
  5787. V = BinOp->getLHS();
  5788. X = Checker.getX();
  5789. E = Checker.getExpr();
  5790. UE = Checker.getUpdateExpr();
  5791. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5792. IsPostfixUpdate = true;
  5793. }
  5794. }
  5795. if (!IsUpdateExprFound) {
  5796. IsUpdateExprFound = !Checker.checkStatement(First);
  5797. BinOp = nullptr;
  5798. if (IsUpdateExprFound) {
  5799. BinOp = dyn_cast<BinaryOperator>(Second);
  5800. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5801. }
  5802. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5803. // { x++; v = x; }
  5804. // { x--; v = x; }
  5805. // { ++x; v = x; }
  5806. // { --x; v = x; }
  5807. // { x binop= expr; v = x; }
  5808. // { x = x binop expr; v = x; }
  5809. // { x = expr binop x; v = x; }
  5810. // Check that the second expression has form v = x.
  5811. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5812. llvm::FoldingSetNodeID XId, PossibleXId;
  5813. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5814. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5815. IsUpdateExprFound = XId == PossibleXId;
  5816. if (IsUpdateExprFound) {
  5817. V = BinOp->getLHS();
  5818. X = Checker.getX();
  5819. E = Checker.getExpr();
  5820. UE = Checker.getUpdateExpr();
  5821. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5822. IsPostfixUpdate = false;
  5823. }
  5824. }
  5825. }
  5826. if (!IsUpdateExprFound) {
  5827. // { v = x; x = expr; }
  5828. auto *FirstExpr = dyn_cast<Expr>(First);
  5829. auto *SecondExpr = dyn_cast<Expr>(Second);
  5830. if (!FirstExpr || !SecondExpr ||
  5831. !(FirstExpr->isInstantiationDependent() ||
  5832. SecondExpr->isInstantiationDependent())) {
  5833. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  5834. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  5835. ErrorFound = NotAnAssignmentOp;
  5836. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  5837. : First->getLocStart();
  5838. NoteRange = ErrorRange = FirstBinOp
  5839. ? FirstBinOp->getSourceRange()
  5840. : SourceRange(ErrorLoc, ErrorLoc);
  5841. } else {
  5842. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  5843. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  5844. ErrorFound = NotAnAssignmentOp;
  5845. NoteLoc = ErrorLoc = SecondBinOp
  5846. ? SecondBinOp->getOperatorLoc()
  5847. : Second->getLocStart();
  5848. NoteRange = ErrorRange =
  5849. SecondBinOp ? SecondBinOp->getSourceRange()
  5850. : SourceRange(ErrorLoc, ErrorLoc);
  5851. } else {
  5852. auto *PossibleXRHSInFirst =
  5853. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  5854. auto *PossibleXLHSInSecond =
  5855. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  5856. llvm::FoldingSetNodeID X1Id, X2Id;
  5857. PossibleXRHSInFirst->Profile(X1Id, Context,
  5858. /*Canonical=*/true);
  5859. PossibleXLHSInSecond->Profile(X2Id, Context,
  5860. /*Canonical=*/true);
  5861. IsUpdateExprFound = X1Id == X2Id;
  5862. if (IsUpdateExprFound) {
  5863. V = FirstBinOp->getLHS();
  5864. X = SecondBinOp->getLHS();
  5865. E = SecondBinOp->getRHS();
  5866. UE = nullptr;
  5867. IsXLHSInRHSPart = false;
  5868. IsPostfixUpdate = true;
  5869. } else {
  5870. ErrorFound = NotASpecificExpression;
  5871. ErrorLoc = FirstBinOp->getExprLoc();
  5872. ErrorRange = FirstBinOp->getSourceRange();
  5873. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  5874. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  5875. }
  5876. }
  5877. }
  5878. }
  5879. }
  5880. } else {
  5881. NoteLoc = ErrorLoc = Body->getLocStart();
  5882. NoteRange = ErrorRange =
  5883. SourceRange(Body->getLocStart(), Body->getLocStart());
  5884. ErrorFound = NotTwoSubstatements;
  5885. }
  5886. } else {
  5887. NoteLoc = ErrorLoc = Body->getLocStart();
  5888. NoteRange = ErrorRange =
  5889. SourceRange(Body->getLocStart(), Body->getLocStart());
  5890. ErrorFound = NotACompoundStatement;
  5891. }
  5892. if (ErrorFound != NoError) {
  5893. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  5894. << ErrorRange;
  5895. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5896. return StmtError();
  5897. } else if (CurContext->isDependentContext()) {
  5898. UE = V = E = X = nullptr;
  5899. }
  5900. }
  5901. }
  5902. getCurFunction()->setHasBranchProtectedScope();
  5903. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5904. X, V, E, UE, IsXLHSInRHSPart,
  5905. IsPostfixUpdate);
  5906. }
  5907. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  5908. Stmt *AStmt,
  5909. SourceLocation StartLoc,
  5910. SourceLocation EndLoc) {
  5911. if (!AStmt)
  5912. return StmtError();
  5913. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5914. // 1.2.2 OpenMP Language Terminology
  5915. // Structured block - An executable statement with a single entry at the
  5916. // top and a single exit at the bottom.
  5917. // The point of exit cannot be a branch out of the structured block.
  5918. // longjmp() and throw() must not violate the entry/exit criteria.
  5919. CS->getCapturedDecl()->setNothrow();
  5920. // OpenMP [2.16, Nesting of Regions]
  5921. // If specified, a teams construct must be contained within a target
  5922. // construct. That target construct must contain no statements or directives
  5923. // outside of the teams construct.
  5924. if (DSAStack->hasInnerTeamsRegion()) {
  5925. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  5926. bool OMPTeamsFound = true;
  5927. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  5928. auto I = CS->body_begin();
  5929. while (I != CS->body_end()) {
  5930. auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  5931. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  5932. OMPTeamsFound = false;
  5933. break;
  5934. }
  5935. ++I;
  5936. }
  5937. assert(I != CS->body_end() && "Not found statement");
  5938. S = *I;
  5939. } else {
  5940. auto *OED = dyn_cast<OMPExecutableDirective>(S);
  5941. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  5942. }
  5943. if (!OMPTeamsFound) {
  5944. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  5945. Diag(DSAStack->getInnerTeamsRegionLoc(),
  5946. diag::note_omp_nested_teams_construct_here);
  5947. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  5948. << isa<OMPExecutableDirective>(S);
  5949. return StmtError();
  5950. }
  5951. }
  5952. getCurFunction()->setHasBranchProtectedScope();
  5953. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5954. }
  5955. StmtResult
  5956. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  5957. Stmt *AStmt, SourceLocation StartLoc,
  5958. SourceLocation EndLoc) {
  5959. if (!AStmt)
  5960. return StmtError();
  5961. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5962. // 1.2.2 OpenMP Language Terminology
  5963. // Structured block - An executable statement with a single entry at the
  5964. // top and a single exit at the bottom.
  5965. // The point of exit cannot be a branch out of the structured block.
  5966. // longjmp() and throw() must not violate the entry/exit criteria.
  5967. CS->getCapturedDecl()->setNothrow();
  5968. getCurFunction()->setHasBranchProtectedScope();
  5969. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5970. AStmt);
  5971. }
  5972. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  5973. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5974. SourceLocation EndLoc,
  5975. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5976. if (!AStmt)
  5977. return StmtError();
  5978. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5979. // 1.2.2 OpenMP Language Terminology
  5980. // Structured block - An executable statement with a single entry at the
  5981. // top and a single exit at the bottom.
  5982. // The point of exit cannot be a branch out of the structured block.
  5983. // longjmp() and throw() must not violate the entry/exit criteria.
  5984. CS->getCapturedDecl()->setNothrow();
  5985. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  5986. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  5987. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  5988. // 1.2.2 OpenMP Language Terminology
  5989. // Structured block - An executable statement with a single entry at the
  5990. // top and a single exit at the bottom.
  5991. // The point of exit cannot be a branch out of the structured block.
  5992. // longjmp() and throw() must not violate the entry/exit criteria.
  5993. CS->getCapturedDecl()->setNothrow();
  5994. }
  5995. OMPLoopDirective::HelperExprs B;
  5996. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5997. // define the nested loops number.
  5998. unsigned NestedLoopCount =
  5999. CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  6000. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6001. VarsWithImplicitDSA, B);
  6002. if (NestedLoopCount == 0)
  6003. return StmtError();
  6004. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6005. "omp target parallel for loop exprs were not built");
  6006. if (!CurContext->isDependentContext()) {
  6007. // Finalize the clauses that need pre-built expressions for CodeGen.
  6008. for (auto C : Clauses) {
  6009. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6010. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6011. B.NumIterations, *this, CurScope,
  6012. DSAStack))
  6013. return StmtError();
  6014. }
  6015. }
  6016. getCurFunction()->setHasBranchProtectedScope();
  6017. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6018. NestedLoopCount, Clauses, AStmt,
  6019. B, DSAStack->isCancelRegion());
  6020. }
  6021. /// Check for existence of a map clause in the list of clauses.
  6022. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6023. const OpenMPClauseKind K) {
  6024. return llvm::any_of(
  6025. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6026. }
  6027. template <typename... Params>
  6028. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6029. const Params... ClauseTypes) {
  6030. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6031. }
  6032. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6033. Stmt *AStmt,
  6034. SourceLocation StartLoc,
  6035. SourceLocation EndLoc) {
  6036. if (!AStmt)
  6037. return StmtError();
  6038. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6039. // OpenMP [2.10.1, Restrictions, p. 97]
  6040. // At least one map clause must appear on the directive.
  6041. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6042. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6043. << "'map' or 'use_device_ptr'"
  6044. << getOpenMPDirectiveName(OMPD_target_data);
  6045. return StmtError();
  6046. }
  6047. getCurFunction()->setHasBranchProtectedScope();
  6048. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6049. AStmt);
  6050. }
  6051. StmtResult
  6052. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6053. SourceLocation StartLoc,
  6054. SourceLocation EndLoc, Stmt *AStmt) {
  6055. if (!AStmt)
  6056. return StmtError();
  6057. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6058. // 1.2.2 OpenMP Language Terminology
  6059. // Structured block - An executable statement with a single entry at the
  6060. // top and a single exit at the bottom.
  6061. // The point of exit cannot be a branch out of the structured block.
  6062. // longjmp() and throw() must not violate the entry/exit criteria.
  6063. CS->getCapturedDecl()->setNothrow();
  6064. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6065. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6066. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6067. // 1.2.2 OpenMP Language Terminology
  6068. // Structured block - An executable statement with a single entry at the
  6069. // top and a single exit at the bottom.
  6070. // The point of exit cannot be a branch out of the structured block.
  6071. // longjmp() and throw() must not violate the entry/exit criteria.
  6072. CS->getCapturedDecl()->setNothrow();
  6073. }
  6074. // OpenMP [2.10.2, Restrictions, p. 99]
  6075. // At least one map clause must appear on the directive.
  6076. if (!hasClauses(Clauses, OMPC_map)) {
  6077. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6078. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6079. return StmtError();
  6080. }
  6081. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6082. AStmt);
  6083. }
  6084. StmtResult
  6085. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6086. SourceLocation StartLoc,
  6087. SourceLocation EndLoc, Stmt *AStmt) {
  6088. if (!AStmt)
  6089. return StmtError();
  6090. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6091. // 1.2.2 OpenMP Language Terminology
  6092. // Structured block - An executable statement with a single entry at the
  6093. // top and a single exit at the bottom.
  6094. // The point of exit cannot be a branch out of the structured block.
  6095. // longjmp() and throw() must not violate the entry/exit criteria.
  6096. CS->getCapturedDecl()->setNothrow();
  6097. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6098. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6099. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6100. // 1.2.2 OpenMP Language Terminology
  6101. // Structured block - An executable statement with a single entry at the
  6102. // top and a single exit at the bottom.
  6103. // The point of exit cannot be a branch out of the structured block.
  6104. // longjmp() and throw() must not violate the entry/exit criteria.
  6105. CS->getCapturedDecl()->setNothrow();
  6106. }
  6107. // OpenMP [2.10.3, Restrictions, p. 102]
  6108. // At least one map clause must appear on the directive.
  6109. if (!hasClauses(Clauses, OMPC_map)) {
  6110. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6111. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6112. return StmtError();
  6113. }
  6114. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6115. AStmt);
  6116. }
  6117. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6118. SourceLocation StartLoc,
  6119. SourceLocation EndLoc,
  6120. Stmt *AStmt) {
  6121. if (!AStmt)
  6122. return StmtError();
  6123. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6124. // 1.2.2 OpenMP Language Terminology
  6125. // Structured block - An executable statement with a single entry at the
  6126. // top and a single exit at the bottom.
  6127. // The point of exit cannot be a branch out of the structured block.
  6128. // longjmp() and throw() must not violate the entry/exit criteria.
  6129. CS->getCapturedDecl()->setNothrow();
  6130. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6131. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6132. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6133. // 1.2.2 OpenMP Language Terminology
  6134. // Structured block - An executable statement with a single entry at the
  6135. // top and a single exit at the bottom.
  6136. // The point of exit cannot be a branch out of the structured block.
  6137. // longjmp() and throw() must not violate the entry/exit criteria.
  6138. CS->getCapturedDecl()->setNothrow();
  6139. }
  6140. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6141. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6142. return StmtError();
  6143. }
  6144. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6145. AStmt);
  6146. }
  6147. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6148. Stmt *AStmt, SourceLocation StartLoc,
  6149. SourceLocation EndLoc) {
  6150. if (!AStmt)
  6151. return StmtError();
  6152. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6153. // 1.2.2 OpenMP Language Terminology
  6154. // Structured block - An executable statement with a single entry at the
  6155. // top and a single exit at the bottom.
  6156. // The point of exit cannot be a branch out of the structured block.
  6157. // longjmp() and throw() must not violate the entry/exit criteria.
  6158. CS->getCapturedDecl()->setNothrow();
  6159. getCurFunction()->setHasBranchProtectedScope();
  6160. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6161. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6162. }
  6163. StmtResult
  6164. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6165. SourceLocation EndLoc,
  6166. OpenMPDirectiveKind CancelRegion) {
  6167. if (DSAStack->isParentNowaitRegion()) {
  6168. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6169. return StmtError();
  6170. }
  6171. if (DSAStack->isParentOrderedRegion()) {
  6172. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6173. return StmtError();
  6174. }
  6175. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6176. CancelRegion);
  6177. }
  6178. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6179. SourceLocation StartLoc,
  6180. SourceLocation EndLoc,
  6181. OpenMPDirectiveKind CancelRegion) {
  6182. if (DSAStack->isParentNowaitRegion()) {
  6183. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6184. return StmtError();
  6185. }
  6186. if (DSAStack->isParentOrderedRegion()) {
  6187. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6188. return StmtError();
  6189. }
  6190. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6191. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6192. CancelRegion);
  6193. }
  6194. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6195. ArrayRef<OMPClause *> Clauses) {
  6196. OMPClause *PrevClause = nullptr;
  6197. bool ErrorFound = false;
  6198. for (auto *C : Clauses) {
  6199. if (C->getClauseKind() == OMPC_grainsize ||
  6200. C->getClauseKind() == OMPC_num_tasks) {
  6201. if (!PrevClause)
  6202. PrevClause = C;
  6203. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6204. S.Diag(C->getLocStart(),
  6205. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6206. << getOpenMPClauseName(C->getClauseKind())
  6207. << getOpenMPClauseName(PrevClause->getClauseKind());
  6208. S.Diag(PrevClause->getLocStart(),
  6209. diag::note_omp_previous_grainsize_num_tasks)
  6210. << getOpenMPClauseName(PrevClause->getClauseKind());
  6211. ErrorFound = true;
  6212. }
  6213. }
  6214. }
  6215. return ErrorFound;
  6216. }
  6217. static bool checkReductionClauseWithNogroup(Sema &S,
  6218. ArrayRef<OMPClause *> Clauses) {
  6219. OMPClause *ReductionClause = nullptr;
  6220. OMPClause *NogroupClause = nullptr;
  6221. for (auto *C : Clauses) {
  6222. if (C->getClauseKind() == OMPC_reduction) {
  6223. ReductionClause = C;
  6224. if (NogroupClause)
  6225. break;
  6226. continue;
  6227. }
  6228. if (C->getClauseKind() == OMPC_nogroup) {
  6229. NogroupClause = C;
  6230. if (ReductionClause)
  6231. break;
  6232. continue;
  6233. }
  6234. }
  6235. if (ReductionClause && NogroupClause) {
  6236. S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
  6237. << SourceRange(NogroupClause->getLocStart(),
  6238. NogroupClause->getLocEnd());
  6239. return true;
  6240. }
  6241. return false;
  6242. }
  6243. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6244. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6245. SourceLocation EndLoc,
  6246. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6247. if (!AStmt)
  6248. return StmtError();
  6249. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6250. OMPLoopDirective::HelperExprs B;
  6251. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6252. // define the nested loops number.
  6253. unsigned NestedLoopCount =
  6254. CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6255. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6256. VarsWithImplicitDSA, B);
  6257. if (NestedLoopCount == 0)
  6258. return StmtError();
  6259. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6260. "omp for loop exprs were not built");
  6261. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6262. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6263. // not appear on the same taskloop directive.
  6264. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6265. return StmtError();
  6266. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6267. // If a reduction clause is present on the taskloop directive, the nogroup
  6268. // clause must not be specified.
  6269. if (checkReductionClauseWithNogroup(*this, Clauses))
  6270. return StmtError();
  6271. getCurFunction()->setHasBranchProtectedScope();
  6272. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6273. NestedLoopCount, Clauses, AStmt, B);
  6274. }
  6275. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6276. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6277. SourceLocation EndLoc,
  6278. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6279. if (!AStmt)
  6280. return StmtError();
  6281. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6282. OMPLoopDirective::HelperExprs B;
  6283. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6284. // define the nested loops number.
  6285. unsigned NestedLoopCount =
  6286. CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6287. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6288. VarsWithImplicitDSA, B);
  6289. if (NestedLoopCount == 0)
  6290. return StmtError();
  6291. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6292. "omp for loop exprs were not built");
  6293. if (!CurContext->isDependentContext()) {
  6294. // Finalize the clauses that need pre-built expressions for CodeGen.
  6295. for (auto C : Clauses) {
  6296. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6297. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6298. B.NumIterations, *this, CurScope,
  6299. DSAStack))
  6300. return StmtError();
  6301. }
  6302. }
  6303. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6304. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6305. // not appear on the same taskloop directive.
  6306. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6307. return StmtError();
  6308. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6309. // If a reduction clause is present on the taskloop directive, the nogroup
  6310. // clause must not be specified.
  6311. if (checkReductionClauseWithNogroup(*this, Clauses))
  6312. return StmtError();
  6313. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6314. return StmtError();
  6315. getCurFunction()->setHasBranchProtectedScope();
  6316. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6317. NestedLoopCount, Clauses, AStmt, B);
  6318. }
  6319. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6320. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6321. SourceLocation EndLoc,
  6322. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6323. if (!AStmt)
  6324. return StmtError();
  6325. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6326. OMPLoopDirective::HelperExprs B;
  6327. // In presence of clause 'collapse' with number of loops, it will
  6328. // define the nested loops number.
  6329. unsigned NestedLoopCount =
  6330. CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6331. nullptr /*ordered not a clause on distribute*/, AStmt,
  6332. *this, *DSAStack, VarsWithImplicitDSA, B);
  6333. if (NestedLoopCount == 0)
  6334. return StmtError();
  6335. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6336. "omp for loop exprs were not built");
  6337. getCurFunction()->setHasBranchProtectedScope();
  6338. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6339. NestedLoopCount, Clauses, AStmt, B);
  6340. }
  6341. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6342. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6343. SourceLocation EndLoc,
  6344. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6345. if (!AStmt)
  6346. return StmtError();
  6347. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6348. // 1.2.2 OpenMP Language Terminology
  6349. // Structured block - An executable statement with a single entry at the
  6350. // top and a single exit at the bottom.
  6351. // The point of exit cannot be a branch out of the structured block.
  6352. // longjmp() and throw() must not violate the entry/exit criteria.
  6353. CS->getCapturedDecl()->setNothrow();
  6354. for (int ThisCaptureLevel =
  6355. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  6356. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6357. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6358. // 1.2.2 OpenMP Language Terminology
  6359. // Structured block - An executable statement with a single entry at the
  6360. // top and a single exit at the bottom.
  6361. // The point of exit cannot be a branch out of the structured block.
  6362. // longjmp() and throw() must not violate the entry/exit criteria.
  6363. CS->getCapturedDecl()->setNothrow();
  6364. }
  6365. OMPLoopDirective::HelperExprs B;
  6366. // In presence of clause 'collapse' with number of loops, it will
  6367. // define the nested loops number.
  6368. unsigned NestedLoopCount = CheckOpenMPLoop(
  6369. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6370. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6371. VarsWithImplicitDSA, B);
  6372. if (NestedLoopCount == 0)
  6373. return StmtError();
  6374. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6375. "omp for loop exprs were not built");
  6376. getCurFunction()->setHasBranchProtectedScope();
  6377. return OMPDistributeParallelForDirective::Create(
  6378. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6379. DSAStack->isCancelRegion());
  6380. }
  6381. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6382. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6383. SourceLocation EndLoc,
  6384. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6385. if (!AStmt)
  6386. return StmtError();
  6387. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6388. // 1.2.2 OpenMP Language Terminology
  6389. // Structured block - An executable statement with a single entry at the
  6390. // top and a single exit at the bottom.
  6391. // The point of exit cannot be a branch out of the structured block.
  6392. // longjmp() and throw() must not violate the entry/exit criteria.
  6393. CS->getCapturedDecl()->setNothrow();
  6394. for (int ThisCaptureLevel =
  6395. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  6396. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6397. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6398. // 1.2.2 OpenMP Language Terminology
  6399. // Structured block - An executable statement with a single entry at the
  6400. // top and a single exit at the bottom.
  6401. // The point of exit cannot be a branch out of the structured block.
  6402. // longjmp() and throw() must not violate the entry/exit criteria.
  6403. CS->getCapturedDecl()->setNothrow();
  6404. }
  6405. OMPLoopDirective::HelperExprs B;
  6406. // In presence of clause 'collapse' with number of loops, it will
  6407. // define the nested loops number.
  6408. unsigned NestedLoopCount = CheckOpenMPLoop(
  6409. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6410. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6411. VarsWithImplicitDSA, B);
  6412. if (NestedLoopCount == 0)
  6413. return StmtError();
  6414. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6415. "omp for loop exprs were not built");
  6416. if (!CurContext->isDependentContext()) {
  6417. // Finalize the clauses that need pre-built expressions for CodeGen.
  6418. for (auto C : Clauses) {
  6419. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6420. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6421. B.NumIterations, *this, CurScope,
  6422. DSAStack))
  6423. return StmtError();
  6424. }
  6425. }
  6426. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6427. return StmtError();
  6428. getCurFunction()->setHasBranchProtectedScope();
  6429. return OMPDistributeParallelForSimdDirective::Create(
  6430. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6431. }
  6432. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  6433. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6434. SourceLocation EndLoc,
  6435. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6436. if (!AStmt)
  6437. return StmtError();
  6438. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6439. // 1.2.2 OpenMP Language Terminology
  6440. // Structured block - An executable statement with a single entry at the
  6441. // top and a single exit at the bottom.
  6442. // The point of exit cannot be a branch out of the structured block.
  6443. // longjmp() and throw() must not violate the entry/exit criteria.
  6444. CS->getCapturedDecl()->setNothrow();
  6445. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  6446. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6447. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6448. // 1.2.2 OpenMP Language Terminology
  6449. // Structured block - An executable statement with a single entry at the
  6450. // top and a single exit at the bottom.
  6451. // The point of exit cannot be a branch out of the structured block.
  6452. // longjmp() and throw() must not violate the entry/exit criteria.
  6453. CS->getCapturedDecl()->setNothrow();
  6454. }
  6455. OMPLoopDirective::HelperExprs B;
  6456. // In presence of clause 'collapse' with number of loops, it will
  6457. // define the nested loops number.
  6458. unsigned NestedLoopCount =
  6459. CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  6460. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6461. *DSAStack, VarsWithImplicitDSA, B);
  6462. if (NestedLoopCount == 0)
  6463. return StmtError();
  6464. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6465. "omp for loop exprs were not built");
  6466. if (!CurContext->isDependentContext()) {
  6467. // Finalize the clauses that need pre-built expressions for CodeGen.
  6468. for (auto C : Clauses) {
  6469. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6470. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6471. B.NumIterations, *this, CurScope,
  6472. DSAStack))
  6473. return StmtError();
  6474. }
  6475. }
  6476. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6477. return StmtError();
  6478. getCurFunction()->setHasBranchProtectedScope();
  6479. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  6480. NestedLoopCount, Clauses, AStmt, B);
  6481. }
  6482. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  6483. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6484. SourceLocation EndLoc,
  6485. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6486. if (!AStmt)
  6487. return StmtError();
  6488. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6489. // 1.2.2 OpenMP Language Terminology
  6490. // Structured block - An executable statement with a single entry at the
  6491. // top and a single exit at the bottom.
  6492. // The point of exit cannot be a branch out of the structured block.
  6493. // longjmp() and throw() must not violate the entry/exit criteria.
  6494. CS->getCapturedDecl()->setNothrow();
  6495. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6496. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6497. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6498. // 1.2.2 OpenMP Language Terminology
  6499. // Structured block - An executable statement with a single entry at the
  6500. // top and a single exit at the bottom.
  6501. // The point of exit cannot be a branch out of the structured block.
  6502. // longjmp() and throw() must not violate the entry/exit criteria.
  6503. CS->getCapturedDecl()->setNothrow();
  6504. }
  6505. OMPLoopDirective::HelperExprs B;
  6506. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6507. // define the nested loops number.
  6508. unsigned NestedLoopCount = CheckOpenMPLoop(
  6509. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6510. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6511. VarsWithImplicitDSA, B);
  6512. if (NestedLoopCount == 0)
  6513. return StmtError();
  6514. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6515. "omp target parallel for simd loop exprs were not built");
  6516. if (!CurContext->isDependentContext()) {
  6517. // Finalize the clauses that need pre-built expressions for CodeGen.
  6518. for (auto C : Clauses) {
  6519. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6520. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6521. B.NumIterations, *this, CurScope,
  6522. DSAStack))
  6523. return StmtError();
  6524. }
  6525. }
  6526. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6527. return StmtError();
  6528. getCurFunction()->setHasBranchProtectedScope();
  6529. return OMPTargetParallelForSimdDirective::Create(
  6530. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6531. }
  6532. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  6533. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6534. SourceLocation EndLoc,
  6535. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6536. if (!AStmt)
  6537. return StmtError();
  6538. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6539. // 1.2.2 OpenMP Language Terminology
  6540. // Structured block - An executable statement with a single entry at the
  6541. // top and a single exit at the bottom.
  6542. // The point of exit cannot be a branch out of the structured block.
  6543. // longjmp() and throw() must not violate the entry/exit criteria.
  6544. CS->getCapturedDecl()->setNothrow();
  6545. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  6546. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6547. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6548. // 1.2.2 OpenMP Language Terminology
  6549. // Structured block - An executable statement with a single entry at the
  6550. // top and a single exit at the bottom.
  6551. // The point of exit cannot be a branch out of the structured block.
  6552. // longjmp() and throw() must not violate the entry/exit criteria.
  6553. CS->getCapturedDecl()->setNothrow();
  6554. }
  6555. OMPLoopDirective::HelperExprs B;
  6556. // In presence of clause 'collapse' with number of loops, it will define the
  6557. // nested loops number.
  6558. unsigned NestedLoopCount =
  6559. CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  6560. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6561. VarsWithImplicitDSA, B);
  6562. if (NestedLoopCount == 0)
  6563. return StmtError();
  6564. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6565. "omp target simd loop exprs were not built");
  6566. if (!CurContext->isDependentContext()) {
  6567. // Finalize the clauses that need pre-built expressions for CodeGen.
  6568. for (auto C : Clauses) {
  6569. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6570. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6571. B.NumIterations, *this, CurScope,
  6572. DSAStack))
  6573. return StmtError();
  6574. }
  6575. }
  6576. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6577. return StmtError();
  6578. getCurFunction()->setHasBranchProtectedScope();
  6579. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  6580. NestedLoopCount, Clauses, AStmt, B);
  6581. }
  6582. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  6583. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6584. SourceLocation EndLoc,
  6585. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6586. if (!AStmt)
  6587. return StmtError();
  6588. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6589. // 1.2.2 OpenMP Language Terminology
  6590. // Structured block - An executable statement with a single entry at the
  6591. // top and a single exit at the bottom.
  6592. // The point of exit cannot be a branch out of the structured block.
  6593. // longjmp() and throw() must not violate the entry/exit criteria.
  6594. CS->getCapturedDecl()->setNothrow();
  6595. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  6596. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6597. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6598. // 1.2.2 OpenMP Language Terminology
  6599. // Structured block - An executable statement with a single entry at the
  6600. // top and a single exit at the bottom.
  6601. // The point of exit cannot be a branch out of the structured block.
  6602. // longjmp() and throw() must not violate the entry/exit criteria.
  6603. CS->getCapturedDecl()->setNothrow();
  6604. }
  6605. OMPLoopDirective::HelperExprs B;
  6606. // In presence of clause 'collapse' with number of loops, it will
  6607. // define the nested loops number.
  6608. unsigned NestedLoopCount =
  6609. CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  6610. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6611. *DSAStack, VarsWithImplicitDSA, B);
  6612. if (NestedLoopCount == 0)
  6613. return StmtError();
  6614. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6615. "omp teams distribute loop exprs were not built");
  6616. getCurFunction()->setHasBranchProtectedScope();
  6617. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6618. return OMPTeamsDistributeDirective::Create(
  6619. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6620. }
  6621. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  6622. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6623. SourceLocation EndLoc,
  6624. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6625. if (!AStmt)
  6626. return StmtError();
  6627. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6628. // 1.2.2 OpenMP Language Terminology
  6629. // Structured block - An executable statement with a single entry at the
  6630. // top and a single exit at the bottom.
  6631. // The point of exit cannot be a branch out of the structured block.
  6632. // longjmp() and throw() must not violate the entry/exit criteria.
  6633. CS->getCapturedDecl()->setNothrow();
  6634. for (int ThisCaptureLevel =
  6635. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  6636. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6637. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6638. // 1.2.2 OpenMP Language Terminology
  6639. // Structured block - An executable statement with a single entry at the
  6640. // top and a single exit at the bottom.
  6641. // The point of exit cannot be a branch out of the structured block.
  6642. // longjmp() and throw() must not violate the entry/exit criteria.
  6643. CS->getCapturedDecl()->setNothrow();
  6644. }
  6645. OMPLoopDirective::HelperExprs B;
  6646. // In presence of clause 'collapse' with number of loops, it will
  6647. // define the nested loops number.
  6648. unsigned NestedLoopCount = CheckOpenMPLoop(
  6649. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6650. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6651. VarsWithImplicitDSA, B);
  6652. if (NestedLoopCount == 0)
  6653. return StmtError();
  6654. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6655. "omp teams distribute simd loop exprs were not built");
  6656. if (!CurContext->isDependentContext()) {
  6657. // Finalize the clauses that need pre-built expressions for CodeGen.
  6658. for (auto C : Clauses) {
  6659. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6660. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6661. B.NumIterations, *this, CurScope,
  6662. DSAStack))
  6663. return StmtError();
  6664. }
  6665. }
  6666. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6667. return StmtError();
  6668. getCurFunction()->setHasBranchProtectedScope();
  6669. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6670. return OMPTeamsDistributeSimdDirective::Create(
  6671. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6672. }
  6673. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  6674. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6675. SourceLocation EndLoc,
  6676. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6677. if (!AStmt)
  6678. return StmtError();
  6679. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6680. // 1.2.2 OpenMP Language Terminology
  6681. // Structured block - An executable statement with a single entry at the
  6682. // top and a single exit at the bottom.
  6683. // The point of exit cannot be a branch out of the structured block.
  6684. // longjmp() and throw() must not violate the entry/exit criteria.
  6685. CS->getCapturedDecl()->setNothrow();
  6686. for (int ThisCaptureLevel =
  6687. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  6688. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6689. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6690. // 1.2.2 OpenMP Language Terminology
  6691. // Structured block - An executable statement with a single entry at the
  6692. // top and a single exit at the bottom.
  6693. // The point of exit cannot be a branch out of the structured block.
  6694. // longjmp() and throw() must not violate the entry/exit criteria.
  6695. CS->getCapturedDecl()->setNothrow();
  6696. }
  6697. OMPLoopDirective::HelperExprs B;
  6698. // In presence of clause 'collapse' with number of loops, it will
  6699. // define the nested loops number.
  6700. auto NestedLoopCount = CheckOpenMPLoop(
  6701. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6702. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6703. VarsWithImplicitDSA, B);
  6704. if (NestedLoopCount == 0)
  6705. return StmtError();
  6706. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6707. "omp for loop exprs were not built");
  6708. if (!CurContext->isDependentContext()) {
  6709. // Finalize the clauses that need pre-built expressions for CodeGen.
  6710. for (auto C : Clauses) {
  6711. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6712. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6713. B.NumIterations, *this, CurScope,
  6714. DSAStack))
  6715. return StmtError();
  6716. }
  6717. }
  6718. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6719. return StmtError();
  6720. getCurFunction()->setHasBranchProtectedScope();
  6721. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6722. return OMPTeamsDistributeParallelForSimdDirective::Create(
  6723. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6724. }
  6725. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  6726. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6727. SourceLocation EndLoc,
  6728. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6729. if (!AStmt)
  6730. return StmtError();
  6731. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6732. // 1.2.2 OpenMP Language Terminology
  6733. // Structured block - An executable statement with a single entry at the
  6734. // top and a single exit at the bottom.
  6735. // The point of exit cannot be a branch out of the structured block.
  6736. // longjmp() and throw() must not violate the entry/exit criteria.
  6737. CS->getCapturedDecl()->setNothrow();
  6738. for (int ThisCaptureLevel =
  6739. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  6740. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6741. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6742. // 1.2.2 OpenMP Language Terminology
  6743. // Structured block - An executable statement with a single entry at the
  6744. // top and a single exit at the bottom.
  6745. // The point of exit cannot be a branch out of the structured block.
  6746. // longjmp() and throw() must not violate the entry/exit criteria.
  6747. CS->getCapturedDecl()->setNothrow();
  6748. }
  6749. OMPLoopDirective::HelperExprs B;
  6750. // In presence of clause 'collapse' with number of loops, it will
  6751. // define the nested loops number.
  6752. unsigned NestedLoopCount = CheckOpenMPLoop(
  6753. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6754. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6755. VarsWithImplicitDSA, B);
  6756. if (NestedLoopCount == 0)
  6757. return StmtError();
  6758. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6759. "omp for loop exprs were not built");
  6760. getCurFunction()->setHasBranchProtectedScope();
  6761. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6762. return OMPTeamsDistributeParallelForDirective::Create(
  6763. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6764. DSAStack->isCancelRegion());
  6765. }
  6766. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6767. Stmt *AStmt,
  6768. SourceLocation StartLoc,
  6769. SourceLocation EndLoc) {
  6770. if (!AStmt)
  6771. return StmtError();
  6772. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6773. // 1.2.2 OpenMP Language Terminology
  6774. // Structured block - An executable statement with a single entry at the
  6775. // top and a single exit at the bottom.
  6776. // The point of exit cannot be a branch out of the structured block.
  6777. // longjmp() and throw() must not violate the entry/exit criteria.
  6778. CS->getCapturedDecl()->setNothrow();
  6779. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  6780. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6781. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6782. // 1.2.2 OpenMP Language Terminology
  6783. // Structured block - An executable statement with a single entry at the
  6784. // top and a single exit at the bottom.
  6785. // The point of exit cannot be a branch out of the structured block.
  6786. // longjmp() and throw() must not violate the entry/exit criteria.
  6787. CS->getCapturedDecl()->setNothrow();
  6788. }
  6789. getCurFunction()->setHasBranchProtectedScope();
  6790. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6791. AStmt);
  6792. }
  6793. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  6794. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6795. SourceLocation EndLoc,
  6796. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6797. if (!AStmt)
  6798. return StmtError();
  6799. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6800. // 1.2.2 OpenMP Language Terminology
  6801. // Structured block - An executable statement with a single entry at the
  6802. // top and a single exit at the bottom.
  6803. // The point of exit cannot be a branch out of the structured block.
  6804. // longjmp() and throw() must not violate the entry/exit criteria.
  6805. CS->getCapturedDecl()->setNothrow();
  6806. for (int ThisCaptureLevel =
  6807. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  6808. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6809. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6810. // 1.2.2 OpenMP Language Terminology
  6811. // Structured block - An executable statement with a single entry at the
  6812. // top and a single exit at the bottom.
  6813. // The point of exit cannot be a branch out of the structured block.
  6814. // longjmp() and throw() must not violate the entry/exit criteria.
  6815. CS->getCapturedDecl()->setNothrow();
  6816. }
  6817. OMPLoopDirective::HelperExprs B;
  6818. // In presence of clause 'collapse' with number of loops, it will
  6819. // define the nested loops number.
  6820. auto NestedLoopCount = CheckOpenMPLoop(
  6821. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  6822. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6823. VarsWithImplicitDSA, B);
  6824. if (NestedLoopCount == 0)
  6825. return StmtError();
  6826. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6827. "omp target teams distribute loop exprs were not built");
  6828. getCurFunction()->setHasBranchProtectedScope();
  6829. return OMPTargetTeamsDistributeDirective::Create(
  6830. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6831. }
  6832. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  6833. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6834. SourceLocation EndLoc,
  6835. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6836. if (!AStmt)
  6837. return StmtError();
  6838. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6839. // 1.2.2 OpenMP Language Terminology
  6840. // Structured block - An executable statement with a single entry at the
  6841. // top and a single exit at the bottom.
  6842. // The point of exit cannot be a branch out of the structured block.
  6843. // longjmp() and throw() must not violate the entry/exit criteria.
  6844. CS->getCapturedDecl()->setNothrow();
  6845. OMPLoopDirective::HelperExprs B;
  6846. // In presence of clause 'collapse' with number of loops, it will
  6847. // define the nested loops number.
  6848. auto NestedLoopCount = CheckOpenMPLoop(
  6849. OMPD_target_teams_distribute_parallel_for,
  6850. getCollapseNumberExpr(Clauses),
  6851. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6852. VarsWithImplicitDSA, B);
  6853. if (NestedLoopCount == 0)
  6854. return StmtError();
  6855. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6856. "omp target teams distribute parallel for loop exprs were not built");
  6857. getCurFunction()->setHasBranchProtectedScope();
  6858. return OMPTargetTeamsDistributeParallelForDirective::Create(
  6859. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6860. DSAStack->isCancelRegion());
  6861. }
  6862. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  6863. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6864. SourceLocation EndLoc,
  6865. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6866. if (!AStmt)
  6867. return StmtError();
  6868. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6869. // 1.2.2 OpenMP Language Terminology
  6870. // Structured block - An executable statement with a single entry at the
  6871. // top and a single exit at the bottom.
  6872. // The point of exit cannot be a branch out of the structured block.
  6873. // longjmp() and throw() must not violate the entry/exit criteria.
  6874. CS->getCapturedDecl()->setNothrow();
  6875. OMPLoopDirective::HelperExprs B;
  6876. // In presence of clause 'collapse' with number of loops, it will
  6877. // define the nested loops number.
  6878. auto NestedLoopCount = CheckOpenMPLoop(
  6879. OMPD_target_teams_distribute_parallel_for_simd,
  6880. getCollapseNumberExpr(Clauses),
  6881. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6882. VarsWithImplicitDSA, B);
  6883. if (NestedLoopCount == 0)
  6884. return StmtError();
  6885. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6886. "omp target teams distribute parallel for simd loop exprs were not "
  6887. "built");
  6888. if (!CurContext->isDependentContext()) {
  6889. // Finalize the clauses that need pre-built expressions for CodeGen.
  6890. for (auto C : Clauses) {
  6891. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6892. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6893. B.NumIterations, *this, CurScope,
  6894. DSAStack))
  6895. return StmtError();
  6896. }
  6897. }
  6898. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6899. return StmtError();
  6900. getCurFunction()->setHasBranchProtectedScope();
  6901. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  6902. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6903. }
  6904. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  6905. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6906. SourceLocation EndLoc,
  6907. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6908. if (!AStmt)
  6909. return StmtError();
  6910. auto *CS = cast<CapturedStmt>(AStmt);
  6911. // 1.2.2 OpenMP Language Terminology
  6912. // Structured block - An executable statement with a single entry at the
  6913. // top and a single exit at the bottom.
  6914. // The point of exit cannot be a branch out of the structured block.
  6915. // longjmp() and throw() must not violate the entry/exit criteria.
  6916. CS->getCapturedDecl()->setNothrow();
  6917. for (int ThisCaptureLevel =
  6918. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  6919. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6920. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6921. // 1.2.2 OpenMP Language Terminology
  6922. // Structured block - An executable statement with a single entry at the
  6923. // top and a single exit at the bottom.
  6924. // The point of exit cannot be a branch out of the structured block.
  6925. // longjmp() and throw() must not violate the entry/exit criteria.
  6926. CS->getCapturedDecl()->setNothrow();
  6927. }
  6928. OMPLoopDirective::HelperExprs B;
  6929. // In presence of clause 'collapse' with number of loops, it will
  6930. // define the nested loops number.
  6931. auto NestedLoopCount = CheckOpenMPLoop(
  6932. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6933. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6934. VarsWithImplicitDSA, B);
  6935. if (NestedLoopCount == 0)
  6936. return StmtError();
  6937. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6938. "omp target teams distribute simd loop exprs were not built");
  6939. if (!CurContext->isDependentContext()) {
  6940. // Finalize the clauses that need pre-built expressions for CodeGen.
  6941. for (auto C : Clauses) {
  6942. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6943. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6944. B.NumIterations, *this, CurScope,
  6945. DSAStack))
  6946. return StmtError();
  6947. }
  6948. }
  6949. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6950. return StmtError();
  6951. getCurFunction()->setHasBranchProtectedScope();
  6952. return OMPTargetTeamsDistributeSimdDirective::Create(
  6953. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6954. }
  6955. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  6956. SourceLocation StartLoc,
  6957. SourceLocation LParenLoc,
  6958. SourceLocation EndLoc) {
  6959. OMPClause *Res = nullptr;
  6960. switch (Kind) {
  6961. case OMPC_final:
  6962. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  6963. break;
  6964. case OMPC_num_threads:
  6965. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6966. break;
  6967. case OMPC_safelen:
  6968. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6969. break;
  6970. case OMPC_simdlen:
  6971. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6972. break;
  6973. case OMPC_collapse:
  6974. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  6975. break;
  6976. case OMPC_ordered:
  6977. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  6978. break;
  6979. case OMPC_device:
  6980. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  6981. break;
  6982. case OMPC_num_teams:
  6983. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6984. break;
  6985. case OMPC_thread_limit:
  6986. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  6987. break;
  6988. case OMPC_priority:
  6989. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  6990. break;
  6991. case OMPC_grainsize:
  6992. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  6993. break;
  6994. case OMPC_num_tasks:
  6995. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  6996. break;
  6997. case OMPC_hint:
  6998. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  6999. break;
  7000. case OMPC_if:
  7001. case OMPC_default:
  7002. case OMPC_proc_bind:
  7003. case OMPC_schedule:
  7004. case OMPC_private:
  7005. case OMPC_firstprivate:
  7006. case OMPC_lastprivate:
  7007. case OMPC_shared:
  7008. case OMPC_reduction:
  7009. case OMPC_task_reduction:
  7010. case OMPC_in_reduction:
  7011. case OMPC_linear:
  7012. case OMPC_aligned:
  7013. case OMPC_copyin:
  7014. case OMPC_copyprivate:
  7015. case OMPC_nowait:
  7016. case OMPC_untied:
  7017. case OMPC_mergeable:
  7018. case OMPC_threadprivate:
  7019. case OMPC_flush:
  7020. case OMPC_read:
  7021. case OMPC_write:
  7022. case OMPC_update:
  7023. case OMPC_capture:
  7024. case OMPC_seq_cst:
  7025. case OMPC_depend:
  7026. case OMPC_threads:
  7027. case OMPC_simd:
  7028. case OMPC_map:
  7029. case OMPC_nogroup:
  7030. case OMPC_dist_schedule:
  7031. case OMPC_defaultmap:
  7032. case OMPC_unknown:
  7033. case OMPC_uniform:
  7034. case OMPC_to:
  7035. case OMPC_from:
  7036. case OMPC_use_device_ptr:
  7037. case OMPC_is_device_ptr:
  7038. llvm_unreachable("Clause is not allowed.");
  7039. }
  7040. return Res;
  7041. }
  7042. // An OpenMP directive such as 'target parallel' has two captured regions:
  7043. // for the 'target' and 'parallel' respectively. This function returns
  7044. // the region in which to capture expressions associated with a clause.
  7045. // A return value of OMPD_unknown signifies that the expression should not
  7046. // be captured.
  7047. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7048. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7049. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7050. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7051. switch (CKind) {
  7052. case OMPC_if:
  7053. switch (DKind) {
  7054. case OMPD_target_parallel:
  7055. case OMPD_target_parallel_for:
  7056. case OMPD_target_parallel_for_simd:
  7057. case OMPD_target_teams_distribute_parallel_for:
  7058. case OMPD_target_teams_distribute_parallel_for_simd:
  7059. // If this clause applies to the nested 'parallel' region, capture within
  7060. // the 'target' region, otherwise do not capture.
  7061. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7062. CaptureRegion = OMPD_target;
  7063. break;
  7064. case OMPD_teams_distribute_parallel_for:
  7065. case OMPD_teams_distribute_parallel_for_simd:
  7066. CaptureRegion = OMPD_teams;
  7067. break;
  7068. case OMPD_cancel:
  7069. case OMPD_parallel:
  7070. case OMPD_parallel_sections:
  7071. case OMPD_parallel_for:
  7072. case OMPD_parallel_for_simd:
  7073. case OMPD_target:
  7074. case OMPD_target_simd:
  7075. case OMPD_target_teams:
  7076. case OMPD_target_teams_distribute:
  7077. case OMPD_target_teams_distribute_simd:
  7078. case OMPD_distribute_parallel_for:
  7079. case OMPD_distribute_parallel_for_simd:
  7080. case OMPD_task:
  7081. case OMPD_taskloop:
  7082. case OMPD_taskloop_simd:
  7083. case OMPD_target_data:
  7084. case OMPD_target_enter_data:
  7085. case OMPD_target_exit_data:
  7086. case OMPD_target_update:
  7087. // Do not capture if-clause expressions.
  7088. break;
  7089. case OMPD_threadprivate:
  7090. case OMPD_taskyield:
  7091. case OMPD_barrier:
  7092. case OMPD_taskwait:
  7093. case OMPD_cancellation_point:
  7094. case OMPD_flush:
  7095. case OMPD_declare_reduction:
  7096. case OMPD_declare_simd:
  7097. case OMPD_declare_target:
  7098. case OMPD_end_declare_target:
  7099. case OMPD_teams:
  7100. case OMPD_simd:
  7101. case OMPD_for:
  7102. case OMPD_for_simd:
  7103. case OMPD_sections:
  7104. case OMPD_section:
  7105. case OMPD_single:
  7106. case OMPD_master:
  7107. case OMPD_critical:
  7108. case OMPD_taskgroup:
  7109. case OMPD_distribute:
  7110. case OMPD_ordered:
  7111. case OMPD_atomic:
  7112. case OMPD_distribute_simd:
  7113. case OMPD_teams_distribute:
  7114. case OMPD_teams_distribute_simd:
  7115. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7116. case OMPD_unknown:
  7117. llvm_unreachable("Unknown OpenMP directive");
  7118. }
  7119. break;
  7120. case OMPC_num_threads:
  7121. switch (DKind) {
  7122. case OMPD_target_parallel:
  7123. case OMPD_target_parallel_for:
  7124. case OMPD_target_parallel_for_simd:
  7125. case OMPD_target_teams_distribute_parallel_for:
  7126. case OMPD_target_teams_distribute_parallel_for_simd:
  7127. CaptureRegion = OMPD_target;
  7128. break;
  7129. case OMPD_teams_distribute_parallel_for:
  7130. case OMPD_teams_distribute_parallel_for_simd:
  7131. CaptureRegion = OMPD_teams;
  7132. break;
  7133. case OMPD_parallel:
  7134. case OMPD_parallel_sections:
  7135. case OMPD_parallel_for:
  7136. case OMPD_parallel_for_simd:
  7137. case OMPD_distribute_parallel_for:
  7138. case OMPD_distribute_parallel_for_simd:
  7139. // Do not capture num_threads-clause expressions.
  7140. break;
  7141. case OMPD_target_data:
  7142. case OMPD_target_enter_data:
  7143. case OMPD_target_exit_data:
  7144. case OMPD_target_update:
  7145. case OMPD_target:
  7146. case OMPD_target_simd:
  7147. case OMPD_target_teams:
  7148. case OMPD_target_teams_distribute:
  7149. case OMPD_target_teams_distribute_simd:
  7150. case OMPD_cancel:
  7151. case OMPD_task:
  7152. case OMPD_taskloop:
  7153. case OMPD_taskloop_simd:
  7154. case OMPD_threadprivate:
  7155. case OMPD_taskyield:
  7156. case OMPD_barrier:
  7157. case OMPD_taskwait:
  7158. case OMPD_cancellation_point:
  7159. case OMPD_flush:
  7160. case OMPD_declare_reduction:
  7161. case OMPD_declare_simd:
  7162. case OMPD_declare_target:
  7163. case OMPD_end_declare_target:
  7164. case OMPD_teams:
  7165. case OMPD_simd:
  7166. case OMPD_for:
  7167. case OMPD_for_simd:
  7168. case OMPD_sections:
  7169. case OMPD_section:
  7170. case OMPD_single:
  7171. case OMPD_master:
  7172. case OMPD_critical:
  7173. case OMPD_taskgroup:
  7174. case OMPD_distribute:
  7175. case OMPD_ordered:
  7176. case OMPD_atomic:
  7177. case OMPD_distribute_simd:
  7178. case OMPD_teams_distribute:
  7179. case OMPD_teams_distribute_simd:
  7180. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7181. case OMPD_unknown:
  7182. llvm_unreachable("Unknown OpenMP directive");
  7183. }
  7184. break;
  7185. case OMPC_num_teams:
  7186. switch (DKind) {
  7187. case OMPD_target_teams:
  7188. case OMPD_target_teams_distribute:
  7189. case OMPD_target_teams_distribute_simd:
  7190. case OMPD_target_teams_distribute_parallel_for:
  7191. case OMPD_target_teams_distribute_parallel_for_simd:
  7192. CaptureRegion = OMPD_target;
  7193. break;
  7194. case OMPD_teams_distribute_parallel_for:
  7195. case OMPD_teams_distribute_parallel_for_simd:
  7196. case OMPD_teams:
  7197. case OMPD_teams_distribute:
  7198. case OMPD_teams_distribute_simd:
  7199. // Do not capture num_teams-clause expressions.
  7200. break;
  7201. case OMPD_distribute_parallel_for:
  7202. case OMPD_distribute_parallel_for_simd:
  7203. case OMPD_task:
  7204. case OMPD_taskloop:
  7205. case OMPD_taskloop_simd:
  7206. case OMPD_target_data:
  7207. case OMPD_target_enter_data:
  7208. case OMPD_target_exit_data:
  7209. case OMPD_target_update:
  7210. case OMPD_cancel:
  7211. case OMPD_parallel:
  7212. case OMPD_parallel_sections:
  7213. case OMPD_parallel_for:
  7214. case OMPD_parallel_for_simd:
  7215. case OMPD_target:
  7216. case OMPD_target_simd:
  7217. case OMPD_target_parallel:
  7218. case OMPD_target_parallel_for:
  7219. case OMPD_target_parallel_for_simd:
  7220. case OMPD_threadprivate:
  7221. case OMPD_taskyield:
  7222. case OMPD_barrier:
  7223. case OMPD_taskwait:
  7224. case OMPD_cancellation_point:
  7225. case OMPD_flush:
  7226. case OMPD_declare_reduction:
  7227. case OMPD_declare_simd:
  7228. case OMPD_declare_target:
  7229. case OMPD_end_declare_target:
  7230. case OMPD_simd:
  7231. case OMPD_for:
  7232. case OMPD_for_simd:
  7233. case OMPD_sections:
  7234. case OMPD_section:
  7235. case OMPD_single:
  7236. case OMPD_master:
  7237. case OMPD_critical:
  7238. case OMPD_taskgroup:
  7239. case OMPD_distribute:
  7240. case OMPD_ordered:
  7241. case OMPD_atomic:
  7242. case OMPD_distribute_simd:
  7243. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7244. case OMPD_unknown:
  7245. llvm_unreachable("Unknown OpenMP directive");
  7246. }
  7247. break;
  7248. case OMPC_thread_limit:
  7249. switch (DKind) {
  7250. case OMPD_target_teams:
  7251. case OMPD_target_teams_distribute:
  7252. case OMPD_target_teams_distribute_simd:
  7253. case OMPD_target_teams_distribute_parallel_for:
  7254. case OMPD_target_teams_distribute_parallel_for_simd:
  7255. CaptureRegion = OMPD_target;
  7256. break;
  7257. case OMPD_teams_distribute_parallel_for:
  7258. case OMPD_teams_distribute_parallel_for_simd:
  7259. case OMPD_teams:
  7260. case OMPD_teams_distribute:
  7261. case OMPD_teams_distribute_simd:
  7262. // Do not capture thread_limit-clause expressions.
  7263. break;
  7264. case OMPD_distribute_parallel_for:
  7265. case OMPD_distribute_parallel_for_simd:
  7266. case OMPD_task:
  7267. case OMPD_taskloop:
  7268. case OMPD_taskloop_simd:
  7269. case OMPD_target_data:
  7270. case OMPD_target_enter_data:
  7271. case OMPD_target_exit_data:
  7272. case OMPD_target_update:
  7273. case OMPD_cancel:
  7274. case OMPD_parallel:
  7275. case OMPD_parallel_sections:
  7276. case OMPD_parallel_for:
  7277. case OMPD_parallel_for_simd:
  7278. case OMPD_target:
  7279. case OMPD_target_simd:
  7280. case OMPD_target_parallel:
  7281. case OMPD_target_parallel_for:
  7282. case OMPD_target_parallel_for_simd:
  7283. case OMPD_threadprivate:
  7284. case OMPD_taskyield:
  7285. case OMPD_barrier:
  7286. case OMPD_taskwait:
  7287. case OMPD_cancellation_point:
  7288. case OMPD_flush:
  7289. case OMPD_declare_reduction:
  7290. case OMPD_declare_simd:
  7291. case OMPD_declare_target:
  7292. case OMPD_end_declare_target:
  7293. case OMPD_simd:
  7294. case OMPD_for:
  7295. case OMPD_for_simd:
  7296. case OMPD_sections:
  7297. case OMPD_section:
  7298. case OMPD_single:
  7299. case OMPD_master:
  7300. case OMPD_critical:
  7301. case OMPD_taskgroup:
  7302. case OMPD_distribute:
  7303. case OMPD_ordered:
  7304. case OMPD_atomic:
  7305. case OMPD_distribute_simd:
  7306. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7307. case OMPD_unknown:
  7308. llvm_unreachable("Unknown OpenMP directive");
  7309. }
  7310. break;
  7311. case OMPC_schedule:
  7312. switch (DKind) {
  7313. case OMPD_target_parallel_for:
  7314. case OMPD_target_parallel_for_simd:
  7315. case OMPD_target_teams_distribute_parallel_for:
  7316. case OMPD_target_teams_distribute_parallel_for_simd:
  7317. CaptureRegion = OMPD_target;
  7318. break;
  7319. case OMPD_teams_distribute_parallel_for:
  7320. case OMPD_teams_distribute_parallel_for_simd:
  7321. CaptureRegion = OMPD_teams;
  7322. break;
  7323. case OMPD_parallel_for:
  7324. case OMPD_parallel_for_simd:
  7325. case OMPD_distribute_parallel_for:
  7326. case OMPD_distribute_parallel_for_simd:
  7327. CaptureRegion = OMPD_parallel;
  7328. break;
  7329. case OMPD_for:
  7330. case OMPD_for_simd:
  7331. // Do not capture schedule-clause expressions.
  7332. break;
  7333. case OMPD_task:
  7334. case OMPD_taskloop:
  7335. case OMPD_taskloop_simd:
  7336. case OMPD_target_data:
  7337. case OMPD_target_enter_data:
  7338. case OMPD_target_exit_data:
  7339. case OMPD_target_update:
  7340. case OMPD_teams:
  7341. case OMPD_teams_distribute:
  7342. case OMPD_teams_distribute_simd:
  7343. case OMPD_target_teams_distribute:
  7344. case OMPD_target_teams_distribute_simd:
  7345. case OMPD_target:
  7346. case OMPD_target_simd:
  7347. case OMPD_target_parallel:
  7348. case OMPD_cancel:
  7349. case OMPD_parallel:
  7350. case OMPD_parallel_sections:
  7351. case OMPD_threadprivate:
  7352. case OMPD_taskyield:
  7353. case OMPD_barrier:
  7354. case OMPD_taskwait:
  7355. case OMPD_cancellation_point:
  7356. case OMPD_flush:
  7357. case OMPD_declare_reduction:
  7358. case OMPD_declare_simd:
  7359. case OMPD_declare_target:
  7360. case OMPD_end_declare_target:
  7361. case OMPD_simd:
  7362. case OMPD_sections:
  7363. case OMPD_section:
  7364. case OMPD_single:
  7365. case OMPD_master:
  7366. case OMPD_critical:
  7367. case OMPD_taskgroup:
  7368. case OMPD_distribute:
  7369. case OMPD_ordered:
  7370. case OMPD_atomic:
  7371. case OMPD_distribute_simd:
  7372. case OMPD_target_teams:
  7373. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7374. case OMPD_unknown:
  7375. llvm_unreachable("Unknown OpenMP directive");
  7376. }
  7377. break;
  7378. case OMPC_dist_schedule:
  7379. switch (DKind) {
  7380. case OMPD_teams_distribute_parallel_for:
  7381. case OMPD_teams_distribute_parallel_for_simd:
  7382. case OMPD_teams_distribute:
  7383. case OMPD_teams_distribute_simd:
  7384. CaptureRegion = OMPD_teams;
  7385. break;
  7386. case OMPD_target_teams_distribute_parallel_for:
  7387. case OMPD_target_teams_distribute_parallel_for_simd:
  7388. case OMPD_target_teams_distribute:
  7389. case OMPD_target_teams_distribute_simd:
  7390. CaptureRegion = OMPD_target;
  7391. break;
  7392. case OMPD_distribute_parallel_for:
  7393. case OMPD_distribute_parallel_for_simd:
  7394. CaptureRegion = OMPD_parallel;
  7395. break;
  7396. case OMPD_distribute:
  7397. case OMPD_distribute_simd:
  7398. // Do not capture thread_limit-clause expressions.
  7399. break;
  7400. case OMPD_parallel_for:
  7401. case OMPD_parallel_for_simd:
  7402. case OMPD_target_parallel_for_simd:
  7403. case OMPD_target_parallel_for:
  7404. case OMPD_task:
  7405. case OMPD_taskloop:
  7406. case OMPD_taskloop_simd:
  7407. case OMPD_target_data:
  7408. case OMPD_target_enter_data:
  7409. case OMPD_target_exit_data:
  7410. case OMPD_target_update:
  7411. case OMPD_teams:
  7412. case OMPD_target:
  7413. case OMPD_target_simd:
  7414. case OMPD_target_parallel:
  7415. case OMPD_cancel:
  7416. case OMPD_parallel:
  7417. case OMPD_parallel_sections:
  7418. case OMPD_threadprivate:
  7419. case OMPD_taskyield:
  7420. case OMPD_barrier:
  7421. case OMPD_taskwait:
  7422. case OMPD_cancellation_point:
  7423. case OMPD_flush:
  7424. case OMPD_declare_reduction:
  7425. case OMPD_declare_simd:
  7426. case OMPD_declare_target:
  7427. case OMPD_end_declare_target:
  7428. case OMPD_simd:
  7429. case OMPD_for:
  7430. case OMPD_for_simd:
  7431. case OMPD_sections:
  7432. case OMPD_section:
  7433. case OMPD_single:
  7434. case OMPD_master:
  7435. case OMPD_critical:
  7436. case OMPD_taskgroup:
  7437. case OMPD_ordered:
  7438. case OMPD_atomic:
  7439. case OMPD_target_teams:
  7440. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7441. case OMPD_unknown:
  7442. llvm_unreachable("Unknown OpenMP directive");
  7443. }
  7444. break;
  7445. case OMPC_device:
  7446. switch (DKind) {
  7447. case OMPD_target_teams:
  7448. case OMPD_target_teams_distribute:
  7449. case OMPD_target_teams_distribute_simd:
  7450. case OMPD_target_teams_distribute_parallel_for:
  7451. case OMPD_target_teams_distribute_parallel_for_simd:
  7452. case OMPD_target_data:
  7453. case OMPD_target_enter_data:
  7454. case OMPD_target_exit_data:
  7455. case OMPD_target_update:
  7456. case OMPD_target:
  7457. case OMPD_target_simd:
  7458. case OMPD_target_parallel:
  7459. case OMPD_target_parallel_for:
  7460. case OMPD_target_parallel_for_simd:
  7461. // Do not capture device-clause expressions.
  7462. break;
  7463. case OMPD_teams_distribute_parallel_for:
  7464. case OMPD_teams_distribute_parallel_for_simd:
  7465. case OMPD_teams:
  7466. case OMPD_teams_distribute:
  7467. case OMPD_teams_distribute_simd:
  7468. case OMPD_distribute_parallel_for:
  7469. case OMPD_distribute_parallel_for_simd:
  7470. case OMPD_task:
  7471. case OMPD_taskloop:
  7472. case OMPD_taskloop_simd:
  7473. case OMPD_cancel:
  7474. case OMPD_parallel:
  7475. case OMPD_parallel_sections:
  7476. case OMPD_parallel_for:
  7477. case OMPD_parallel_for_simd:
  7478. case OMPD_threadprivate:
  7479. case OMPD_taskyield:
  7480. case OMPD_barrier:
  7481. case OMPD_taskwait:
  7482. case OMPD_cancellation_point:
  7483. case OMPD_flush:
  7484. case OMPD_declare_reduction:
  7485. case OMPD_declare_simd:
  7486. case OMPD_declare_target:
  7487. case OMPD_end_declare_target:
  7488. case OMPD_simd:
  7489. case OMPD_for:
  7490. case OMPD_for_simd:
  7491. case OMPD_sections:
  7492. case OMPD_section:
  7493. case OMPD_single:
  7494. case OMPD_master:
  7495. case OMPD_critical:
  7496. case OMPD_taskgroup:
  7497. case OMPD_distribute:
  7498. case OMPD_ordered:
  7499. case OMPD_atomic:
  7500. case OMPD_distribute_simd:
  7501. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7502. case OMPD_unknown:
  7503. llvm_unreachable("Unknown OpenMP directive");
  7504. }
  7505. break;
  7506. case OMPC_firstprivate:
  7507. case OMPC_lastprivate:
  7508. case OMPC_reduction:
  7509. case OMPC_task_reduction:
  7510. case OMPC_in_reduction:
  7511. case OMPC_linear:
  7512. case OMPC_default:
  7513. case OMPC_proc_bind:
  7514. case OMPC_final:
  7515. case OMPC_safelen:
  7516. case OMPC_simdlen:
  7517. case OMPC_collapse:
  7518. case OMPC_private:
  7519. case OMPC_shared:
  7520. case OMPC_aligned:
  7521. case OMPC_copyin:
  7522. case OMPC_copyprivate:
  7523. case OMPC_ordered:
  7524. case OMPC_nowait:
  7525. case OMPC_untied:
  7526. case OMPC_mergeable:
  7527. case OMPC_threadprivate:
  7528. case OMPC_flush:
  7529. case OMPC_read:
  7530. case OMPC_write:
  7531. case OMPC_update:
  7532. case OMPC_capture:
  7533. case OMPC_seq_cst:
  7534. case OMPC_depend:
  7535. case OMPC_threads:
  7536. case OMPC_simd:
  7537. case OMPC_map:
  7538. case OMPC_priority:
  7539. case OMPC_grainsize:
  7540. case OMPC_nogroup:
  7541. case OMPC_num_tasks:
  7542. case OMPC_hint:
  7543. case OMPC_defaultmap:
  7544. case OMPC_unknown:
  7545. case OMPC_uniform:
  7546. case OMPC_to:
  7547. case OMPC_from:
  7548. case OMPC_use_device_ptr:
  7549. case OMPC_is_device_ptr:
  7550. llvm_unreachable("Unexpected OpenMP clause.");
  7551. }
  7552. return CaptureRegion;
  7553. }
  7554. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  7555. Expr *Condition, SourceLocation StartLoc,
  7556. SourceLocation LParenLoc,
  7557. SourceLocation NameModifierLoc,
  7558. SourceLocation ColonLoc,
  7559. SourceLocation EndLoc) {
  7560. Expr *ValExpr = Condition;
  7561. Stmt *HelperValStmt = nullptr;
  7562. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7563. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7564. !Condition->isInstantiationDependent() &&
  7565. !Condition->containsUnexpandedParameterPack()) {
  7566. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7567. if (Val.isInvalid())
  7568. return nullptr;
  7569. ValExpr = MakeFullExpr(Val.get()).get();
  7570. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7571. CaptureRegion =
  7572. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  7573. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7574. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7575. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7576. HelperValStmt = buildPreInits(Context, Captures);
  7577. }
  7578. }
  7579. return new (Context)
  7580. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  7581. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  7582. }
  7583. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  7584. SourceLocation StartLoc,
  7585. SourceLocation LParenLoc,
  7586. SourceLocation EndLoc) {
  7587. Expr *ValExpr = Condition;
  7588. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7589. !Condition->isInstantiationDependent() &&
  7590. !Condition->containsUnexpandedParameterPack()) {
  7591. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7592. if (Val.isInvalid())
  7593. return nullptr;
  7594. ValExpr = MakeFullExpr(Val.get()).get();
  7595. }
  7596. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  7597. }
  7598. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  7599. Expr *Op) {
  7600. if (!Op)
  7601. return ExprError();
  7602. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  7603. public:
  7604. IntConvertDiagnoser()
  7605. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  7606. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  7607. QualType T) override {
  7608. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  7609. }
  7610. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  7611. QualType T) override {
  7612. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  7613. }
  7614. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  7615. QualType T,
  7616. QualType ConvTy) override {
  7617. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  7618. }
  7619. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  7620. QualType ConvTy) override {
  7621. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7622. << ConvTy->isEnumeralType() << ConvTy;
  7623. }
  7624. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  7625. QualType T) override {
  7626. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  7627. }
  7628. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  7629. QualType ConvTy) override {
  7630. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7631. << ConvTy->isEnumeralType() << ConvTy;
  7632. }
  7633. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  7634. QualType) override {
  7635. llvm_unreachable("conversion functions are permitted");
  7636. }
  7637. } ConvertDiagnoser;
  7638. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  7639. }
  7640. static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  7641. OpenMPClauseKind CKind,
  7642. bool StrictlyPositive) {
  7643. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  7644. !ValExpr->isInstantiationDependent()) {
  7645. SourceLocation Loc = ValExpr->getExprLoc();
  7646. ExprResult Value =
  7647. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  7648. if (Value.isInvalid())
  7649. return false;
  7650. ValExpr = Value.get();
  7651. // The expression must evaluate to a non-negative integer value.
  7652. llvm::APSInt Result;
  7653. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  7654. Result.isSigned() &&
  7655. !((!StrictlyPositive && Result.isNonNegative()) ||
  7656. (StrictlyPositive && Result.isStrictlyPositive()))) {
  7657. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  7658. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7659. << ValExpr->getSourceRange();
  7660. return false;
  7661. }
  7662. }
  7663. return true;
  7664. }
  7665. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  7666. SourceLocation StartLoc,
  7667. SourceLocation LParenLoc,
  7668. SourceLocation EndLoc) {
  7669. Expr *ValExpr = NumThreads;
  7670. Stmt *HelperValStmt = nullptr;
  7671. // OpenMP [2.5, Restrictions]
  7672. // The num_threads expression must evaluate to a positive integer value.
  7673. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  7674. /*StrictlyPositive=*/true))
  7675. return nullptr;
  7676. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7677. OpenMPDirectiveKind CaptureRegion =
  7678. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  7679. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7680. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7681. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7682. HelperValStmt = buildPreInits(Context, Captures);
  7683. }
  7684. return new (Context) OMPNumThreadsClause(
  7685. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  7686. }
  7687. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  7688. OpenMPClauseKind CKind,
  7689. bool StrictlyPositive) {
  7690. if (!E)
  7691. return ExprError();
  7692. if (E->isValueDependent() || E->isTypeDependent() ||
  7693. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  7694. return E;
  7695. llvm::APSInt Result;
  7696. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  7697. if (ICE.isInvalid())
  7698. return ExprError();
  7699. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  7700. (!StrictlyPositive && !Result.isNonNegative())) {
  7701. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  7702. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7703. << E->getSourceRange();
  7704. return ExprError();
  7705. }
  7706. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  7707. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  7708. << E->getSourceRange();
  7709. return ExprError();
  7710. }
  7711. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  7712. DSAStack->setAssociatedLoops(Result.getExtValue());
  7713. else if (CKind == OMPC_ordered)
  7714. DSAStack->setAssociatedLoops(Result.getExtValue());
  7715. return ICE;
  7716. }
  7717. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  7718. SourceLocation LParenLoc,
  7719. SourceLocation EndLoc) {
  7720. // OpenMP [2.8.1, simd construct, Description]
  7721. // The parameter of the safelen clause must be a constant
  7722. // positive integer expression.
  7723. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  7724. if (Safelen.isInvalid())
  7725. return nullptr;
  7726. return new (Context)
  7727. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  7728. }
  7729. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  7730. SourceLocation LParenLoc,
  7731. SourceLocation EndLoc) {
  7732. // OpenMP [2.8.1, simd construct, Description]
  7733. // The parameter of the simdlen clause must be a constant
  7734. // positive integer expression.
  7735. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  7736. if (Simdlen.isInvalid())
  7737. return nullptr;
  7738. return new (Context)
  7739. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  7740. }
  7741. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  7742. SourceLocation StartLoc,
  7743. SourceLocation LParenLoc,
  7744. SourceLocation EndLoc) {
  7745. // OpenMP [2.7.1, loop construct, Description]
  7746. // OpenMP [2.8.1, simd construct, Description]
  7747. // OpenMP [2.9.6, distribute construct, Description]
  7748. // The parameter of the collapse clause must be a constant
  7749. // positive integer expression.
  7750. ExprResult NumForLoopsResult =
  7751. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  7752. if (NumForLoopsResult.isInvalid())
  7753. return nullptr;
  7754. return new (Context)
  7755. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  7756. }
  7757. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  7758. SourceLocation EndLoc,
  7759. SourceLocation LParenLoc,
  7760. Expr *NumForLoops) {
  7761. // OpenMP [2.7.1, loop construct, Description]
  7762. // OpenMP [2.8.1, simd construct, Description]
  7763. // OpenMP [2.9.6, distribute construct, Description]
  7764. // The parameter of the ordered clause must be a constant
  7765. // positive integer expression if any.
  7766. if (NumForLoops && LParenLoc.isValid()) {
  7767. ExprResult NumForLoopsResult =
  7768. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  7769. if (NumForLoopsResult.isInvalid())
  7770. return nullptr;
  7771. NumForLoops = NumForLoopsResult.get();
  7772. } else
  7773. NumForLoops = nullptr;
  7774. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
  7775. return new (Context)
  7776. OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
  7777. }
  7778. OMPClause *Sema::ActOnOpenMPSimpleClause(
  7779. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  7780. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  7781. OMPClause *Res = nullptr;
  7782. switch (Kind) {
  7783. case OMPC_default:
  7784. Res =
  7785. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  7786. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  7787. break;
  7788. case OMPC_proc_bind:
  7789. Res = ActOnOpenMPProcBindClause(
  7790. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  7791. LParenLoc, EndLoc);
  7792. break;
  7793. case OMPC_if:
  7794. case OMPC_final:
  7795. case OMPC_num_threads:
  7796. case OMPC_safelen:
  7797. case OMPC_simdlen:
  7798. case OMPC_collapse:
  7799. case OMPC_schedule:
  7800. case OMPC_private:
  7801. case OMPC_firstprivate:
  7802. case OMPC_lastprivate:
  7803. case OMPC_shared:
  7804. case OMPC_reduction:
  7805. case OMPC_task_reduction:
  7806. case OMPC_in_reduction:
  7807. case OMPC_linear:
  7808. case OMPC_aligned:
  7809. case OMPC_copyin:
  7810. case OMPC_copyprivate:
  7811. case OMPC_ordered:
  7812. case OMPC_nowait:
  7813. case OMPC_untied:
  7814. case OMPC_mergeable:
  7815. case OMPC_threadprivate:
  7816. case OMPC_flush:
  7817. case OMPC_read:
  7818. case OMPC_write:
  7819. case OMPC_update:
  7820. case OMPC_capture:
  7821. case OMPC_seq_cst:
  7822. case OMPC_depend:
  7823. case OMPC_device:
  7824. case OMPC_threads:
  7825. case OMPC_simd:
  7826. case OMPC_map:
  7827. case OMPC_num_teams:
  7828. case OMPC_thread_limit:
  7829. case OMPC_priority:
  7830. case OMPC_grainsize:
  7831. case OMPC_nogroup:
  7832. case OMPC_num_tasks:
  7833. case OMPC_hint:
  7834. case OMPC_dist_schedule:
  7835. case OMPC_defaultmap:
  7836. case OMPC_unknown:
  7837. case OMPC_uniform:
  7838. case OMPC_to:
  7839. case OMPC_from:
  7840. case OMPC_use_device_ptr:
  7841. case OMPC_is_device_ptr:
  7842. llvm_unreachable("Clause is not allowed.");
  7843. }
  7844. return Res;
  7845. }
  7846. static std::string
  7847. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  7848. ArrayRef<unsigned> Exclude = llvm::None) {
  7849. std::string Values;
  7850. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  7851. unsigned Skipped = Exclude.size();
  7852. auto S = Exclude.begin(), E = Exclude.end();
  7853. for (unsigned i = First; i < Last; ++i) {
  7854. if (std::find(S, E, i) != E) {
  7855. --Skipped;
  7856. continue;
  7857. }
  7858. Values += "'";
  7859. Values += getOpenMPSimpleClauseTypeName(K, i);
  7860. Values += "'";
  7861. if (i == Bound - Skipped)
  7862. Values += " or ";
  7863. else if (i != Bound + 1 - Skipped)
  7864. Values += ", ";
  7865. }
  7866. return Values;
  7867. }
  7868. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  7869. SourceLocation KindKwLoc,
  7870. SourceLocation StartLoc,
  7871. SourceLocation LParenLoc,
  7872. SourceLocation EndLoc) {
  7873. if (Kind == OMPC_DEFAULT_unknown) {
  7874. static_assert(OMPC_DEFAULT_unknown > 0,
  7875. "OMPC_DEFAULT_unknown not greater than 0");
  7876. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7877. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  7878. /*Last=*/OMPC_DEFAULT_unknown)
  7879. << getOpenMPClauseName(OMPC_default);
  7880. return nullptr;
  7881. }
  7882. switch (Kind) {
  7883. case OMPC_DEFAULT_none:
  7884. DSAStack->setDefaultDSANone(KindKwLoc);
  7885. break;
  7886. case OMPC_DEFAULT_shared:
  7887. DSAStack->setDefaultDSAShared(KindKwLoc);
  7888. break;
  7889. case OMPC_DEFAULT_unknown:
  7890. llvm_unreachable("Clause kind is not allowed.");
  7891. break;
  7892. }
  7893. return new (Context)
  7894. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7895. }
  7896. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  7897. SourceLocation KindKwLoc,
  7898. SourceLocation StartLoc,
  7899. SourceLocation LParenLoc,
  7900. SourceLocation EndLoc) {
  7901. if (Kind == OMPC_PROC_BIND_unknown) {
  7902. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7903. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  7904. /*Last=*/OMPC_PROC_BIND_unknown)
  7905. << getOpenMPClauseName(OMPC_proc_bind);
  7906. return nullptr;
  7907. }
  7908. return new (Context)
  7909. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7910. }
  7911. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  7912. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  7913. SourceLocation StartLoc, SourceLocation LParenLoc,
  7914. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  7915. SourceLocation EndLoc) {
  7916. OMPClause *Res = nullptr;
  7917. switch (Kind) {
  7918. case OMPC_schedule:
  7919. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  7920. assert(Argument.size() == NumberOfElements &&
  7921. ArgumentLoc.size() == NumberOfElements);
  7922. Res = ActOnOpenMPScheduleClause(
  7923. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  7924. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  7925. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  7926. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  7927. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  7928. break;
  7929. case OMPC_if:
  7930. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  7931. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  7932. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  7933. DelimLoc, EndLoc);
  7934. break;
  7935. case OMPC_dist_schedule:
  7936. Res = ActOnOpenMPDistScheduleClause(
  7937. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  7938. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  7939. break;
  7940. case OMPC_defaultmap:
  7941. enum { Modifier, DefaultmapKind };
  7942. Res = ActOnOpenMPDefaultmapClause(
  7943. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  7944. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  7945. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  7946. EndLoc);
  7947. break;
  7948. case OMPC_final:
  7949. case OMPC_num_threads:
  7950. case OMPC_safelen:
  7951. case OMPC_simdlen:
  7952. case OMPC_collapse:
  7953. case OMPC_default:
  7954. case OMPC_proc_bind:
  7955. case OMPC_private:
  7956. case OMPC_firstprivate:
  7957. case OMPC_lastprivate:
  7958. case OMPC_shared:
  7959. case OMPC_reduction:
  7960. case OMPC_task_reduction:
  7961. case OMPC_in_reduction:
  7962. case OMPC_linear:
  7963. case OMPC_aligned:
  7964. case OMPC_copyin:
  7965. case OMPC_copyprivate:
  7966. case OMPC_ordered:
  7967. case OMPC_nowait:
  7968. case OMPC_untied:
  7969. case OMPC_mergeable:
  7970. case OMPC_threadprivate:
  7971. case OMPC_flush:
  7972. case OMPC_read:
  7973. case OMPC_write:
  7974. case OMPC_update:
  7975. case OMPC_capture:
  7976. case OMPC_seq_cst:
  7977. case OMPC_depend:
  7978. case OMPC_device:
  7979. case OMPC_threads:
  7980. case OMPC_simd:
  7981. case OMPC_map:
  7982. case OMPC_num_teams:
  7983. case OMPC_thread_limit:
  7984. case OMPC_priority:
  7985. case OMPC_grainsize:
  7986. case OMPC_nogroup:
  7987. case OMPC_num_tasks:
  7988. case OMPC_hint:
  7989. case OMPC_unknown:
  7990. case OMPC_uniform:
  7991. case OMPC_to:
  7992. case OMPC_from:
  7993. case OMPC_use_device_ptr:
  7994. case OMPC_is_device_ptr:
  7995. llvm_unreachable("Clause is not allowed.");
  7996. }
  7997. return Res;
  7998. }
  7999. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  8000. OpenMPScheduleClauseModifier M2,
  8001. SourceLocation M1Loc, SourceLocation M2Loc) {
  8002. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  8003. SmallVector<unsigned, 2> Excluded;
  8004. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  8005. Excluded.push_back(M2);
  8006. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  8007. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  8008. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  8009. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  8010. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  8011. << getListOfPossibleValues(OMPC_schedule,
  8012. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  8013. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8014. Excluded)
  8015. << getOpenMPClauseName(OMPC_schedule);
  8016. return true;
  8017. }
  8018. return false;
  8019. }
  8020. OMPClause *Sema::ActOnOpenMPScheduleClause(
  8021. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  8022. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8023. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  8024. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  8025. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  8026. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  8027. return nullptr;
  8028. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8029. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  8030. // but not both.
  8031. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  8032. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  8033. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  8034. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  8035. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  8036. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  8037. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  8038. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  8039. return nullptr;
  8040. }
  8041. if (Kind == OMPC_SCHEDULE_unknown) {
  8042. std::string Values;
  8043. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  8044. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  8045. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8046. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8047. Exclude);
  8048. } else {
  8049. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8050. /*Last=*/OMPC_SCHEDULE_unknown);
  8051. }
  8052. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8053. << Values << getOpenMPClauseName(OMPC_schedule);
  8054. return nullptr;
  8055. }
  8056. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8057. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8058. // schedule(guided).
  8059. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8060. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8061. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8062. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8063. diag::err_omp_schedule_nonmonotonic_static);
  8064. return nullptr;
  8065. }
  8066. Expr *ValExpr = ChunkSize;
  8067. Stmt *HelperValStmt = nullptr;
  8068. if (ChunkSize) {
  8069. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8070. !ChunkSize->isInstantiationDependent() &&
  8071. !ChunkSize->containsUnexpandedParameterPack()) {
  8072. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  8073. ExprResult Val =
  8074. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8075. if (Val.isInvalid())
  8076. return nullptr;
  8077. ValExpr = Val.get();
  8078. // OpenMP [2.7.1, Restrictions]
  8079. // chunk_size must be a loop invariant integer expression with a positive
  8080. // value.
  8081. llvm::APSInt Result;
  8082. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8083. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8084. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8085. << "schedule" << 1 << ChunkSize->getSourceRange();
  8086. return nullptr;
  8087. }
  8088. } else if (getOpenMPCaptureRegionForClause(
  8089. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8090. OMPD_unknown &&
  8091. !CurContext->isDependentContext()) {
  8092. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  8093. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8094. HelperValStmt = buildPreInits(Context, Captures);
  8095. }
  8096. }
  8097. }
  8098. return new (Context)
  8099. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8100. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8101. }
  8102. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8103. SourceLocation StartLoc,
  8104. SourceLocation EndLoc) {
  8105. OMPClause *Res = nullptr;
  8106. switch (Kind) {
  8107. case OMPC_ordered:
  8108. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8109. break;
  8110. case OMPC_nowait:
  8111. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8112. break;
  8113. case OMPC_untied:
  8114. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8115. break;
  8116. case OMPC_mergeable:
  8117. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8118. break;
  8119. case OMPC_read:
  8120. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8121. break;
  8122. case OMPC_write:
  8123. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8124. break;
  8125. case OMPC_update:
  8126. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8127. break;
  8128. case OMPC_capture:
  8129. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8130. break;
  8131. case OMPC_seq_cst:
  8132. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8133. break;
  8134. case OMPC_threads:
  8135. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8136. break;
  8137. case OMPC_simd:
  8138. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8139. break;
  8140. case OMPC_nogroup:
  8141. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8142. break;
  8143. case OMPC_if:
  8144. case OMPC_final:
  8145. case OMPC_num_threads:
  8146. case OMPC_safelen:
  8147. case OMPC_simdlen:
  8148. case OMPC_collapse:
  8149. case OMPC_schedule:
  8150. case OMPC_private:
  8151. case OMPC_firstprivate:
  8152. case OMPC_lastprivate:
  8153. case OMPC_shared:
  8154. case OMPC_reduction:
  8155. case OMPC_task_reduction:
  8156. case OMPC_in_reduction:
  8157. case OMPC_linear:
  8158. case OMPC_aligned:
  8159. case OMPC_copyin:
  8160. case OMPC_copyprivate:
  8161. case OMPC_default:
  8162. case OMPC_proc_bind:
  8163. case OMPC_threadprivate:
  8164. case OMPC_flush:
  8165. case OMPC_depend:
  8166. case OMPC_device:
  8167. case OMPC_map:
  8168. case OMPC_num_teams:
  8169. case OMPC_thread_limit:
  8170. case OMPC_priority:
  8171. case OMPC_grainsize:
  8172. case OMPC_num_tasks:
  8173. case OMPC_hint:
  8174. case OMPC_dist_schedule:
  8175. case OMPC_defaultmap:
  8176. case OMPC_unknown:
  8177. case OMPC_uniform:
  8178. case OMPC_to:
  8179. case OMPC_from:
  8180. case OMPC_use_device_ptr:
  8181. case OMPC_is_device_ptr:
  8182. llvm_unreachable("Clause is not allowed.");
  8183. }
  8184. return Res;
  8185. }
  8186. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  8187. SourceLocation EndLoc) {
  8188. DSAStack->setNowaitRegion();
  8189. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  8190. }
  8191. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  8192. SourceLocation EndLoc) {
  8193. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  8194. }
  8195. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  8196. SourceLocation EndLoc) {
  8197. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  8198. }
  8199. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  8200. SourceLocation EndLoc) {
  8201. return new (Context) OMPReadClause(StartLoc, EndLoc);
  8202. }
  8203. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  8204. SourceLocation EndLoc) {
  8205. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  8206. }
  8207. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  8208. SourceLocation EndLoc) {
  8209. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  8210. }
  8211. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  8212. SourceLocation EndLoc) {
  8213. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  8214. }
  8215. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  8216. SourceLocation EndLoc) {
  8217. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  8218. }
  8219. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  8220. SourceLocation EndLoc) {
  8221. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  8222. }
  8223. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  8224. SourceLocation EndLoc) {
  8225. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  8226. }
  8227. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  8228. SourceLocation EndLoc) {
  8229. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  8230. }
  8231. OMPClause *Sema::ActOnOpenMPVarListClause(
  8232. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  8233. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  8234. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  8235. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  8236. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  8237. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8238. SourceLocation DepLinMapLoc) {
  8239. OMPClause *Res = nullptr;
  8240. switch (Kind) {
  8241. case OMPC_private:
  8242. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8243. break;
  8244. case OMPC_firstprivate:
  8245. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8246. break;
  8247. case OMPC_lastprivate:
  8248. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8249. break;
  8250. case OMPC_shared:
  8251. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  8252. break;
  8253. case OMPC_reduction:
  8254. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8255. EndLoc, ReductionIdScopeSpec, ReductionId);
  8256. break;
  8257. case OMPC_task_reduction:
  8258. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8259. EndLoc, ReductionIdScopeSpec,
  8260. ReductionId);
  8261. break;
  8262. case OMPC_in_reduction:
  8263. Res =
  8264. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8265. EndLoc, ReductionIdScopeSpec, ReductionId);
  8266. break;
  8267. case OMPC_linear:
  8268. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  8269. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  8270. break;
  8271. case OMPC_aligned:
  8272. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  8273. ColonLoc, EndLoc);
  8274. break;
  8275. case OMPC_copyin:
  8276. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  8277. break;
  8278. case OMPC_copyprivate:
  8279. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8280. break;
  8281. case OMPC_flush:
  8282. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  8283. break;
  8284. case OMPC_depend:
  8285. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  8286. StartLoc, LParenLoc, EndLoc);
  8287. break;
  8288. case OMPC_map:
  8289. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  8290. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  8291. LParenLoc, EndLoc);
  8292. break;
  8293. case OMPC_to:
  8294. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  8295. break;
  8296. case OMPC_from:
  8297. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  8298. break;
  8299. case OMPC_use_device_ptr:
  8300. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8301. break;
  8302. case OMPC_is_device_ptr:
  8303. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8304. break;
  8305. case OMPC_if:
  8306. case OMPC_final:
  8307. case OMPC_num_threads:
  8308. case OMPC_safelen:
  8309. case OMPC_simdlen:
  8310. case OMPC_collapse:
  8311. case OMPC_default:
  8312. case OMPC_proc_bind:
  8313. case OMPC_schedule:
  8314. case OMPC_ordered:
  8315. case OMPC_nowait:
  8316. case OMPC_untied:
  8317. case OMPC_mergeable:
  8318. case OMPC_threadprivate:
  8319. case OMPC_read:
  8320. case OMPC_write:
  8321. case OMPC_update:
  8322. case OMPC_capture:
  8323. case OMPC_seq_cst:
  8324. case OMPC_device:
  8325. case OMPC_threads:
  8326. case OMPC_simd:
  8327. case OMPC_num_teams:
  8328. case OMPC_thread_limit:
  8329. case OMPC_priority:
  8330. case OMPC_grainsize:
  8331. case OMPC_nogroup:
  8332. case OMPC_num_tasks:
  8333. case OMPC_hint:
  8334. case OMPC_dist_schedule:
  8335. case OMPC_defaultmap:
  8336. case OMPC_unknown:
  8337. case OMPC_uniform:
  8338. llvm_unreachable("Clause is not allowed.");
  8339. }
  8340. return Res;
  8341. }
  8342. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  8343. ExprObjectKind OK, SourceLocation Loc) {
  8344. ExprResult Res = BuildDeclRefExpr(
  8345. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  8346. if (!Res.isUsable())
  8347. return ExprError();
  8348. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  8349. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  8350. if (!Res.isUsable())
  8351. return ExprError();
  8352. }
  8353. if (VK != VK_LValue && Res.get()->isGLValue()) {
  8354. Res = DefaultLvalueConversion(Res.get());
  8355. if (!Res.isUsable())
  8356. return ExprError();
  8357. }
  8358. return Res;
  8359. }
  8360. static std::pair<ValueDecl *, bool>
  8361. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  8362. SourceRange &ERange, bool AllowArraySection = false) {
  8363. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  8364. RefExpr->containsUnexpandedParameterPack())
  8365. return std::make_pair(nullptr, true);
  8366. // OpenMP [3.1, C/C++]
  8367. // A list item is a variable name.
  8368. // OpenMP [2.9.3.3, Restrictions, p.1]
  8369. // A variable that is part of another variable (as an array or
  8370. // structure element) cannot appear in a private clause.
  8371. RefExpr = RefExpr->IgnoreParens();
  8372. enum {
  8373. NoArrayExpr = -1,
  8374. ArraySubscript = 0,
  8375. OMPArraySection = 1
  8376. } IsArrayExpr = NoArrayExpr;
  8377. if (AllowArraySection) {
  8378. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  8379. auto *Base = ASE->getBase()->IgnoreParenImpCasts();
  8380. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8381. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8382. RefExpr = Base;
  8383. IsArrayExpr = ArraySubscript;
  8384. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  8385. auto *Base = OASE->getBase()->IgnoreParenImpCasts();
  8386. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  8387. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  8388. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8389. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8390. RefExpr = Base;
  8391. IsArrayExpr = OMPArraySection;
  8392. }
  8393. }
  8394. ELoc = RefExpr->getExprLoc();
  8395. ERange = RefExpr->getSourceRange();
  8396. RefExpr = RefExpr->IgnoreParenImpCasts();
  8397. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  8398. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  8399. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  8400. (S.getCurrentThisType().isNull() || !ME ||
  8401. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  8402. !isa<FieldDecl>(ME->getMemberDecl()))) {
  8403. if (IsArrayExpr != NoArrayExpr)
  8404. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  8405. << ERange;
  8406. else {
  8407. S.Diag(ELoc,
  8408. AllowArraySection
  8409. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  8410. : diag::err_omp_expected_var_name_member_expr)
  8411. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  8412. }
  8413. return std::make_pair(nullptr, false);
  8414. }
  8415. return std::make_pair(
  8416. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  8417. }
  8418. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  8419. SourceLocation StartLoc,
  8420. SourceLocation LParenLoc,
  8421. SourceLocation EndLoc) {
  8422. SmallVector<Expr *, 8> Vars;
  8423. SmallVector<Expr *, 8> PrivateCopies;
  8424. for (auto &RefExpr : VarList) {
  8425. assert(RefExpr && "NULL expr in OpenMP private clause.");
  8426. SourceLocation ELoc;
  8427. SourceRange ERange;
  8428. Expr *SimpleRefExpr = RefExpr;
  8429. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8430. if (Res.second) {
  8431. // It will be analyzed later.
  8432. Vars.push_back(RefExpr);
  8433. PrivateCopies.push_back(nullptr);
  8434. }
  8435. ValueDecl *D = Res.first;
  8436. if (!D)
  8437. continue;
  8438. QualType Type = D->getType();
  8439. auto *VD = dyn_cast<VarDecl>(D);
  8440. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8441. // A variable that appears in a private clause must not have an incomplete
  8442. // type or a reference type.
  8443. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  8444. continue;
  8445. Type = Type.getNonReferenceType();
  8446. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8447. // in a Construct]
  8448. // Variables with the predetermined data-sharing attributes may not be
  8449. // listed in data-sharing attributes clauses, except for the cases
  8450. // listed below. For these exceptions only, listing a predetermined
  8451. // variable in a data-sharing attribute clause is allowed and overrides
  8452. // the variable's predetermined data-sharing attributes.
  8453. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8454. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  8455. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8456. << getOpenMPClauseName(OMPC_private);
  8457. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8458. continue;
  8459. }
  8460. auto CurrDir = DSAStack->getCurrentDirective();
  8461. // Variably modified types are not supported for tasks.
  8462. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8463. isOpenMPTaskingDirective(CurrDir)) {
  8464. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8465. << getOpenMPClauseName(OMPC_private) << Type
  8466. << getOpenMPDirectiveName(CurrDir);
  8467. bool IsDecl =
  8468. !VD ||
  8469. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8470. Diag(D->getLocation(),
  8471. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8472. << D;
  8473. continue;
  8474. }
  8475. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8476. // A list item cannot appear in both a map clause and a data-sharing
  8477. // attribute clause on the same construct
  8478. if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
  8479. CurrDir == OMPD_target_teams ||
  8480. CurrDir == OMPD_target_teams_distribute ||
  8481. CurrDir == OMPD_target_teams_distribute_parallel_for ||
  8482. CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
  8483. CurrDir == OMPD_target_teams_distribute_simd ||
  8484. CurrDir == OMPD_target_parallel_for_simd ||
  8485. CurrDir == OMPD_target_parallel_for) {
  8486. OpenMPClauseKind ConflictKind;
  8487. if (DSAStack->checkMappableExprComponentListsForDecl(
  8488. VD, /*CurrentRegionOnly=*/true,
  8489. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8490. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8491. ConflictKind = WhereFoundClauseKind;
  8492. return true;
  8493. })) {
  8494. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8495. << getOpenMPClauseName(OMPC_private)
  8496. << getOpenMPClauseName(ConflictKind)
  8497. << getOpenMPDirectiveName(CurrDir);
  8498. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8499. continue;
  8500. }
  8501. }
  8502. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  8503. // A variable of class type (or array thereof) that appears in a private
  8504. // clause requires an accessible, unambiguous default constructor for the
  8505. // class type.
  8506. // Generate helper private variable and initialize it with the default
  8507. // value. The address of the original variable is replaced by the address of
  8508. // the new private variable in CodeGen. This new variable is not added to
  8509. // IdResolver, so the code in the OpenMP region uses original variable for
  8510. // proper diagnostics.
  8511. Type = Type.getUnqualifiedType();
  8512. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8513. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8514. ActOnUninitializedDecl(VDPrivate);
  8515. if (VDPrivate->isInvalidDecl())
  8516. continue;
  8517. auto VDPrivateRefExpr = buildDeclRefExpr(
  8518. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  8519. DeclRefExpr *Ref = nullptr;
  8520. if (!VD && !CurContext->isDependentContext())
  8521. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8522. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  8523. Vars.push_back((VD || CurContext->isDependentContext())
  8524. ? RefExpr->IgnoreParens()
  8525. : Ref);
  8526. PrivateCopies.push_back(VDPrivateRefExpr);
  8527. }
  8528. if (Vars.empty())
  8529. return nullptr;
  8530. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  8531. PrivateCopies);
  8532. }
  8533. namespace {
  8534. class DiagsUninitializedSeveretyRAII {
  8535. private:
  8536. DiagnosticsEngine &Diags;
  8537. SourceLocation SavedLoc;
  8538. bool IsIgnored;
  8539. public:
  8540. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  8541. bool IsIgnored)
  8542. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  8543. if (!IsIgnored) {
  8544. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  8545. /*Map*/ diag::Severity::Ignored, Loc);
  8546. }
  8547. }
  8548. ~DiagsUninitializedSeveretyRAII() {
  8549. if (!IsIgnored)
  8550. Diags.popMappings(SavedLoc);
  8551. }
  8552. };
  8553. }
  8554. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  8555. SourceLocation StartLoc,
  8556. SourceLocation LParenLoc,
  8557. SourceLocation EndLoc) {
  8558. SmallVector<Expr *, 8> Vars;
  8559. SmallVector<Expr *, 8> PrivateCopies;
  8560. SmallVector<Expr *, 8> Inits;
  8561. SmallVector<Decl *, 4> ExprCaptures;
  8562. bool IsImplicitClause =
  8563. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  8564. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  8565. for (auto &RefExpr : VarList) {
  8566. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  8567. SourceLocation ELoc;
  8568. SourceRange ERange;
  8569. Expr *SimpleRefExpr = RefExpr;
  8570. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8571. if (Res.second) {
  8572. // It will be analyzed later.
  8573. Vars.push_back(RefExpr);
  8574. PrivateCopies.push_back(nullptr);
  8575. Inits.push_back(nullptr);
  8576. }
  8577. ValueDecl *D = Res.first;
  8578. if (!D)
  8579. continue;
  8580. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  8581. QualType Type = D->getType();
  8582. auto *VD = dyn_cast<VarDecl>(D);
  8583. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8584. // A variable that appears in a private clause must not have an incomplete
  8585. // type or a reference type.
  8586. if (RequireCompleteType(ELoc, Type,
  8587. diag::err_omp_firstprivate_incomplete_type))
  8588. continue;
  8589. Type = Type.getNonReferenceType();
  8590. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  8591. // A variable of class type (or array thereof) that appears in a private
  8592. // clause requires an accessible, unambiguous copy constructor for the
  8593. // class type.
  8594. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  8595. // If an implicit firstprivate variable found it was checked already.
  8596. DSAStackTy::DSAVarData TopDVar;
  8597. if (!IsImplicitClause) {
  8598. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8599. TopDVar = DVar;
  8600. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8601. bool IsConstant = ElemType.isConstant(Context);
  8602. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  8603. // A list item that specifies a given variable may not appear in more
  8604. // than one clause on the same directive, except that a variable may be
  8605. // specified in both firstprivate and lastprivate clauses.
  8606. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8607. // A list item may appear in a firstprivate or lastprivate clause but not
  8608. // both.
  8609. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  8610. (isOpenMPDistributeDirective(CurrDir) ||
  8611. DVar.CKind != OMPC_lastprivate) &&
  8612. DVar.RefExpr) {
  8613. Diag(ELoc, diag::err_omp_wrong_dsa)
  8614. << getOpenMPClauseName(DVar.CKind)
  8615. << getOpenMPClauseName(OMPC_firstprivate);
  8616. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8617. continue;
  8618. }
  8619. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8620. // in a Construct]
  8621. // Variables with the predetermined data-sharing attributes may not be
  8622. // listed in data-sharing attributes clauses, except for the cases
  8623. // listed below. For these exceptions only, listing a predetermined
  8624. // variable in a data-sharing attribute clause is allowed and overrides
  8625. // the variable's predetermined data-sharing attributes.
  8626. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8627. // in a Construct, C/C++, p.2]
  8628. // Variables with const-qualified type having no mutable member may be
  8629. // listed in a firstprivate clause, even if they are static data members.
  8630. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  8631. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  8632. Diag(ELoc, diag::err_omp_wrong_dsa)
  8633. << getOpenMPClauseName(DVar.CKind)
  8634. << getOpenMPClauseName(OMPC_firstprivate);
  8635. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8636. continue;
  8637. }
  8638. // OpenMP [2.9.3.4, Restrictions, p.2]
  8639. // A list item that is private within a parallel region must not appear
  8640. // in a firstprivate clause on a worksharing construct if any of the
  8641. // worksharing regions arising from the worksharing construct ever bind
  8642. // to any of the parallel regions arising from the parallel construct.
  8643. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8644. // A list item that is private within a teams region must not appear in a
  8645. // firstprivate clause on a distribute construct if any of the distribute
  8646. // regions arising from the distribute construct ever bind to any of the
  8647. // teams regions arising from the teams construct.
  8648. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8649. // A list item that appears in a reduction clause of a teams construct
  8650. // must not appear in a firstprivate clause on a distribute construct if
  8651. // any of the distribute regions arising from the distribute construct
  8652. // ever bind to any of the teams regions arising from the teams construct.
  8653. if ((isOpenMPWorksharingDirective(CurrDir) ||
  8654. isOpenMPDistributeDirective(CurrDir)) &&
  8655. !isOpenMPParallelDirective(CurrDir) &&
  8656. !isOpenMPTeamsDirective(CurrDir)) {
  8657. DVar = DSAStack->getImplicitDSA(D, true);
  8658. if (DVar.CKind != OMPC_shared &&
  8659. (isOpenMPParallelDirective(DVar.DKind) ||
  8660. isOpenMPTeamsDirective(DVar.DKind) ||
  8661. DVar.DKind == OMPD_unknown)) {
  8662. Diag(ELoc, diag::err_omp_required_access)
  8663. << getOpenMPClauseName(OMPC_firstprivate)
  8664. << getOpenMPClauseName(OMPC_shared);
  8665. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8666. continue;
  8667. }
  8668. }
  8669. // OpenMP [2.9.3.4, Restrictions, p.3]
  8670. // A list item that appears in a reduction clause of a parallel construct
  8671. // must not appear in a firstprivate clause on a worksharing or task
  8672. // construct if any of the worksharing or task regions arising from the
  8673. // worksharing or task construct ever bind to any of the parallel regions
  8674. // arising from the parallel construct.
  8675. // OpenMP [2.9.3.4, Restrictions, p.4]
  8676. // A list item that appears in a reduction clause in worksharing
  8677. // construct must not appear in a firstprivate clause in a task construct
  8678. // encountered during execution of any of the worksharing regions arising
  8679. // from the worksharing construct.
  8680. if (isOpenMPTaskingDirective(CurrDir)) {
  8681. DVar = DSAStack->hasInnermostDSA(
  8682. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  8683. [](OpenMPDirectiveKind K) -> bool {
  8684. return isOpenMPParallelDirective(K) ||
  8685. isOpenMPWorksharingDirective(K) ||
  8686. isOpenMPTeamsDirective(K);
  8687. },
  8688. /*FromParent=*/true);
  8689. if (DVar.CKind == OMPC_reduction &&
  8690. (isOpenMPParallelDirective(DVar.DKind) ||
  8691. isOpenMPWorksharingDirective(DVar.DKind) ||
  8692. isOpenMPTeamsDirective(DVar.DKind))) {
  8693. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  8694. << getOpenMPDirectiveName(DVar.DKind);
  8695. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8696. continue;
  8697. }
  8698. }
  8699. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8700. // A list item cannot appear in both a map clause and a data-sharing
  8701. // attribute clause on the same construct
  8702. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  8703. OpenMPClauseKind ConflictKind;
  8704. if (DSAStack->checkMappableExprComponentListsForDecl(
  8705. VD, /*CurrentRegionOnly=*/true,
  8706. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8707. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8708. ConflictKind = WhereFoundClauseKind;
  8709. return true;
  8710. })) {
  8711. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8712. << getOpenMPClauseName(OMPC_firstprivate)
  8713. << getOpenMPClauseName(ConflictKind)
  8714. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8715. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8716. continue;
  8717. }
  8718. }
  8719. }
  8720. // Variably modified types are not supported for tasks.
  8721. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8722. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  8723. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8724. << getOpenMPClauseName(OMPC_firstprivate) << Type
  8725. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8726. bool IsDecl =
  8727. !VD ||
  8728. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8729. Diag(D->getLocation(),
  8730. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8731. << D;
  8732. continue;
  8733. }
  8734. Type = Type.getUnqualifiedType();
  8735. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8736. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8737. // Generate helper private variable and initialize it with the value of the
  8738. // original variable. The address of the original variable is replaced by
  8739. // the address of the new private variable in the CodeGen. This new variable
  8740. // is not added to IdResolver, so the code in the OpenMP region uses
  8741. // original variable for proper diagnostics and variable capturing.
  8742. Expr *VDInitRefExpr = nullptr;
  8743. // For arrays generate initializer for single element and replace it by the
  8744. // original array element in CodeGen.
  8745. if (Type->isArrayType()) {
  8746. auto VDInit =
  8747. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  8748. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  8749. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  8750. ElemType = ElemType.getUnqualifiedType();
  8751. auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  8752. ".firstprivate.temp");
  8753. InitializedEntity Entity =
  8754. InitializedEntity::InitializeVariable(VDInitTemp);
  8755. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  8756. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  8757. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  8758. if (Result.isInvalid())
  8759. VDPrivate->setInvalidDecl();
  8760. else
  8761. VDPrivate->setInit(Result.getAs<Expr>());
  8762. // Remove temp variable declaration.
  8763. Context.Deallocate(VDInitTemp);
  8764. } else {
  8765. auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  8766. ".firstprivate.temp");
  8767. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  8768. RefExpr->getExprLoc());
  8769. AddInitializerToDecl(VDPrivate,
  8770. DefaultLvalueConversion(VDInitRefExpr).get(),
  8771. /*DirectInit=*/false);
  8772. }
  8773. if (VDPrivate->isInvalidDecl()) {
  8774. if (IsImplicitClause) {
  8775. Diag(RefExpr->getExprLoc(),
  8776. diag::note_omp_task_predetermined_firstprivate_here);
  8777. }
  8778. continue;
  8779. }
  8780. CurContext->addDecl(VDPrivate);
  8781. auto VDPrivateRefExpr = buildDeclRefExpr(
  8782. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  8783. RefExpr->getExprLoc());
  8784. DeclRefExpr *Ref = nullptr;
  8785. if (!VD && !CurContext->isDependentContext()) {
  8786. if (TopDVar.CKind == OMPC_lastprivate)
  8787. Ref = TopDVar.PrivateCopy;
  8788. else {
  8789. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8790. if (!IsOpenMPCapturedDecl(D))
  8791. ExprCaptures.push_back(Ref->getDecl());
  8792. }
  8793. }
  8794. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  8795. Vars.push_back((VD || CurContext->isDependentContext())
  8796. ? RefExpr->IgnoreParens()
  8797. : Ref);
  8798. PrivateCopies.push_back(VDPrivateRefExpr);
  8799. Inits.push_back(VDInitRefExpr);
  8800. }
  8801. if (Vars.empty())
  8802. return nullptr;
  8803. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8804. Vars, PrivateCopies, Inits,
  8805. buildPreInits(Context, ExprCaptures));
  8806. }
  8807. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  8808. SourceLocation StartLoc,
  8809. SourceLocation LParenLoc,
  8810. SourceLocation EndLoc) {
  8811. SmallVector<Expr *, 8> Vars;
  8812. SmallVector<Expr *, 8> SrcExprs;
  8813. SmallVector<Expr *, 8> DstExprs;
  8814. SmallVector<Expr *, 8> AssignmentOps;
  8815. SmallVector<Decl *, 4> ExprCaptures;
  8816. SmallVector<Expr *, 4> ExprPostUpdates;
  8817. for (auto &RefExpr : VarList) {
  8818. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8819. SourceLocation ELoc;
  8820. SourceRange ERange;
  8821. Expr *SimpleRefExpr = RefExpr;
  8822. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8823. if (Res.second) {
  8824. // It will be analyzed later.
  8825. Vars.push_back(RefExpr);
  8826. SrcExprs.push_back(nullptr);
  8827. DstExprs.push_back(nullptr);
  8828. AssignmentOps.push_back(nullptr);
  8829. }
  8830. ValueDecl *D = Res.first;
  8831. if (!D)
  8832. continue;
  8833. QualType Type = D->getType();
  8834. auto *VD = dyn_cast<VarDecl>(D);
  8835. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  8836. // A variable that appears in a lastprivate clause must not have an
  8837. // incomplete type or a reference type.
  8838. if (RequireCompleteType(ELoc, Type,
  8839. diag::err_omp_lastprivate_incomplete_type))
  8840. continue;
  8841. Type = Type.getNonReferenceType();
  8842. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8843. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  8844. // in a Construct]
  8845. // Variables with the predetermined data-sharing attributes may not be
  8846. // listed in data-sharing attributes clauses, except for the cases
  8847. // listed below.
  8848. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8849. // A list item may appear in a firstprivate or lastprivate clause but not
  8850. // both.
  8851. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8852. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  8853. (isOpenMPDistributeDirective(CurrDir) ||
  8854. DVar.CKind != OMPC_firstprivate) &&
  8855. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  8856. Diag(ELoc, diag::err_omp_wrong_dsa)
  8857. << getOpenMPClauseName(DVar.CKind)
  8858. << getOpenMPClauseName(OMPC_lastprivate);
  8859. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8860. continue;
  8861. }
  8862. // OpenMP [2.14.3.5, Restrictions, p.2]
  8863. // A list item that is private within a parallel region, or that appears in
  8864. // the reduction clause of a parallel construct, must not appear in a
  8865. // lastprivate clause on a worksharing construct if any of the corresponding
  8866. // worksharing regions ever binds to any of the corresponding parallel
  8867. // regions.
  8868. DSAStackTy::DSAVarData TopDVar = DVar;
  8869. if (isOpenMPWorksharingDirective(CurrDir) &&
  8870. !isOpenMPParallelDirective(CurrDir) &&
  8871. !isOpenMPTeamsDirective(CurrDir)) {
  8872. DVar = DSAStack->getImplicitDSA(D, true);
  8873. if (DVar.CKind != OMPC_shared) {
  8874. Diag(ELoc, diag::err_omp_required_access)
  8875. << getOpenMPClauseName(OMPC_lastprivate)
  8876. << getOpenMPClauseName(OMPC_shared);
  8877. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8878. continue;
  8879. }
  8880. }
  8881. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  8882. // A variable of class type (or array thereof) that appears in a
  8883. // lastprivate clause requires an accessible, unambiguous default
  8884. // constructor for the class type, unless the list item is also specified
  8885. // in a firstprivate clause.
  8886. // A variable of class type (or array thereof) that appears in a
  8887. // lastprivate clause requires an accessible, unambiguous copy assignment
  8888. // operator for the class type.
  8889. Type = Context.getBaseElementType(Type).getNonReferenceType();
  8890. auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  8891. Type.getUnqualifiedType(), ".lastprivate.src",
  8892. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8893. auto *PseudoSrcExpr =
  8894. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  8895. auto *DstVD =
  8896. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  8897. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8898. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  8899. // For arrays generate assignment operation for single element and replace
  8900. // it by the original array element in CodeGen.
  8901. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  8902. PseudoDstExpr, PseudoSrcExpr);
  8903. if (AssignmentOp.isInvalid())
  8904. continue;
  8905. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  8906. /*DiscardedValue=*/true);
  8907. if (AssignmentOp.isInvalid())
  8908. continue;
  8909. DeclRefExpr *Ref = nullptr;
  8910. if (!VD && !CurContext->isDependentContext()) {
  8911. if (TopDVar.CKind == OMPC_firstprivate)
  8912. Ref = TopDVar.PrivateCopy;
  8913. else {
  8914. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8915. if (!IsOpenMPCapturedDecl(D))
  8916. ExprCaptures.push_back(Ref->getDecl());
  8917. }
  8918. if (TopDVar.CKind == OMPC_firstprivate ||
  8919. (!IsOpenMPCapturedDecl(D) &&
  8920. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  8921. ExprResult RefRes = DefaultLvalueConversion(Ref);
  8922. if (!RefRes.isUsable())
  8923. continue;
  8924. ExprResult PostUpdateRes =
  8925. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  8926. RefRes.get());
  8927. if (!PostUpdateRes.isUsable())
  8928. continue;
  8929. ExprPostUpdates.push_back(
  8930. IgnoredValueConversions(PostUpdateRes.get()).get());
  8931. }
  8932. }
  8933. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  8934. Vars.push_back((VD || CurContext->isDependentContext())
  8935. ? RefExpr->IgnoreParens()
  8936. : Ref);
  8937. SrcExprs.push_back(PseudoSrcExpr);
  8938. DstExprs.push_back(PseudoDstExpr);
  8939. AssignmentOps.push_back(AssignmentOp.get());
  8940. }
  8941. if (Vars.empty())
  8942. return nullptr;
  8943. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8944. Vars, SrcExprs, DstExprs, AssignmentOps,
  8945. buildPreInits(Context, ExprCaptures),
  8946. buildPostUpdate(*this, ExprPostUpdates));
  8947. }
  8948. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  8949. SourceLocation StartLoc,
  8950. SourceLocation LParenLoc,
  8951. SourceLocation EndLoc) {
  8952. SmallVector<Expr *, 8> Vars;
  8953. for (auto &RefExpr : VarList) {
  8954. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8955. SourceLocation ELoc;
  8956. SourceRange ERange;
  8957. Expr *SimpleRefExpr = RefExpr;
  8958. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8959. if (Res.second) {
  8960. // It will be analyzed later.
  8961. Vars.push_back(RefExpr);
  8962. }
  8963. ValueDecl *D = Res.first;
  8964. if (!D)
  8965. continue;
  8966. auto *VD = dyn_cast<VarDecl>(D);
  8967. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8968. // in a Construct]
  8969. // Variables with the predetermined data-sharing attributes may not be
  8970. // listed in data-sharing attributes clauses, except for the cases
  8971. // listed below. For these exceptions only, listing a predetermined
  8972. // variable in a data-sharing attribute clause is allowed and overrides
  8973. // the variable's predetermined data-sharing attributes.
  8974. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8975. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  8976. DVar.RefExpr) {
  8977. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8978. << getOpenMPClauseName(OMPC_shared);
  8979. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8980. continue;
  8981. }
  8982. DeclRefExpr *Ref = nullptr;
  8983. if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  8984. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8985. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  8986. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  8987. ? RefExpr->IgnoreParens()
  8988. : Ref);
  8989. }
  8990. if (Vars.empty())
  8991. return nullptr;
  8992. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  8993. }
  8994. namespace {
  8995. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  8996. DSAStackTy *Stack;
  8997. public:
  8998. bool VisitDeclRefExpr(DeclRefExpr *E) {
  8999. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  9000. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  9001. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  9002. return false;
  9003. if (DVar.CKind != OMPC_unknown)
  9004. return true;
  9005. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  9006. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  9007. /*FromParent=*/true);
  9008. if (DVarPrivate.CKind != OMPC_unknown)
  9009. return true;
  9010. return false;
  9011. }
  9012. return false;
  9013. }
  9014. bool VisitStmt(Stmt *S) {
  9015. for (auto Child : S->children()) {
  9016. if (Child && Visit(Child))
  9017. return true;
  9018. }
  9019. return false;
  9020. }
  9021. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  9022. };
  9023. } // namespace
  9024. namespace {
  9025. // Transform MemberExpression for specified FieldDecl of current class to
  9026. // DeclRefExpr to specified OMPCapturedExprDecl.
  9027. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  9028. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  9029. ValueDecl *Field;
  9030. DeclRefExpr *CapturedExpr;
  9031. public:
  9032. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  9033. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  9034. ExprResult TransformMemberExpr(MemberExpr *E) {
  9035. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  9036. E->getMemberDecl() == Field) {
  9037. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  9038. return CapturedExpr;
  9039. }
  9040. return BaseTransform::TransformMemberExpr(E);
  9041. }
  9042. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  9043. };
  9044. } // namespace
  9045. template <typename T>
  9046. static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
  9047. const llvm::function_ref<T(ValueDecl *)> &Gen) {
  9048. for (auto &Set : Lookups) {
  9049. for (auto *D : Set) {
  9050. if (auto Res = Gen(cast<ValueDecl>(D)))
  9051. return Res;
  9052. }
  9053. }
  9054. return T();
  9055. }
  9056. static ExprResult
  9057. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  9058. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  9059. const DeclarationNameInfo &ReductionId, QualType Ty,
  9060. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  9061. if (ReductionIdScopeSpec.isInvalid())
  9062. return ExprError();
  9063. SmallVector<UnresolvedSet<8>, 4> Lookups;
  9064. if (S) {
  9065. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9066. Lookup.suppressDiagnostics();
  9067. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  9068. auto *D = Lookup.getRepresentativeDecl();
  9069. do {
  9070. S = S->getParent();
  9071. } while (S && !S->isDeclScope(D));
  9072. if (S)
  9073. S = S->getParent();
  9074. Lookups.push_back(UnresolvedSet<8>());
  9075. Lookups.back().append(Lookup.begin(), Lookup.end());
  9076. Lookup.clear();
  9077. }
  9078. } else if (auto *ULE =
  9079. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  9080. Lookups.push_back(UnresolvedSet<8>());
  9081. Decl *PrevD = nullptr;
  9082. for (auto *D : ULE->decls()) {
  9083. if (D == PrevD)
  9084. Lookups.push_back(UnresolvedSet<8>());
  9085. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  9086. Lookups.back().addDecl(DRD);
  9087. PrevD = D;
  9088. }
  9089. }
  9090. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  9091. Ty->isInstantiationDependentType() ||
  9092. Ty->containsUnexpandedParameterPack() ||
  9093. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
  9094. return !D->isInvalidDecl() &&
  9095. (D->getType()->isDependentType() ||
  9096. D->getType()->isInstantiationDependentType() ||
  9097. D->getType()->containsUnexpandedParameterPack());
  9098. })) {
  9099. UnresolvedSet<8> ResSet;
  9100. for (auto &Set : Lookups) {
  9101. ResSet.append(Set.begin(), Set.end());
  9102. // The last item marks the end of all declarations at the specified scope.
  9103. ResSet.addDecl(Set[Set.size() - 1]);
  9104. }
  9105. return UnresolvedLookupExpr::Create(
  9106. SemaRef.Context, /*NamingClass=*/nullptr,
  9107. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  9108. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  9109. }
  9110. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9111. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  9112. if (!D->isInvalidDecl() &&
  9113. SemaRef.Context.hasSameType(D->getType(), Ty))
  9114. return D;
  9115. return nullptr;
  9116. }))
  9117. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9118. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9119. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  9120. if (!D->isInvalidDecl() &&
  9121. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  9122. !Ty.isMoreQualifiedThan(D->getType()))
  9123. return D;
  9124. return nullptr;
  9125. })) {
  9126. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  9127. /*DetectVirtual=*/false);
  9128. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  9129. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  9130. VD->getType().getUnqualifiedType()))) {
  9131. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  9132. /*DiagID=*/0) !=
  9133. Sema::AR_inaccessible) {
  9134. SemaRef.BuildBasePathArray(Paths, BasePath);
  9135. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9136. }
  9137. }
  9138. }
  9139. }
  9140. if (ReductionIdScopeSpec.isSet()) {
  9141. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  9142. return ExprError();
  9143. }
  9144. return ExprEmpty();
  9145. }
  9146. namespace {
  9147. /// Data for the reduction-based clauses.
  9148. struct ReductionData {
  9149. /// List of original reduction items.
  9150. SmallVector<Expr *, 8> Vars;
  9151. /// List of private copies of the reduction items.
  9152. SmallVector<Expr *, 8> Privates;
  9153. /// LHS expressions for the reduction_op expressions.
  9154. SmallVector<Expr *, 8> LHSs;
  9155. /// RHS expressions for the reduction_op expressions.
  9156. SmallVector<Expr *, 8> RHSs;
  9157. /// Reduction operation expression.
  9158. SmallVector<Expr *, 8> ReductionOps;
  9159. /// Taskgroup descriptors for the corresponding reduction items in
  9160. /// in_reduction clauses.
  9161. SmallVector<Expr *, 8> TaskgroupDescriptors;
  9162. /// List of captures for clause.
  9163. SmallVector<Decl *, 4> ExprCaptures;
  9164. /// List of postupdate expressions.
  9165. SmallVector<Expr *, 4> ExprPostUpdates;
  9166. ReductionData() = delete;
  9167. /// Reserves required memory for the reduction data.
  9168. ReductionData(unsigned Size) {
  9169. Vars.reserve(Size);
  9170. Privates.reserve(Size);
  9171. LHSs.reserve(Size);
  9172. RHSs.reserve(Size);
  9173. ReductionOps.reserve(Size);
  9174. TaskgroupDescriptors.reserve(Size);
  9175. ExprCaptures.reserve(Size);
  9176. ExprPostUpdates.reserve(Size);
  9177. }
  9178. /// Stores reduction item and reduction operation only (required for dependent
  9179. /// reduction item).
  9180. void push(Expr *Item, Expr *ReductionOp) {
  9181. Vars.emplace_back(Item);
  9182. Privates.emplace_back(nullptr);
  9183. LHSs.emplace_back(nullptr);
  9184. RHSs.emplace_back(nullptr);
  9185. ReductionOps.emplace_back(ReductionOp);
  9186. TaskgroupDescriptors.emplace_back(nullptr);
  9187. }
  9188. /// Stores reduction data.
  9189. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  9190. Expr *TaskgroupDescriptor) {
  9191. Vars.emplace_back(Item);
  9192. Privates.emplace_back(Private);
  9193. LHSs.emplace_back(LHS);
  9194. RHSs.emplace_back(RHS);
  9195. ReductionOps.emplace_back(ReductionOp);
  9196. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  9197. }
  9198. };
  9199. } // namespace
  9200. static bool CheckOMPArraySectionConstantForReduction(
  9201. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  9202. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  9203. const Expr *Length = OASE->getLength();
  9204. if (Length == nullptr) {
  9205. // For array sections of the form [1:] or [:], we would need to analyze
  9206. // the lower bound...
  9207. if (OASE->getColonLoc().isValid())
  9208. return false;
  9209. // This is an array subscript which has implicit length 1!
  9210. SingleElement = true;
  9211. ArraySizes.push_back(llvm::APSInt::get(1));
  9212. } else {
  9213. llvm::APSInt ConstantLengthValue;
  9214. if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
  9215. return false;
  9216. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  9217. ArraySizes.push_back(ConstantLengthValue);
  9218. }
  9219. // Get the base of this array section and walk up from there.
  9220. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9221. // We require length = 1 for all array sections except the right-most to
  9222. // guarantee that the memory region is contiguous and has no holes in it.
  9223. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  9224. Length = TempOASE->getLength();
  9225. if (Length == nullptr) {
  9226. // For array sections of the form [1:] or [:], we would need to analyze
  9227. // the lower bound...
  9228. if (OASE->getColonLoc().isValid())
  9229. return false;
  9230. // This is an array subscript which has implicit length 1!
  9231. ArraySizes.push_back(llvm::APSInt::get(1));
  9232. } else {
  9233. llvm::APSInt ConstantLengthValue;
  9234. if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
  9235. ConstantLengthValue.getSExtValue() != 1)
  9236. return false;
  9237. ArraySizes.push_back(ConstantLengthValue);
  9238. }
  9239. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9240. }
  9241. // If we have a single element, we don't need to add the implicit lengths.
  9242. if (!SingleElement) {
  9243. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  9244. // Has implicit length 1!
  9245. ArraySizes.push_back(llvm::APSInt::get(1));
  9246. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9247. }
  9248. }
  9249. // This array section can be privatized as a single value or as a constant
  9250. // sized array.
  9251. return true;
  9252. }
  9253. static bool ActOnOMPReductionKindClause(
  9254. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  9255. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9256. SourceLocation ColonLoc, SourceLocation EndLoc,
  9257. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9258. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  9259. auto DN = ReductionId.getName();
  9260. auto OOK = DN.getCXXOverloadedOperator();
  9261. BinaryOperatorKind BOK = BO_Comma;
  9262. ASTContext &Context = S.Context;
  9263. // OpenMP [2.14.3.6, reduction clause]
  9264. // C
  9265. // reduction-identifier is either an identifier or one of the following
  9266. // operators: +, -, *, &, |, ^, && and ||
  9267. // C++
  9268. // reduction-identifier is either an id-expression or one of the following
  9269. // operators: +, -, *, &, |, ^, && and ||
  9270. switch (OOK) {
  9271. case OO_Plus:
  9272. case OO_Minus:
  9273. BOK = BO_Add;
  9274. break;
  9275. case OO_Star:
  9276. BOK = BO_Mul;
  9277. break;
  9278. case OO_Amp:
  9279. BOK = BO_And;
  9280. break;
  9281. case OO_Pipe:
  9282. BOK = BO_Or;
  9283. break;
  9284. case OO_Caret:
  9285. BOK = BO_Xor;
  9286. break;
  9287. case OO_AmpAmp:
  9288. BOK = BO_LAnd;
  9289. break;
  9290. case OO_PipePipe:
  9291. BOK = BO_LOr;
  9292. break;
  9293. case OO_New:
  9294. case OO_Delete:
  9295. case OO_Array_New:
  9296. case OO_Array_Delete:
  9297. case OO_Slash:
  9298. case OO_Percent:
  9299. case OO_Tilde:
  9300. case OO_Exclaim:
  9301. case OO_Equal:
  9302. case OO_Less:
  9303. case OO_Greater:
  9304. case OO_LessEqual:
  9305. case OO_GreaterEqual:
  9306. case OO_PlusEqual:
  9307. case OO_MinusEqual:
  9308. case OO_StarEqual:
  9309. case OO_SlashEqual:
  9310. case OO_PercentEqual:
  9311. case OO_CaretEqual:
  9312. case OO_AmpEqual:
  9313. case OO_PipeEqual:
  9314. case OO_LessLess:
  9315. case OO_GreaterGreater:
  9316. case OO_LessLessEqual:
  9317. case OO_GreaterGreaterEqual:
  9318. case OO_EqualEqual:
  9319. case OO_ExclaimEqual:
  9320. case OO_Spaceship:
  9321. case OO_PlusPlus:
  9322. case OO_MinusMinus:
  9323. case OO_Comma:
  9324. case OO_ArrowStar:
  9325. case OO_Arrow:
  9326. case OO_Call:
  9327. case OO_Subscript:
  9328. case OO_Conditional:
  9329. case OO_Coawait:
  9330. case NUM_OVERLOADED_OPERATORS:
  9331. llvm_unreachable("Unexpected reduction identifier");
  9332. case OO_None:
  9333. if (auto *II = DN.getAsIdentifierInfo()) {
  9334. if (II->isStr("max"))
  9335. BOK = BO_GT;
  9336. else if (II->isStr("min"))
  9337. BOK = BO_LT;
  9338. }
  9339. break;
  9340. }
  9341. SourceRange ReductionIdRange;
  9342. if (ReductionIdScopeSpec.isValid())
  9343. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  9344. else
  9345. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  9346. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  9347. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  9348. bool FirstIter = true;
  9349. for (auto RefExpr : VarList) {
  9350. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  9351. // OpenMP [2.1, C/C++]
  9352. // A list item is a variable or array section, subject to the restrictions
  9353. // specified in Section 2.4 on page 42 and in each of the sections
  9354. // describing clauses and directives for which a list appears.
  9355. // OpenMP [2.14.3.3, Restrictions, p.1]
  9356. // A variable that is part of another variable (as an array or
  9357. // structure element) cannot appear in a private clause.
  9358. if (!FirstIter && IR != ER)
  9359. ++IR;
  9360. FirstIter = false;
  9361. SourceLocation ELoc;
  9362. SourceRange ERange;
  9363. Expr *SimpleRefExpr = RefExpr;
  9364. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  9365. /*AllowArraySection=*/true);
  9366. if (Res.second) {
  9367. // Try to find 'declare reduction' corresponding construct before using
  9368. // builtin/overloaded operators.
  9369. QualType Type = Context.DependentTy;
  9370. CXXCastPath BasePath;
  9371. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9372. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9373. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9374. Expr *ReductionOp = nullptr;
  9375. if (S.CurContext->isDependentContext() &&
  9376. (DeclareReductionRef.isUnset() ||
  9377. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  9378. ReductionOp = DeclareReductionRef.get();
  9379. // It will be analyzed later.
  9380. RD.push(RefExpr, ReductionOp);
  9381. }
  9382. ValueDecl *D = Res.first;
  9383. if (!D)
  9384. continue;
  9385. Expr *TaskgroupDescriptor = nullptr;
  9386. QualType Type;
  9387. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  9388. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  9389. if (ASE)
  9390. Type = ASE->getType().getNonReferenceType();
  9391. else if (OASE) {
  9392. auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  9393. if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
  9394. Type = ATy->getElementType();
  9395. else
  9396. Type = BaseType->getPointeeType();
  9397. Type = Type.getNonReferenceType();
  9398. } else
  9399. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  9400. auto *VD = dyn_cast<VarDecl>(D);
  9401. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9402. // A variable that appears in a private clause must not have an incomplete
  9403. // type or a reference type.
  9404. if (S.RequireCompleteType(ELoc, Type,
  9405. diag::err_omp_reduction_incomplete_type))
  9406. continue;
  9407. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9408. // A list item that appears in a reduction clause must not be
  9409. // const-qualified.
  9410. if (Type.getNonReferenceType().isConstant(Context)) {
  9411. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  9412. if (!ASE && !OASE) {
  9413. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9414. VarDecl::DeclarationOnly;
  9415. S.Diag(D->getLocation(),
  9416. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9417. << D;
  9418. }
  9419. continue;
  9420. }
  9421. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  9422. // If a list-item is a reference type then it must bind to the same object
  9423. // for all threads of the team.
  9424. if (!ASE && !OASE && VD) {
  9425. VarDecl *VDDef = VD->getDefinition();
  9426. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  9427. DSARefChecker Check(Stack);
  9428. if (Check.Visit(VDDef->getInit())) {
  9429. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  9430. << getOpenMPClauseName(ClauseKind) << ERange;
  9431. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  9432. continue;
  9433. }
  9434. }
  9435. }
  9436. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9437. // in a Construct]
  9438. // Variables with the predetermined data-sharing attributes may not be
  9439. // listed in data-sharing attributes clauses, except for the cases
  9440. // listed below. For these exceptions only, listing a predetermined
  9441. // variable in a data-sharing attribute clause is allowed and overrides
  9442. // the variable's predetermined data-sharing attributes.
  9443. // OpenMP [2.14.3.6, Restrictions, p.3]
  9444. // Any number of reduction clauses can be specified on the directive,
  9445. // but a list item can appear only once in the reduction clauses for that
  9446. // directive.
  9447. DSAStackTy::DSAVarData DVar;
  9448. DVar = Stack->getTopDSA(D, false);
  9449. if (DVar.CKind == OMPC_reduction) {
  9450. S.Diag(ELoc, diag::err_omp_once_referenced)
  9451. << getOpenMPClauseName(ClauseKind);
  9452. if (DVar.RefExpr)
  9453. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  9454. continue;
  9455. } else if (DVar.CKind != OMPC_unknown) {
  9456. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  9457. << getOpenMPClauseName(DVar.CKind)
  9458. << getOpenMPClauseName(OMPC_reduction);
  9459. ReportOriginalDSA(S, Stack, D, DVar);
  9460. continue;
  9461. }
  9462. // OpenMP [2.14.3.6, Restrictions, p.1]
  9463. // A list item that appears in a reduction clause of a worksharing
  9464. // construct must be shared in the parallel regions to which any of the
  9465. // worksharing regions arising from the worksharing construct bind.
  9466. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  9467. if (isOpenMPWorksharingDirective(CurrDir) &&
  9468. !isOpenMPParallelDirective(CurrDir) &&
  9469. !isOpenMPTeamsDirective(CurrDir)) {
  9470. DVar = Stack->getImplicitDSA(D, true);
  9471. if (DVar.CKind != OMPC_shared) {
  9472. S.Diag(ELoc, diag::err_omp_required_access)
  9473. << getOpenMPClauseName(OMPC_reduction)
  9474. << getOpenMPClauseName(OMPC_shared);
  9475. ReportOriginalDSA(S, Stack, D, DVar);
  9476. continue;
  9477. }
  9478. }
  9479. // Try to find 'declare reduction' corresponding construct before using
  9480. // builtin/overloaded operators.
  9481. CXXCastPath BasePath;
  9482. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9483. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9484. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9485. if (DeclareReductionRef.isInvalid())
  9486. continue;
  9487. if (S.CurContext->isDependentContext() &&
  9488. (DeclareReductionRef.isUnset() ||
  9489. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  9490. RD.push(RefExpr, DeclareReductionRef.get());
  9491. continue;
  9492. }
  9493. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  9494. // Not allowed reduction identifier is found.
  9495. S.Diag(ReductionId.getLocStart(),
  9496. diag::err_omp_unknown_reduction_identifier)
  9497. << Type << ReductionIdRange;
  9498. continue;
  9499. }
  9500. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9501. // The type of a list item that appears in a reduction clause must be valid
  9502. // for the reduction-identifier. For a max or min reduction in C, the type
  9503. // of the list item must be an allowed arithmetic data type: char, int,
  9504. // float, double, or _Bool, possibly modified with long, short, signed, or
  9505. // unsigned. For a max or min reduction in C++, the type of the list item
  9506. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  9507. // double, or bool, possibly modified with long, short, signed, or unsigned.
  9508. if (DeclareReductionRef.isUnset()) {
  9509. if ((BOK == BO_GT || BOK == BO_LT) &&
  9510. !(Type->isScalarType() ||
  9511. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  9512. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  9513. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  9514. if (!ASE && !OASE) {
  9515. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9516. VarDecl::DeclarationOnly;
  9517. S.Diag(D->getLocation(),
  9518. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9519. << D;
  9520. }
  9521. continue;
  9522. }
  9523. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  9524. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  9525. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  9526. << getOpenMPClauseName(ClauseKind);
  9527. if (!ASE && !OASE) {
  9528. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9529. VarDecl::DeclarationOnly;
  9530. S.Diag(D->getLocation(),
  9531. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9532. << D;
  9533. }
  9534. continue;
  9535. }
  9536. }
  9537. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  9538. auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  9539. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9540. auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  9541. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9542. auto PrivateTy = Type;
  9543. // Try if we can determine constant lengths for all array sections and avoid
  9544. // the VLA.
  9545. bool ConstantLengthOASE = false;
  9546. if (OASE) {
  9547. bool SingleElement;
  9548. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  9549. ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
  9550. Context, OASE, SingleElement, ArraySizes);
  9551. // If we don't have a single element, we must emit a constant array type.
  9552. if (ConstantLengthOASE && !SingleElement) {
  9553. for (auto &Size : ArraySizes) {
  9554. PrivateTy = Context.getConstantArrayType(
  9555. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  9556. }
  9557. }
  9558. }
  9559. if ((OASE && !ConstantLengthOASE) ||
  9560. (!OASE && !ASE &&
  9561. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  9562. if (!Context.getTargetInfo().isVLASupported() &&
  9563. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  9564. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  9565. S.Diag(ELoc, diag::note_vla_unsupported);
  9566. continue;
  9567. }
  9568. // For arrays/array sections only:
  9569. // Create pseudo array type for private copy. The size for this array will
  9570. // be generated during codegen.
  9571. // For array subscripts or single variables Private Ty is the same as Type
  9572. // (type of the variable or single array element).
  9573. PrivateTy = Context.getVariableArrayType(
  9574. Type,
  9575. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  9576. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  9577. } else if (!ASE && !OASE &&
  9578. Context.getAsArrayType(D->getType().getNonReferenceType()))
  9579. PrivateTy = D->getType().getNonReferenceType();
  9580. // Private copy.
  9581. auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  9582. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9583. // Add initializer for private variable.
  9584. Expr *Init = nullptr;
  9585. auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  9586. auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  9587. if (DeclareReductionRef.isUsable()) {
  9588. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  9589. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  9590. if (DRD->getInitializer()) {
  9591. Init = DRDRef;
  9592. RHSVD->setInit(DRDRef);
  9593. RHSVD->setInitStyle(VarDecl::CallInit);
  9594. }
  9595. } else {
  9596. switch (BOK) {
  9597. case BO_Add:
  9598. case BO_Xor:
  9599. case BO_Or:
  9600. case BO_LOr:
  9601. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  9602. if (Type->isScalarType() || Type->isAnyComplexType())
  9603. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  9604. break;
  9605. case BO_Mul:
  9606. case BO_LAnd:
  9607. if (Type->isScalarType() || Type->isAnyComplexType()) {
  9608. // '*' and '&&' reduction ops - initializer is '1'.
  9609. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  9610. }
  9611. break;
  9612. case BO_And: {
  9613. // '&' reduction op - initializer is '~0'.
  9614. QualType OrigType = Type;
  9615. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  9616. Type = ComplexTy->getElementType();
  9617. if (Type->isRealFloatingType()) {
  9618. llvm::APFloat InitValue =
  9619. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  9620. /*isIEEE=*/true);
  9621. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9622. Type, ELoc);
  9623. } else if (Type->isScalarType()) {
  9624. auto Size = Context.getTypeSize(Type);
  9625. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  9626. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  9627. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9628. }
  9629. if (Init && OrigType->isAnyComplexType()) {
  9630. // Init = 0xFFFF + 0xFFFFi;
  9631. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  9632. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  9633. }
  9634. Type = OrigType;
  9635. break;
  9636. }
  9637. case BO_LT:
  9638. case BO_GT: {
  9639. // 'min' reduction op - initializer is 'Largest representable number in
  9640. // the reduction list item type'.
  9641. // 'max' reduction op - initializer is 'Least representable number in
  9642. // the reduction list item type'.
  9643. if (Type->isIntegerType() || Type->isPointerType()) {
  9644. bool IsSigned = Type->hasSignedIntegerRepresentation();
  9645. auto Size = Context.getTypeSize(Type);
  9646. QualType IntTy =
  9647. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  9648. llvm::APInt InitValue =
  9649. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  9650. : llvm::APInt::getMinValue(Size)
  9651. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  9652. : llvm::APInt::getMaxValue(Size);
  9653. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9654. if (Type->isPointerType()) {
  9655. // Cast to pointer type.
  9656. auto CastExpr = S.BuildCStyleCastExpr(
  9657. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  9658. if (CastExpr.isInvalid())
  9659. continue;
  9660. Init = CastExpr.get();
  9661. }
  9662. } else if (Type->isRealFloatingType()) {
  9663. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  9664. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  9665. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9666. Type, ELoc);
  9667. }
  9668. break;
  9669. }
  9670. case BO_PtrMemD:
  9671. case BO_PtrMemI:
  9672. case BO_MulAssign:
  9673. case BO_Div:
  9674. case BO_Rem:
  9675. case BO_Sub:
  9676. case BO_Shl:
  9677. case BO_Shr:
  9678. case BO_LE:
  9679. case BO_GE:
  9680. case BO_EQ:
  9681. case BO_NE:
  9682. case BO_AndAssign:
  9683. case BO_XorAssign:
  9684. case BO_OrAssign:
  9685. case BO_Assign:
  9686. case BO_AddAssign:
  9687. case BO_SubAssign:
  9688. case BO_DivAssign:
  9689. case BO_RemAssign:
  9690. case BO_ShlAssign:
  9691. case BO_ShrAssign:
  9692. case BO_Comma:
  9693. llvm_unreachable("Unexpected reduction operation");
  9694. }
  9695. }
  9696. if (Init && DeclareReductionRef.isUnset())
  9697. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  9698. else if (!Init)
  9699. S.ActOnUninitializedDecl(RHSVD);
  9700. if (RHSVD->isInvalidDecl())
  9701. continue;
  9702. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  9703. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  9704. << Type << ReductionIdRange;
  9705. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9706. VarDecl::DeclarationOnly;
  9707. S.Diag(D->getLocation(),
  9708. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9709. << D;
  9710. continue;
  9711. }
  9712. // Store initializer for single element in private copy. Will be used during
  9713. // codegen.
  9714. PrivateVD->setInit(RHSVD->getInit());
  9715. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  9716. auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  9717. ExprResult ReductionOp;
  9718. if (DeclareReductionRef.isUsable()) {
  9719. QualType RedTy = DeclareReductionRef.get()->getType();
  9720. QualType PtrRedTy = Context.getPointerType(RedTy);
  9721. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  9722. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  9723. if (!BasePath.empty()) {
  9724. LHS = S.DefaultLvalueConversion(LHS.get());
  9725. RHS = S.DefaultLvalueConversion(RHS.get());
  9726. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9727. CK_UncheckedDerivedToBase, LHS.get(),
  9728. &BasePath, LHS.get()->getValueKind());
  9729. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9730. CK_UncheckedDerivedToBase, RHS.get(),
  9731. &BasePath, RHS.get()->getValueKind());
  9732. }
  9733. FunctionProtoType::ExtProtoInfo EPI;
  9734. QualType Params[] = {PtrRedTy, PtrRedTy};
  9735. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  9736. auto *OVE = new (Context) OpaqueValueExpr(
  9737. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  9738. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  9739. Expr *Args[] = {LHS.get(), RHS.get()};
  9740. ReductionOp = new (Context)
  9741. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  9742. } else {
  9743. ReductionOp = S.BuildBinOp(
  9744. Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
  9745. if (ReductionOp.isUsable()) {
  9746. if (BOK != BO_LT && BOK != BO_GT) {
  9747. ReductionOp =
  9748. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9749. BO_Assign, LHSDRE, ReductionOp.get());
  9750. } else {
  9751. auto *ConditionalOp = new (Context)
  9752. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  9753. Type, VK_LValue, OK_Ordinary);
  9754. ReductionOp =
  9755. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9756. BO_Assign, LHSDRE, ConditionalOp);
  9757. }
  9758. if (ReductionOp.isUsable())
  9759. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  9760. }
  9761. if (!ReductionOp.isUsable())
  9762. continue;
  9763. }
  9764. // OpenMP [2.15.4.6, Restrictions, p.2]
  9765. // A list item that appears in an in_reduction clause of a task construct
  9766. // must appear in a task_reduction clause of a construct associated with a
  9767. // taskgroup region that includes the participating task in its taskgroup
  9768. // set. The construct associated with the innermost region that meets this
  9769. // condition must specify the same reduction-identifier as the in_reduction
  9770. // clause.
  9771. if (ClauseKind == OMPC_in_reduction) {
  9772. SourceRange ParentSR;
  9773. BinaryOperatorKind ParentBOK;
  9774. const Expr *ParentReductionOp;
  9775. Expr *ParentBOKTD, *ParentReductionOpTD;
  9776. DSAStackTy::DSAVarData ParentBOKDSA =
  9777. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  9778. ParentBOKTD);
  9779. DSAStackTy::DSAVarData ParentReductionOpDSA =
  9780. Stack->getTopMostTaskgroupReductionData(
  9781. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  9782. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  9783. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  9784. if (!IsParentBOK && !IsParentReductionOp) {
  9785. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  9786. continue;
  9787. }
  9788. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  9789. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  9790. IsParentReductionOp) {
  9791. bool EmitError = true;
  9792. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  9793. llvm::FoldingSetNodeID RedId, ParentRedId;
  9794. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  9795. DeclareReductionRef.get()->Profile(RedId, Context,
  9796. /*Canonical=*/true);
  9797. EmitError = RedId != ParentRedId;
  9798. }
  9799. if (EmitError) {
  9800. S.Diag(ReductionId.getLocStart(),
  9801. diag::err_omp_reduction_identifier_mismatch)
  9802. << ReductionIdRange << RefExpr->getSourceRange();
  9803. S.Diag(ParentSR.getBegin(),
  9804. diag::note_omp_previous_reduction_identifier)
  9805. << ParentSR
  9806. << (IsParentBOK ? ParentBOKDSA.RefExpr
  9807. : ParentReductionOpDSA.RefExpr)
  9808. ->getSourceRange();
  9809. continue;
  9810. }
  9811. }
  9812. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  9813. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  9814. }
  9815. DeclRefExpr *Ref = nullptr;
  9816. Expr *VarsExpr = RefExpr->IgnoreParens();
  9817. if (!VD && !S.CurContext->isDependentContext()) {
  9818. if (ASE || OASE) {
  9819. TransformExprToCaptures RebuildToCapture(S, D);
  9820. VarsExpr =
  9821. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  9822. Ref = RebuildToCapture.getCapturedExpr();
  9823. } else {
  9824. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  9825. }
  9826. if (!S.IsOpenMPCapturedDecl(D)) {
  9827. RD.ExprCaptures.emplace_back(Ref->getDecl());
  9828. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  9829. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  9830. if (!RefRes.isUsable())
  9831. continue;
  9832. ExprResult PostUpdateRes =
  9833. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9834. RefRes.get());
  9835. if (!PostUpdateRes.isUsable())
  9836. continue;
  9837. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  9838. Stack->getCurrentDirective() == OMPD_taskgroup) {
  9839. S.Diag(RefExpr->getExprLoc(),
  9840. diag::err_omp_reduction_non_addressable_expression)
  9841. << RefExpr->getSourceRange();
  9842. continue;
  9843. }
  9844. RD.ExprPostUpdates.emplace_back(
  9845. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  9846. }
  9847. }
  9848. }
  9849. // All reduction items are still marked as reduction (to do not increase
  9850. // code base size).
  9851. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  9852. if (CurrDir == OMPD_taskgroup) {
  9853. if (DeclareReductionRef.isUsable())
  9854. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  9855. DeclareReductionRef.get());
  9856. else
  9857. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  9858. }
  9859. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  9860. TaskgroupDescriptor);
  9861. }
  9862. return RD.Vars.empty();
  9863. }
  9864. OMPClause *Sema::ActOnOpenMPReductionClause(
  9865. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9866. SourceLocation ColonLoc, SourceLocation EndLoc,
  9867. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9868. ArrayRef<Expr *> UnresolvedReductions) {
  9869. ReductionData RD(VarList.size());
  9870. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  9871. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9872. ReductionIdScopeSpec, ReductionId,
  9873. UnresolvedReductions, RD))
  9874. return nullptr;
  9875. return OMPReductionClause::Create(
  9876. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9877. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9878. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9879. buildPreInits(Context, RD.ExprCaptures),
  9880. buildPostUpdate(*this, RD.ExprPostUpdates));
  9881. }
  9882. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  9883. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9884. SourceLocation ColonLoc, SourceLocation EndLoc,
  9885. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9886. ArrayRef<Expr *> UnresolvedReductions) {
  9887. ReductionData RD(VarList.size());
  9888. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
  9889. VarList, StartLoc, LParenLoc, ColonLoc,
  9890. EndLoc, ReductionIdScopeSpec, ReductionId,
  9891. UnresolvedReductions, RD))
  9892. return nullptr;
  9893. return OMPTaskReductionClause::Create(
  9894. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9895. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9896. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9897. buildPreInits(Context, RD.ExprCaptures),
  9898. buildPostUpdate(*this, RD.ExprPostUpdates));
  9899. }
  9900. OMPClause *Sema::ActOnOpenMPInReductionClause(
  9901. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9902. SourceLocation ColonLoc, SourceLocation EndLoc,
  9903. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9904. ArrayRef<Expr *> UnresolvedReductions) {
  9905. ReductionData RD(VarList.size());
  9906. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  9907. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9908. ReductionIdScopeSpec, ReductionId,
  9909. UnresolvedReductions, RD))
  9910. return nullptr;
  9911. return OMPInReductionClause::Create(
  9912. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9913. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9914. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  9915. buildPreInits(Context, RD.ExprCaptures),
  9916. buildPostUpdate(*this, RD.ExprPostUpdates));
  9917. }
  9918. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  9919. SourceLocation LinLoc) {
  9920. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  9921. LinKind == OMPC_LINEAR_unknown) {
  9922. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  9923. return true;
  9924. }
  9925. return false;
  9926. }
  9927. bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
  9928. OpenMPLinearClauseKind LinKind,
  9929. QualType Type) {
  9930. auto *VD = dyn_cast_or_null<VarDecl>(D);
  9931. // A variable must not have an incomplete type or a reference type.
  9932. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  9933. return true;
  9934. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  9935. !Type->isReferenceType()) {
  9936. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  9937. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  9938. return true;
  9939. }
  9940. Type = Type.getNonReferenceType();
  9941. // A list item must not be const-qualified.
  9942. if (Type.isConstant(Context)) {
  9943. Diag(ELoc, diag::err_omp_const_variable)
  9944. << getOpenMPClauseName(OMPC_linear);
  9945. if (D) {
  9946. bool IsDecl =
  9947. !VD ||
  9948. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9949. Diag(D->getLocation(),
  9950. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9951. << D;
  9952. }
  9953. return true;
  9954. }
  9955. // A list item must be of integral or pointer type.
  9956. Type = Type.getUnqualifiedType().getCanonicalType();
  9957. const auto *Ty = Type.getTypePtrOrNull();
  9958. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  9959. !Ty->isPointerType())) {
  9960. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  9961. if (D) {
  9962. bool IsDecl =
  9963. !VD ||
  9964. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9965. Diag(D->getLocation(),
  9966. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9967. << D;
  9968. }
  9969. return true;
  9970. }
  9971. return false;
  9972. }
  9973. OMPClause *Sema::ActOnOpenMPLinearClause(
  9974. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  9975. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  9976. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  9977. SmallVector<Expr *, 8> Vars;
  9978. SmallVector<Expr *, 8> Privates;
  9979. SmallVector<Expr *, 8> Inits;
  9980. SmallVector<Decl *, 4> ExprCaptures;
  9981. SmallVector<Expr *, 4> ExprPostUpdates;
  9982. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  9983. LinKind = OMPC_LINEAR_val;
  9984. for (auto &RefExpr : VarList) {
  9985. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  9986. SourceLocation ELoc;
  9987. SourceRange ERange;
  9988. Expr *SimpleRefExpr = RefExpr;
  9989. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  9990. /*AllowArraySection=*/false);
  9991. if (Res.second) {
  9992. // It will be analyzed later.
  9993. Vars.push_back(RefExpr);
  9994. Privates.push_back(nullptr);
  9995. Inits.push_back(nullptr);
  9996. }
  9997. ValueDecl *D = Res.first;
  9998. if (!D)
  9999. continue;
  10000. QualType Type = D->getType();
  10001. auto *VD = dyn_cast<VarDecl>(D);
  10002. // OpenMP [2.14.3.7, linear clause]
  10003. // A list-item cannot appear in more than one linear clause.
  10004. // A list-item that appears in a linear clause cannot appear in any
  10005. // other data-sharing attribute clause.
  10006. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  10007. if (DVar.RefExpr) {
  10008. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10009. << getOpenMPClauseName(OMPC_linear);
  10010. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10011. continue;
  10012. }
  10013. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  10014. continue;
  10015. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10016. // Build private copy of original var.
  10017. auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
  10018. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10019. auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  10020. // Build var to save initial value.
  10021. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  10022. Expr *InitExpr;
  10023. DeclRefExpr *Ref = nullptr;
  10024. if (!VD && !CurContext->isDependentContext()) {
  10025. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10026. if (!IsOpenMPCapturedDecl(D)) {
  10027. ExprCaptures.push_back(Ref->getDecl());
  10028. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10029. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10030. if (!RefRes.isUsable())
  10031. continue;
  10032. ExprResult PostUpdateRes =
  10033. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10034. SimpleRefExpr, RefRes.get());
  10035. if (!PostUpdateRes.isUsable())
  10036. continue;
  10037. ExprPostUpdates.push_back(
  10038. IgnoredValueConversions(PostUpdateRes.get()).get());
  10039. }
  10040. }
  10041. }
  10042. if (LinKind == OMPC_LINEAR_uval)
  10043. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  10044. else
  10045. InitExpr = VD ? SimpleRefExpr : Ref;
  10046. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  10047. /*DirectInit=*/false);
  10048. auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  10049. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  10050. Vars.push_back((VD || CurContext->isDependentContext())
  10051. ? RefExpr->IgnoreParens()
  10052. : Ref);
  10053. Privates.push_back(PrivateRef);
  10054. Inits.push_back(InitRef);
  10055. }
  10056. if (Vars.empty())
  10057. return nullptr;
  10058. Expr *StepExpr = Step;
  10059. Expr *CalcStepExpr = nullptr;
  10060. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  10061. !Step->isInstantiationDependent() &&
  10062. !Step->containsUnexpandedParameterPack()) {
  10063. SourceLocation StepLoc = Step->getLocStart();
  10064. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  10065. if (Val.isInvalid())
  10066. return nullptr;
  10067. StepExpr = Val.get();
  10068. // Build var to save the step value.
  10069. VarDecl *SaveVar =
  10070. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  10071. ExprResult SaveRef =
  10072. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  10073. ExprResult CalcStep =
  10074. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  10075. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  10076. // Warn about zero linear step (it would be probably better specified as
  10077. // making corresponding variables 'const').
  10078. llvm::APSInt Result;
  10079. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  10080. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  10081. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  10082. << (Vars.size() > 1);
  10083. if (!IsConstant && CalcStep.isUsable()) {
  10084. // Calculate the step beforehand instead of doing this on each iteration.
  10085. // (This is not used if the number of iterations may be kfold-ed).
  10086. CalcStepExpr = CalcStep.get();
  10087. }
  10088. }
  10089. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  10090. ColonLoc, EndLoc, Vars, Privates, Inits,
  10091. StepExpr, CalcStepExpr,
  10092. buildPreInits(Context, ExprCaptures),
  10093. buildPostUpdate(*this, ExprPostUpdates));
  10094. }
  10095. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  10096. Expr *NumIterations, Sema &SemaRef,
  10097. Scope *S, DSAStackTy *Stack) {
  10098. // Walk the vars and build update/final expressions for the CodeGen.
  10099. SmallVector<Expr *, 8> Updates;
  10100. SmallVector<Expr *, 8> Finals;
  10101. Expr *Step = Clause.getStep();
  10102. Expr *CalcStep = Clause.getCalcStep();
  10103. // OpenMP [2.14.3.7, linear clause]
  10104. // If linear-step is not specified it is assumed to be 1.
  10105. if (Step == nullptr)
  10106. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  10107. else if (CalcStep) {
  10108. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  10109. }
  10110. bool HasErrors = false;
  10111. auto CurInit = Clause.inits().begin();
  10112. auto CurPrivate = Clause.privates().begin();
  10113. auto LinKind = Clause.getModifier();
  10114. for (auto &RefExpr : Clause.varlists()) {
  10115. SourceLocation ELoc;
  10116. SourceRange ERange;
  10117. Expr *SimpleRefExpr = RefExpr;
  10118. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
  10119. /*AllowArraySection=*/false);
  10120. ValueDecl *D = Res.first;
  10121. if (Res.second || !D) {
  10122. Updates.push_back(nullptr);
  10123. Finals.push_back(nullptr);
  10124. HasErrors = true;
  10125. continue;
  10126. }
  10127. auto &&Info = Stack->isLoopControlVariable(D);
  10128. // OpenMP [2.15.11, distribute simd Construct]
  10129. // A list item may not appear in a linear clause, unless it is the loop
  10130. // iteration variable.
  10131. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  10132. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  10133. SemaRef.Diag(ELoc,
  10134. diag::err_omp_linear_distribute_var_non_loop_iteration);
  10135. Updates.push_back(nullptr);
  10136. Finals.push_back(nullptr);
  10137. HasErrors = true;
  10138. continue;
  10139. }
  10140. Expr *InitExpr = *CurInit;
  10141. // Build privatized reference to the current linear var.
  10142. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  10143. Expr *CapturedRef;
  10144. if (LinKind == OMPC_LINEAR_uval)
  10145. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  10146. else
  10147. CapturedRef =
  10148. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  10149. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  10150. /*RefersToCapture=*/true);
  10151. // Build update: Var = InitExpr + IV * Step
  10152. ExprResult Update;
  10153. if (!Info.first) {
  10154. Update =
  10155. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  10156. InitExpr, IV, Step, /* Subtract */ false);
  10157. } else
  10158. Update = *CurPrivate;
  10159. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
  10160. /*DiscardedValue=*/true);
  10161. // Build final: Var = InitExpr + NumIterations * Step
  10162. ExprResult Final;
  10163. if (!Info.first) {
  10164. Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  10165. InitExpr, NumIterations, Step,
  10166. /* Subtract */ false);
  10167. } else
  10168. Final = *CurPrivate;
  10169. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
  10170. /*DiscardedValue=*/true);
  10171. if (!Update.isUsable() || !Final.isUsable()) {
  10172. Updates.push_back(nullptr);
  10173. Finals.push_back(nullptr);
  10174. HasErrors = true;
  10175. } else {
  10176. Updates.push_back(Update.get());
  10177. Finals.push_back(Final.get());
  10178. }
  10179. ++CurInit;
  10180. ++CurPrivate;
  10181. }
  10182. Clause.setUpdates(Updates);
  10183. Clause.setFinals(Finals);
  10184. return HasErrors;
  10185. }
  10186. OMPClause *Sema::ActOnOpenMPAlignedClause(
  10187. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  10188. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10189. SmallVector<Expr *, 8> Vars;
  10190. for (auto &RefExpr : VarList) {
  10191. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10192. SourceLocation ELoc;
  10193. SourceRange ERange;
  10194. Expr *SimpleRefExpr = RefExpr;
  10195. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10196. /*AllowArraySection=*/false);
  10197. if (Res.second) {
  10198. // It will be analyzed later.
  10199. Vars.push_back(RefExpr);
  10200. }
  10201. ValueDecl *D = Res.first;
  10202. if (!D)
  10203. continue;
  10204. QualType QType = D->getType();
  10205. auto *VD = dyn_cast<VarDecl>(D);
  10206. // OpenMP [2.8.1, simd construct, Restrictions]
  10207. // The type of list items appearing in the aligned clause must be
  10208. // array, pointer, reference to array, or reference to pointer.
  10209. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10210. const Type *Ty = QType.getTypePtrOrNull();
  10211. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  10212. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  10213. << QType << getLangOpts().CPlusPlus << ERange;
  10214. bool IsDecl =
  10215. !VD ||
  10216. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10217. Diag(D->getLocation(),
  10218. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10219. << D;
  10220. continue;
  10221. }
  10222. // OpenMP [2.8.1, simd construct, Restrictions]
  10223. // A list-item cannot appear in more than one aligned clause.
  10224. if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  10225. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  10226. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  10227. << getOpenMPClauseName(OMPC_aligned);
  10228. continue;
  10229. }
  10230. DeclRefExpr *Ref = nullptr;
  10231. if (!VD && IsOpenMPCapturedDecl(D))
  10232. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10233. Vars.push_back(DefaultFunctionArrayConversion(
  10234. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  10235. .get());
  10236. }
  10237. // OpenMP [2.8.1, simd construct, Description]
  10238. // The parameter of the aligned clause, alignment, must be a constant
  10239. // positive integer expression.
  10240. // If no optional parameter is specified, implementation-defined default
  10241. // alignments for SIMD instructions on the target platforms are assumed.
  10242. if (Alignment != nullptr) {
  10243. ExprResult AlignResult =
  10244. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  10245. if (AlignResult.isInvalid())
  10246. return nullptr;
  10247. Alignment = AlignResult.get();
  10248. }
  10249. if (Vars.empty())
  10250. return nullptr;
  10251. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  10252. EndLoc, Vars, Alignment);
  10253. }
  10254. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  10255. SourceLocation StartLoc,
  10256. SourceLocation LParenLoc,
  10257. SourceLocation EndLoc) {
  10258. SmallVector<Expr *, 8> Vars;
  10259. SmallVector<Expr *, 8> SrcExprs;
  10260. SmallVector<Expr *, 8> DstExprs;
  10261. SmallVector<Expr *, 8> AssignmentOps;
  10262. for (auto &RefExpr : VarList) {
  10263. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  10264. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10265. // It will be analyzed later.
  10266. Vars.push_back(RefExpr);
  10267. SrcExprs.push_back(nullptr);
  10268. DstExprs.push_back(nullptr);
  10269. AssignmentOps.push_back(nullptr);
  10270. continue;
  10271. }
  10272. SourceLocation ELoc = RefExpr->getExprLoc();
  10273. // OpenMP [2.1, C/C++]
  10274. // A list item is a variable name.
  10275. // OpenMP [2.14.4.1, Restrictions, p.1]
  10276. // A list item that appears in a copyin clause must be threadprivate.
  10277. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  10278. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  10279. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  10280. << 0 << RefExpr->getSourceRange();
  10281. continue;
  10282. }
  10283. Decl *D = DE->getDecl();
  10284. VarDecl *VD = cast<VarDecl>(D);
  10285. QualType Type = VD->getType();
  10286. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  10287. // It will be analyzed later.
  10288. Vars.push_back(DE);
  10289. SrcExprs.push_back(nullptr);
  10290. DstExprs.push_back(nullptr);
  10291. AssignmentOps.push_back(nullptr);
  10292. continue;
  10293. }
  10294. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  10295. // A list item that appears in a copyin clause must be threadprivate.
  10296. if (!DSAStack->isThreadPrivate(VD)) {
  10297. Diag(ELoc, diag::err_omp_required_access)
  10298. << getOpenMPClauseName(OMPC_copyin)
  10299. << getOpenMPDirectiveName(OMPD_threadprivate);
  10300. continue;
  10301. }
  10302. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10303. // A variable of class type (or array thereof) that appears in a
  10304. // copyin clause requires an accessible, unambiguous copy assignment
  10305. // operator for the class type.
  10306. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  10307. auto *SrcVD =
  10308. buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
  10309. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10310. auto *PseudoSrcExpr = buildDeclRefExpr(
  10311. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  10312. auto *DstVD =
  10313. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
  10314. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10315. auto *PseudoDstExpr =
  10316. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  10317. // For arrays generate assignment operation for single element and replace
  10318. // it by the original array element in CodeGen.
  10319. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  10320. PseudoDstExpr, PseudoSrcExpr);
  10321. if (AssignmentOp.isInvalid())
  10322. continue;
  10323. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  10324. /*DiscardedValue=*/true);
  10325. if (AssignmentOp.isInvalid())
  10326. continue;
  10327. DSAStack->addDSA(VD, DE, OMPC_copyin);
  10328. Vars.push_back(DE);
  10329. SrcExprs.push_back(PseudoSrcExpr);
  10330. DstExprs.push_back(PseudoDstExpr);
  10331. AssignmentOps.push_back(AssignmentOp.get());
  10332. }
  10333. if (Vars.empty())
  10334. return nullptr;
  10335. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  10336. SrcExprs, DstExprs, AssignmentOps);
  10337. }
  10338. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  10339. SourceLocation StartLoc,
  10340. SourceLocation LParenLoc,
  10341. SourceLocation EndLoc) {
  10342. SmallVector<Expr *, 8> Vars;
  10343. SmallVector<Expr *, 8> SrcExprs;
  10344. SmallVector<Expr *, 8> DstExprs;
  10345. SmallVector<Expr *, 8> AssignmentOps;
  10346. for (auto &RefExpr : VarList) {
  10347. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10348. SourceLocation ELoc;
  10349. SourceRange ERange;
  10350. Expr *SimpleRefExpr = RefExpr;
  10351. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10352. /*AllowArraySection=*/false);
  10353. if (Res.second) {
  10354. // It will be analyzed later.
  10355. Vars.push_back(RefExpr);
  10356. SrcExprs.push_back(nullptr);
  10357. DstExprs.push_back(nullptr);
  10358. AssignmentOps.push_back(nullptr);
  10359. }
  10360. ValueDecl *D = Res.first;
  10361. if (!D)
  10362. continue;
  10363. QualType Type = D->getType();
  10364. auto *VD = dyn_cast<VarDecl>(D);
  10365. // OpenMP [2.14.4.2, Restrictions, p.2]
  10366. // A list item that appears in a copyprivate clause may not appear in a
  10367. // private or firstprivate clause on the single construct.
  10368. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  10369. auto DVar = DSAStack->getTopDSA(D, false);
  10370. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  10371. DVar.RefExpr) {
  10372. Diag(ELoc, diag::err_omp_wrong_dsa)
  10373. << getOpenMPClauseName(DVar.CKind)
  10374. << getOpenMPClauseName(OMPC_copyprivate);
  10375. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10376. continue;
  10377. }
  10378. // OpenMP [2.11.4.2, Restrictions, p.1]
  10379. // All list items that appear in a copyprivate clause must be either
  10380. // threadprivate or private in the enclosing context.
  10381. if (DVar.CKind == OMPC_unknown) {
  10382. DVar = DSAStack->getImplicitDSA(D, false);
  10383. if (DVar.CKind == OMPC_shared) {
  10384. Diag(ELoc, diag::err_omp_required_access)
  10385. << getOpenMPClauseName(OMPC_copyprivate)
  10386. << "threadprivate or private in the enclosing context";
  10387. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10388. continue;
  10389. }
  10390. }
  10391. }
  10392. // Variably modified types are not supported.
  10393. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  10394. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10395. << getOpenMPClauseName(OMPC_copyprivate) << Type
  10396. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10397. bool IsDecl =
  10398. !VD ||
  10399. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10400. Diag(D->getLocation(),
  10401. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10402. << D;
  10403. continue;
  10404. }
  10405. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10406. // A variable of class type (or array thereof) that appears in a
  10407. // copyin clause requires an accessible, unambiguous copy assignment
  10408. // operator for the class type.
  10409. Type = Context.getBaseElementType(Type.getNonReferenceType())
  10410. .getUnqualifiedType();
  10411. auto *SrcVD =
  10412. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
  10413. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10414. auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  10415. auto *DstVD =
  10416. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
  10417. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10418. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  10419. auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10420. PseudoDstExpr, PseudoSrcExpr);
  10421. if (AssignmentOp.isInvalid())
  10422. continue;
  10423. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  10424. /*DiscardedValue=*/true);
  10425. if (AssignmentOp.isInvalid())
  10426. continue;
  10427. // No need to mark vars as copyprivate, they are already threadprivate or
  10428. // implicitly private.
  10429. assert(VD || IsOpenMPCapturedDecl(D));
  10430. Vars.push_back(
  10431. VD ? RefExpr->IgnoreParens()
  10432. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  10433. SrcExprs.push_back(PseudoSrcExpr);
  10434. DstExprs.push_back(PseudoDstExpr);
  10435. AssignmentOps.push_back(AssignmentOp.get());
  10436. }
  10437. if (Vars.empty())
  10438. return nullptr;
  10439. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10440. Vars, SrcExprs, DstExprs, AssignmentOps);
  10441. }
  10442. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  10443. SourceLocation StartLoc,
  10444. SourceLocation LParenLoc,
  10445. SourceLocation EndLoc) {
  10446. if (VarList.empty())
  10447. return nullptr;
  10448. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  10449. }
  10450. OMPClause *
  10451. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  10452. SourceLocation DepLoc, SourceLocation ColonLoc,
  10453. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  10454. SourceLocation LParenLoc, SourceLocation EndLoc) {
  10455. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  10456. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  10457. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10458. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  10459. return nullptr;
  10460. }
  10461. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  10462. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  10463. DepKind == OMPC_DEPEND_sink)) {
  10464. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  10465. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10466. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  10467. /*Last=*/OMPC_DEPEND_unknown, Except)
  10468. << getOpenMPClauseName(OMPC_depend);
  10469. return nullptr;
  10470. }
  10471. SmallVector<Expr *, 8> Vars;
  10472. DSAStackTy::OperatorOffsetTy OpsOffs;
  10473. llvm::APSInt DepCounter(/*BitWidth=*/32);
  10474. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  10475. if (DepKind == OMPC_DEPEND_sink) {
  10476. if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
  10477. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  10478. TotalDepCount.setIsUnsigned(/*Val=*/true);
  10479. }
  10480. }
  10481. if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
  10482. DSAStack->getParentOrderedRegionParam()) {
  10483. for (auto &RefExpr : VarList) {
  10484. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  10485. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10486. // It will be analyzed later.
  10487. Vars.push_back(RefExpr);
  10488. continue;
  10489. }
  10490. SourceLocation ELoc = RefExpr->getExprLoc();
  10491. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  10492. if (DepKind == OMPC_DEPEND_sink) {
  10493. if (DepCounter >= TotalDepCount) {
  10494. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  10495. continue;
  10496. }
  10497. ++DepCounter;
  10498. // OpenMP [2.13.9, Summary]
  10499. // depend(dependence-type : vec), where dependence-type is:
  10500. // 'sink' and where vec is the iteration vector, which has the form:
  10501. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  10502. // where n is the value specified by the ordered clause in the loop
  10503. // directive, xi denotes the loop iteration variable of the i-th nested
  10504. // loop associated with the loop directive, and di is a constant
  10505. // non-negative integer.
  10506. if (CurContext->isDependentContext()) {
  10507. // It will be analyzed later.
  10508. Vars.push_back(RefExpr);
  10509. continue;
  10510. }
  10511. SimpleExpr = SimpleExpr->IgnoreImplicit();
  10512. OverloadedOperatorKind OOK = OO_None;
  10513. SourceLocation OOLoc;
  10514. Expr *LHS = SimpleExpr;
  10515. Expr *RHS = nullptr;
  10516. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  10517. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  10518. OOLoc = BO->getOperatorLoc();
  10519. LHS = BO->getLHS()->IgnoreParenImpCasts();
  10520. RHS = BO->getRHS()->IgnoreParenImpCasts();
  10521. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  10522. OOK = OCE->getOperator();
  10523. OOLoc = OCE->getOperatorLoc();
  10524. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10525. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  10526. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  10527. OOK = MCE->getMethodDecl()
  10528. ->getNameInfo()
  10529. .getName()
  10530. .getCXXOverloadedOperator();
  10531. OOLoc = MCE->getCallee()->getExprLoc();
  10532. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  10533. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10534. }
  10535. SourceLocation ELoc;
  10536. SourceRange ERange;
  10537. auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
  10538. /*AllowArraySection=*/false);
  10539. if (Res.second) {
  10540. // It will be analyzed later.
  10541. Vars.push_back(RefExpr);
  10542. }
  10543. ValueDecl *D = Res.first;
  10544. if (!D)
  10545. continue;
  10546. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  10547. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  10548. continue;
  10549. }
  10550. if (RHS) {
  10551. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  10552. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  10553. if (RHSRes.isInvalid())
  10554. continue;
  10555. }
  10556. if (!CurContext->isDependentContext() &&
  10557. DSAStack->getParentOrderedRegionParam() &&
  10558. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  10559. ValueDecl* VD = DSAStack->getParentLoopControlVariable(
  10560. DepCounter.getZExtValue());
  10561. if (VD) {
  10562. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  10563. << 1 << VD;
  10564. } else {
  10565. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  10566. }
  10567. continue;
  10568. }
  10569. OpsOffs.push_back({RHS, OOK});
  10570. } else {
  10571. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  10572. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  10573. (ASE &&
  10574. !ASE->getBase()
  10575. ->getType()
  10576. .getNonReferenceType()
  10577. ->isPointerType() &&
  10578. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  10579. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10580. << RefExpr->getSourceRange();
  10581. continue;
  10582. }
  10583. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  10584. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  10585. ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  10586. RefExpr->IgnoreParenImpCasts());
  10587. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  10588. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  10589. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10590. << RefExpr->getSourceRange();
  10591. continue;
  10592. }
  10593. }
  10594. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  10595. }
  10596. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  10597. TotalDepCount > VarList.size() &&
  10598. DSAStack->getParentOrderedRegionParam() &&
  10599. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  10600. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
  10601. << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  10602. }
  10603. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  10604. Vars.empty())
  10605. return nullptr;
  10606. }
  10607. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10608. DepKind, DepLoc, ColonLoc, Vars);
  10609. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
  10610. DSAStack->addDoacrossDependClause(C, OpsOffs);
  10611. return C;
  10612. }
  10613. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  10614. SourceLocation LParenLoc,
  10615. SourceLocation EndLoc) {
  10616. Expr *ValExpr = Device;
  10617. Stmt *HelperValStmt = nullptr;
  10618. // OpenMP [2.9.1, Restrictions]
  10619. // The device expression must evaluate to a non-negative integer value.
  10620. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  10621. /*StrictlyPositive=*/false))
  10622. return nullptr;
  10623. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10624. OpenMPDirectiveKind CaptureRegion =
  10625. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  10626. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10627. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  10628. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10629. HelperValStmt = buildPreInits(Context, Captures);
  10630. }
  10631. return new (Context)
  10632. OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
  10633. }
  10634. static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  10635. DSAStackTy *Stack, QualType QTy) {
  10636. NamedDecl *ND;
  10637. if (QTy->isIncompleteType(&ND)) {
  10638. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  10639. return false;
  10640. }
  10641. return true;
  10642. }
  10643. /// \brief Return true if it can be proven that the provided array expression
  10644. /// (array section or array subscript) does NOT specify the whole size of the
  10645. /// array whose base type is \a BaseQTy.
  10646. static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  10647. const Expr *E,
  10648. QualType BaseQTy) {
  10649. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10650. // If this is an array subscript, it refers to the whole size if the size of
  10651. // the dimension is constant and equals 1. Also, an array section assumes the
  10652. // format of an array subscript if no colon is used.
  10653. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  10654. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10655. return ATy->getSize().getSExtValue() != 1;
  10656. // Size can't be evaluated statically.
  10657. return false;
  10658. }
  10659. assert(OASE && "Expecting array section if not an array subscript.");
  10660. auto *LowerBound = OASE->getLowerBound();
  10661. auto *Length = OASE->getLength();
  10662. // If there is a lower bound that does not evaluates to zero, we are not
  10663. // covering the whole dimension.
  10664. if (LowerBound) {
  10665. llvm::APSInt ConstLowerBound;
  10666. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  10667. return false; // Can't get the integer value as a constant.
  10668. if (ConstLowerBound.getSExtValue())
  10669. return true;
  10670. }
  10671. // If we don't have a length we covering the whole dimension.
  10672. if (!Length)
  10673. return false;
  10674. // If the base is a pointer, we don't have a way to get the size of the
  10675. // pointee.
  10676. if (BaseQTy->isPointerType())
  10677. return false;
  10678. // We can only check if the length is the same as the size of the dimension
  10679. // if we have a constant array.
  10680. auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  10681. if (!CATy)
  10682. return false;
  10683. llvm::APSInt ConstLength;
  10684. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10685. return false; // Can't get the integer value as a constant.
  10686. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  10687. }
  10688. // Return true if it can be proven that the provided array expression (array
  10689. // section or array subscript) does NOT specify a single element of the array
  10690. // whose base type is \a BaseQTy.
  10691. static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  10692. const Expr *E,
  10693. QualType BaseQTy) {
  10694. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10695. // An array subscript always refer to a single element. Also, an array section
  10696. // assumes the format of an array subscript if no colon is used.
  10697. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  10698. return false;
  10699. assert(OASE && "Expecting array section if not an array subscript.");
  10700. auto *Length = OASE->getLength();
  10701. // If we don't have a length we have to check if the array has unitary size
  10702. // for this dimension. Also, we should always expect a length if the base type
  10703. // is pointer.
  10704. if (!Length) {
  10705. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10706. return ATy->getSize().getSExtValue() != 1;
  10707. // We cannot assume anything.
  10708. return false;
  10709. }
  10710. // Check if the length evaluates to 1.
  10711. llvm::APSInt ConstLength;
  10712. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10713. return false; // Can't get the integer value as a constant.
  10714. return ConstLength.getSExtValue() != 1;
  10715. }
  10716. // Return the expression of the base of the mappable expression or null if it
  10717. // cannot be determined and do all the necessary checks to see if the expression
  10718. // is valid as a standalone mappable expression. In the process, record all the
  10719. // components of the expression.
  10720. static Expr *CheckMapClauseExpressionBase(
  10721. Sema &SemaRef, Expr *E,
  10722. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  10723. OpenMPClauseKind CKind, bool NoDiagnose) {
  10724. SourceLocation ELoc = E->getExprLoc();
  10725. SourceRange ERange = E->getSourceRange();
  10726. // The base of elements of list in a map clause have to be either:
  10727. // - a reference to variable or field.
  10728. // - a member expression.
  10729. // - an array expression.
  10730. //
  10731. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  10732. // reference to 'r'.
  10733. //
  10734. // If we have:
  10735. //
  10736. // struct SS {
  10737. // Bla S;
  10738. // foo() {
  10739. // #pragma omp target map (S.Arr[:12]);
  10740. // }
  10741. // }
  10742. //
  10743. // We want to retrieve the member expression 'this->S';
  10744. Expr *RelevantExpr = nullptr;
  10745. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  10746. // If a list item is an array section, it must specify contiguous storage.
  10747. //
  10748. // For this restriction it is sufficient that we make sure only references
  10749. // to variables or fields and array expressions, and that no array sections
  10750. // exist except in the rightmost expression (unless they cover the whole
  10751. // dimension of the array). E.g. these would be invalid:
  10752. //
  10753. // r.ArrS[3:5].Arr[6:7]
  10754. //
  10755. // r.ArrS[3:5].x
  10756. //
  10757. // but these would be valid:
  10758. // r.ArrS[3].Arr[6:7]
  10759. //
  10760. // r.ArrS[3].x
  10761. bool AllowUnitySizeArraySection = true;
  10762. bool AllowWholeSizeArraySection = true;
  10763. while (!RelevantExpr) {
  10764. E = E->IgnoreParenImpCasts();
  10765. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  10766. if (!isa<VarDecl>(CurE->getDecl()))
  10767. return nullptr;
  10768. RelevantExpr = CurE;
  10769. // If we got a reference to a declaration, we should not expect any array
  10770. // section before that.
  10771. AllowUnitySizeArraySection = false;
  10772. AllowWholeSizeArraySection = false;
  10773. // Record the component.
  10774. CurComponents.emplace_back(CurE, CurE->getDecl());
  10775. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  10776. auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  10777. if (isa<CXXThisExpr>(BaseE))
  10778. // We found a base expression: this->Val.
  10779. RelevantExpr = CurE;
  10780. else
  10781. E = BaseE;
  10782. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  10783. if (!NoDiagnose) {
  10784. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  10785. << CurE->getSourceRange();
  10786. return nullptr;
  10787. }
  10788. if (RelevantExpr)
  10789. return nullptr;
  10790. continue;
  10791. }
  10792. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  10793. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  10794. // A bit-field cannot appear in a map clause.
  10795. //
  10796. if (FD->isBitField()) {
  10797. if (!NoDiagnose) {
  10798. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  10799. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  10800. return nullptr;
  10801. }
  10802. if (RelevantExpr)
  10803. return nullptr;
  10804. continue;
  10805. }
  10806. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10807. // If the type of a list item is a reference to a type T then the type
  10808. // will be considered to be T for all purposes of this clause.
  10809. QualType CurType = BaseE->getType().getNonReferenceType();
  10810. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  10811. // A list item cannot be a variable that is a member of a structure with
  10812. // a union type.
  10813. //
  10814. if (auto *RT = CurType->getAs<RecordType>()) {
  10815. if (RT->isUnionType()) {
  10816. if (!NoDiagnose) {
  10817. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  10818. << CurE->getSourceRange();
  10819. return nullptr;
  10820. }
  10821. continue;
  10822. }
  10823. }
  10824. // If we got a member expression, we should not expect any array section
  10825. // before that:
  10826. //
  10827. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  10828. // If a list item is an element of a structure, only the rightmost symbol
  10829. // of the variable reference can be an array section.
  10830. //
  10831. AllowUnitySizeArraySection = false;
  10832. AllowWholeSizeArraySection = false;
  10833. // Record the component.
  10834. CurComponents.emplace_back(CurE, FD);
  10835. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  10836. E = CurE->getBase()->IgnoreParenImpCasts();
  10837. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  10838. if (!NoDiagnose) {
  10839. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10840. << 0 << CurE->getSourceRange();
  10841. return nullptr;
  10842. }
  10843. continue;
  10844. }
  10845. // If we got an array subscript that express the whole dimension we
  10846. // can have any array expressions before. If it only expressing part of
  10847. // the dimension, we can only have unitary-size array expressions.
  10848. if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  10849. E->getType()))
  10850. AllowWholeSizeArraySection = false;
  10851. // Record the component - we don't have any declaration associated.
  10852. CurComponents.emplace_back(CurE, nullptr);
  10853. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  10854. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  10855. E = CurE->getBase()->IgnoreParenImpCasts();
  10856. QualType CurType =
  10857. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10858. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10859. // If the type of a list item is a reference to a type T then the type
  10860. // will be considered to be T for all purposes of this clause.
  10861. if (CurType->isReferenceType())
  10862. CurType = CurType->getPointeeType();
  10863. bool IsPointer = CurType->isAnyPointerType();
  10864. if (!IsPointer && !CurType->isArrayType()) {
  10865. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10866. << 0 << CurE->getSourceRange();
  10867. return nullptr;
  10868. }
  10869. bool NotWhole =
  10870. CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  10871. bool NotUnity =
  10872. CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  10873. if (AllowWholeSizeArraySection) {
  10874. // Any array section is currently allowed. Allowing a whole size array
  10875. // section implies allowing a unity array section as well.
  10876. //
  10877. // If this array section refers to the whole dimension we can still
  10878. // accept other array sections before this one, except if the base is a
  10879. // pointer. Otherwise, only unitary sections are accepted.
  10880. if (NotWhole || IsPointer)
  10881. AllowWholeSizeArraySection = false;
  10882. } else if (AllowUnitySizeArraySection && NotUnity) {
  10883. // A unity or whole array section is not allowed and that is not
  10884. // compatible with the properties of the current array section.
  10885. SemaRef.Diag(
  10886. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  10887. << CurE->getSourceRange();
  10888. return nullptr;
  10889. }
  10890. // Record the component - we don't have any declaration associated.
  10891. CurComponents.emplace_back(CurE, nullptr);
  10892. } else {
  10893. if (!NoDiagnose) {
  10894. // If nothing else worked, this is not a valid map clause expression.
  10895. SemaRef.Diag(
  10896. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  10897. << ERange;
  10898. }
  10899. return nullptr;
  10900. }
  10901. }
  10902. return RelevantExpr;
  10903. }
  10904. // Return true if expression E associated with value VD has conflicts with other
  10905. // map information.
  10906. static bool CheckMapConflicts(
  10907. Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
  10908. bool CurrentRegionOnly,
  10909. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  10910. OpenMPClauseKind CKind) {
  10911. assert(VD && E);
  10912. SourceLocation ELoc = E->getExprLoc();
  10913. SourceRange ERange = E->getSourceRange();
  10914. // In order to easily check the conflicts we need to match each component of
  10915. // the expression under test with the components of the expressions that are
  10916. // already in the stack.
  10917. assert(!CurComponents.empty() && "Map clause expression with no components!");
  10918. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  10919. "Map clause expression with unexpected base!");
  10920. // Variables to help detecting enclosing problems in data environment nests.
  10921. bool IsEnclosedByDataEnvironmentExpr = false;
  10922. const Expr *EnclosingExpr = nullptr;
  10923. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  10924. VD, CurrentRegionOnly,
  10925. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  10926. StackComponents,
  10927. OpenMPClauseKind) -> bool {
  10928. assert(!StackComponents.empty() &&
  10929. "Map clause expression with no components!");
  10930. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  10931. "Map clause expression with unexpected base!");
  10932. // The whole expression in the stack.
  10933. auto *RE = StackComponents.front().getAssociatedExpression();
  10934. // Expressions must start from the same base. Here we detect at which
  10935. // point both expressions diverge from each other and see if we can
  10936. // detect if the memory referred to both expressions is contiguous and
  10937. // do not overlap.
  10938. auto CI = CurComponents.rbegin();
  10939. auto CE = CurComponents.rend();
  10940. auto SI = StackComponents.rbegin();
  10941. auto SE = StackComponents.rend();
  10942. for (; CI != CE && SI != SE; ++CI, ++SI) {
  10943. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  10944. // At most one list item can be an array item derived from a given
  10945. // variable in map clauses of the same construct.
  10946. if (CurrentRegionOnly &&
  10947. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  10948. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  10949. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  10950. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  10951. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  10952. diag::err_omp_multiple_array_items_in_map_clause)
  10953. << CI->getAssociatedExpression()->getSourceRange();
  10954. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  10955. diag::note_used_here)
  10956. << SI->getAssociatedExpression()->getSourceRange();
  10957. return true;
  10958. }
  10959. // Do both expressions have the same kind?
  10960. if (CI->getAssociatedExpression()->getStmtClass() !=
  10961. SI->getAssociatedExpression()->getStmtClass())
  10962. break;
  10963. // Are we dealing with different variables/fields?
  10964. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  10965. break;
  10966. }
  10967. // Check if the extra components of the expressions in the enclosing
  10968. // data environment are redundant for the current base declaration.
  10969. // If they are, the maps completely overlap, which is legal.
  10970. for (; SI != SE; ++SI) {
  10971. QualType Type;
  10972. if (auto *ASE =
  10973. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  10974. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  10975. } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
  10976. SI->getAssociatedExpression())) {
  10977. auto *E = OASE->getBase()->IgnoreParenImpCasts();
  10978. Type =
  10979. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10980. }
  10981. if (Type.isNull() || Type->isAnyPointerType() ||
  10982. CheckArrayExpressionDoesNotReferToWholeSize(
  10983. SemaRef, SI->getAssociatedExpression(), Type))
  10984. break;
  10985. }
  10986. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  10987. // List items of map clauses in the same construct must not share
  10988. // original storage.
  10989. //
  10990. // If the expressions are exactly the same or one is a subset of the
  10991. // other, it means they are sharing storage.
  10992. if (CI == CE && SI == SE) {
  10993. if (CurrentRegionOnly) {
  10994. if (CKind == OMPC_map)
  10995. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  10996. else {
  10997. assert(CKind == OMPC_to || CKind == OMPC_from);
  10998. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  10999. << ERange;
  11000. }
  11001. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11002. << RE->getSourceRange();
  11003. return true;
  11004. } else {
  11005. // If we find the same expression in the enclosing data environment,
  11006. // that is legal.
  11007. IsEnclosedByDataEnvironmentExpr = true;
  11008. return false;
  11009. }
  11010. }
  11011. QualType DerivedType =
  11012. std::prev(CI)->getAssociatedDeclaration()->getType();
  11013. SourceLocation DerivedLoc =
  11014. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  11015. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11016. // If the type of a list item is a reference to a type T then the type
  11017. // will be considered to be T for all purposes of this clause.
  11018. DerivedType = DerivedType.getNonReferenceType();
  11019. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  11020. // A variable for which the type is pointer and an array section
  11021. // derived from that variable must not appear as list items of map
  11022. // clauses of the same construct.
  11023. //
  11024. // Also, cover one of the cases in:
  11025. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11026. // If any part of the original storage of a list item has corresponding
  11027. // storage in the device data environment, all of the original storage
  11028. // must have corresponding storage in the device data environment.
  11029. //
  11030. if (DerivedType->isAnyPointerType()) {
  11031. if (CI == CE || SI == SE) {
  11032. SemaRef.Diag(
  11033. DerivedLoc,
  11034. diag::err_omp_pointer_mapped_along_with_derived_section)
  11035. << DerivedLoc;
  11036. } else {
  11037. assert(CI != CE && SI != SE);
  11038. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
  11039. << DerivedLoc;
  11040. }
  11041. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11042. << RE->getSourceRange();
  11043. return true;
  11044. }
  11045. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11046. // List items of map clauses in the same construct must not share
  11047. // original storage.
  11048. //
  11049. // An expression is a subset of the other.
  11050. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  11051. if (CKind == OMPC_map)
  11052. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11053. else {
  11054. assert(CKind == OMPC_to || CKind == OMPC_from);
  11055. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11056. << ERange;
  11057. }
  11058. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11059. << RE->getSourceRange();
  11060. return true;
  11061. }
  11062. // The current expression uses the same base as other expression in the
  11063. // data environment but does not contain it completely.
  11064. if (!CurrentRegionOnly && SI != SE)
  11065. EnclosingExpr = RE;
  11066. // The current expression is a subset of the expression in the data
  11067. // environment.
  11068. IsEnclosedByDataEnvironmentExpr |=
  11069. (!CurrentRegionOnly && CI != CE && SI == SE);
  11070. return false;
  11071. });
  11072. if (CurrentRegionOnly)
  11073. return FoundError;
  11074. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11075. // If any part of the original storage of a list item has corresponding
  11076. // storage in the device data environment, all of the original storage must
  11077. // have corresponding storage in the device data environment.
  11078. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  11079. // If a list item is an element of a structure, and a different element of
  11080. // the structure has a corresponding list item in the device data environment
  11081. // prior to a task encountering the construct associated with the map clause,
  11082. // then the list item must also have a corresponding list item in the device
  11083. // data environment prior to the task encountering the construct.
  11084. //
  11085. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  11086. SemaRef.Diag(ELoc,
  11087. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  11088. << ERange;
  11089. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  11090. << EnclosingExpr->getSourceRange();
  11091. return true;
  11092. }
  11093. return FoundError;
  11094. }
  11095. namespace {
  11096. // Utility struct that gathers all the related lists associated with a mappable
  11097. // expression.
  11098. struct MappableVarListInfo final {
  11099. // The list of expressions.
  11100. ArrayRef<Expr *> VarList;
  11101. // The list of processed expressions.
  11102. SmallVector<Expr *, 16> ProcessedVarList;
  11103. // The mappble components for each expression.
  11104. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  11105. // The base declaration of the variable.
  11106. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  11107. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  11108. // We have a list of components and base declarations for each entry in the
  11109. // variable list.
  11110. VarComponents.reserve(VarList.size());
  11111. VarBaseDeclarations.reserve(VarList.size());
  11112. }
  11113. };
  11114. }
  11115. // Check the validity of the provided variable list for the provided clause kind
  11116. // \a CKind. In the check process the valid expressions, and mappable expression
  11117. // components and variables are extracted and used to fill \a Vars,
  11118. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  11119. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  11120. static void
  11121. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  11122. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  11123. SourceLocation StartLoc,
  11124. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  11125. bool IsMapTypeImplicit = false) {
  11126. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  11127. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  11128. "Unexpected clause kind with mappable expressions!");
  11129. // Keep track of the mappable components and base declarations in this clause.
  11130. // Each entry in the list is going to have a list of components associated. We
  11131. // record each set of the components so that we can build the clause later on.
  11132. // In the end we should have the same amount of declarations and component
  11133. // lists.
  11134. for (auto &RE : MVLI.VarList) {
  11135. assert(RE && "Null expr in omp to/from/map clause");
  11136. SourceLocation ELoc = RE->getExprLoc();
  11137. auto *VE = RE->IgnoreParenLValueCasts();
  11138. if (VE->isValueDependent() || VE->isTypeDependent() ||
  11139. VE->isInstantiationDependent() ||
  11140. VE->containsUnexpandedParameterPack()) {
  11141. // We can only analyze this information once the missing information is
  11142. // resolved.
  11143. MVLI.ProcessedVarList.push_back(RE);
  11144. continue;
  11145. }
  11146. auto *SimpleExpr = RE->IgnoreParenCasts();
  11147. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  11148. SemaRef.Diag(ELoc,
  11149. diag::err_omp_expected_named_var_member_or_array_expression)
  11150. << RE->getSourceRange();
  11151. continue;
  11152. }
  11153. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  11154. ValueDecl *CurDeclaration = nullptr;
  11155. // Obtain the array or member expression bases if required. Also, fill the
  11156. // components array with all the components identified in the process.
  11157. auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
  11158. CKind, /*NoDiagnose=*/false);
  11159. if (!BE)
  11160. continue;
  11161. assert(!CurComponents.empty() &&
  11162. "Invalid mappable expression information.");
  11163. // For the following checks, we rely on the base declaration which is
  11164. // expected to be associated with the last component. The declaration is
  11165. // expected to be a variable or a field (if 'this' is being mapped).
  11166. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  11167. assert(CurDeclaration && "Null decl on map clause.");
  11168. assert(
  11169. CurDeclaration->isCanonicalDecl() &&
  11170. "Expecting components to have associated only canonical declarations.");
  11171. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  11172. auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  11173. assert((VD || FD) && "Only variables or fields are expected here!");
  11174. (void)FD;
  11175. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  11176. // threadprivate variables cannot appear in a map clause.
  11177. // OpenMP 4.5 [2.10.5, target update Construct]
  11178. // threadprivate variables cannot appear in a from clause.
  11179. if (VD && DSAS->isThreadPrivate(VD)) {
  11180. auto DVar = DSAS->getTopDSA(VD, false);
  11181. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  11182. << getOpenMPClauseName(CKind);
  11183. ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
  11184. continue;
  11185. }
  11186. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11187. // A list item cannot appear in both a map clause and a data-sharing
  11188. // attribute clause on the same construct.
  11189. // Check conflicts with other map clause expressions. We check the conflicts
  11190. // with the current construct separately from the enclosing data
  11191. // environment, because the restrictions are different. We only have to
  11192. // check conflicts across regions for the map clauses.
  11193. if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11194. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  11195. break;
  11196. if (CKind == OMPC_map &&
  11197. CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11198. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  11199. break;
  11200. // OpenMP 4.5 [2.10.5, target update Construct]
  11201. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11202. // If the type of a list item is a reference to a type T then the type will
  11203. // be considered to be T for all purposes of this clause.
  11204. QualType Type = CurDeclaration->getType().getNonReferenceType();
  11205. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  11206. // A list item in a to or from clause must have a mappable type.
  11207. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11208. // A list item must have a mappable type.
  11209. if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  11210. DSAS, Type))
  11211. continue;
  11212. if (CKind == OMPC_map) {
  11213. // target enter data
  11214. // OpenMP [2.10.2, Restrictions, p. 99]
  11215. // A map-type must be specified in all map clauses and must be either
  11216. // to or alloc.
  11217. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  11218. if (DKind == OMPD_target_enter_data &&
  11219. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  11220. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11221. << (IsMapTypeImplicit ? 1 : 0)
  11222. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11223. << getOpenMPDirectiveName(DKind);
  11224. continue;
  11225. }
  11226. // target exit_data
  11227. // OpenMP [2.10.3, Restrictions, p. 102]
  11228. // A map-type must be specified in all map clauses and must be either
  11229. // from, release, or delete.
  11230. if (DKind == OMPD_target_exit_data &&
  11231. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  11232. MapType == OMPC_MAP_delete)) {
  11233. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11234. << (IsMapTypeImplicit ? 1 : 0)
  11235. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11236. << getOpenMPDirectiveName(DKind);
  11237. continue;
  11238. }
  11239. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11240. // A list item cannot appear in both a map clause and a data-sharing
  11241. // attribute clause on the same construct
  11242. if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
  11243. DKind == OMPD_target_teams_distribute ||
  11244. DKind == OMPD_target_teams_distribute_parallel_for ||
  11245. DKind == OMPD_target_teams_distribute_parallel_for_simd ||
  11246. DKind == OMPD_target_teams_distribute_simd) && VD) {
  11247. auto DVar = DSAS->getTopDSA(VD, false);
  11248. if (isOpenMPPrivate(DVar.CKind)) {
  11249. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11250. << getOpenMPClauseName(DVar.CKind)
  11251. << getOpenMPClauseName(OMPC_map)
  11252. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  11253. ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
  11254. continue;
  11255. }
  11256. }
  11257. }
  11258. // Save the current expression.
  11259. MVLI.ProcessedVarList.push_back(RE);
  11260. // Store the components in the stack so that they can be used to check
  11261. // against other clauses later on.
  11262. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  11263. /*WhereFoundClauseKind=*/OMPC_map);
  11264. // Save the components and declaration to create the clause. For purposes of
  11265. // the clause creation, any component list that has has base 'this' uses
  11266. // null as base declaration.
  11267. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11268. MVLI.VarComponents.back().append(CurComponents.begin(),
  11269. CurComponents.end());
  11270. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  11271. : CurDeclaration);
  11272. }
  11273. }
  11274. OMPClause *
  11275. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  11276. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  11277. SourceLocation MapLoc, SourceLocation ColonLoc,
  11278. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11279. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11280. MappableVarListInfo MVLI(VarList);
  11281. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  11282. MapType, IsMapTypeImplicit);
  11283. // We need to produce a map clause even if we don't have variables so that
  11284. // other diagnostics related with non-existing map clauses are accurate.
  11285. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11286. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11287. MVLI.VarComponents, MapTypeModifier, MapType,
  11288. IsMapTypeImplicit, MapLoc);
  11289. }
  11290. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  11291. TypeResult ParsedType) {
  11292. assert(ParsedType.isUsable());
  11293. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  11294. if (ReductionType.isNull())
  11295. return QualType();
  11296. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  11297. // A type name in a declare reduction directive cannot be a function type, an
  11298. // array type, a reference type, or a type qualified with const, volatile or
  11299. // restrict.
  11300. if (ReductionType.hasQualifiers()) {
  11301. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  11302. return QualType();
  11303. }
  11304. if (ReductionType->isFunctionType()) {
  11305. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  11306. return QualType();
  11307. }
  11308. if (ReductionType->isReferenceType()) {
  11309. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  11310. return QualType();
  11311. }
  11312. if (ReductionType->isArrayType()) {
  11313. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  11314. return QualType();
  11315. }
  11316. return ReductionType;
  11317. }
  11318. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  11319. Scope *S, DeclContext *DC, DeclarationName Name,
  11320. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  11321. AccessSpecifier AS, Decl *PrevDeclInScope) {
  11322. SmallVector<Decl *, 8> Decls;
  11323. Decls.reserve(ReductionTypes.size());
  11324. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  11325. forRedeclarationInCurContext());
  11326. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  11327. // A reduction-identifier may not be re-declared in the current scope for the
  11328. // same type or for a type that is compatible according to the base language
  11329. // rules.
  11330. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  11331. OMPDeclareReductionDecl *PrevDRD = nullptr;
  11332. bool InCompoundScope = true;
  11333. if (S != nullptr) {
  11334. // Find previous declaration with the same name not referenced in other
  11335. // declarations.
  11336. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  11337. InCompoundScope =
  11338. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  11339. LookupName(Lookup, S);
  11340. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  11341. /*AllowInlineNamespace=*/false);
  11342. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  11343. auto Filter = Lookup.makeFilter();
  11344. while (Filter.hasNext()) {
  11345. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  11346. if (InCompoundScope) {
  11347. auto I = UsedAsPrevious.find(PrevDecl);
  11348. if (I == UsedAsPrevious.end())
  11349. UsedAsPrevious[PrevDecl] = false;
  11350. if (auto *D = PrevDecl->getPrevDeclInScope())
  11351. UsedAsPrevious[D] = true;
  11352. }
  11353. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  11354. PrevDecl->getLocation();
  11355. }
  11356. Filter.done();
  11357. if (InCompoundScope) {
  11358. for (auto &PrevData : UsedAsPrevious) {
  11359. if (!PrevData.second) {
  11360. PrevDRD = PrevData.first;
  11361. break;
  11362. }
  11363. }
  11364. }
  11365. } else if (PrevDeclInScope != nullptr) {
  11366. auto *PrevDRDInScope = PrevDRD =
  11367. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  11368. do {
  11369. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  11370. PrevDRDInScope->getLocation();
  11371. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  11372. } while (PrevDRDInScope != nullptr);
  11373. }
  11374. for (auto &TyData : ReductionTypes) {
  11375. auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  11376. bool Invalid = false;
  11377. if (I != PreviousRedeclTypes.end()) {
  11378. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  11379. << TyData.first;
  11380. Diag(I->second, diag::note_previous_definition);
  11381. Invalid = true;
  11382. }
  11383. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  11384. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  11385. Name, TyData.first, PrevDRD);
  11386. DC->addDecl(DRD);
  11387. DRD->setAccess(AS);
  11388. Decls.push_back(DRD);
  11389. if (Invalid)
  11390. DRD->setInvalidDecl();
  11391. else
  11392. PrevDRD = DRD;
  11393. }
  11394. return DeclGroupPtrTy::make(
  11395. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  11396. }
  11397. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  11398. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11399. // Enter new function scope.
  11400. PushFunctionScope();
  11401. getCurFunction()->setHasBranchProtectedScope();
  11402. getCurFunction()->setHasOMPDeclareReductionCombiner();
  11403. if (S != nullptr)
  11404. PushDeclContext(S, DRD);
  11405. else
  11406. CurContext = DRD;
  11407. PushExpressionEvaluationContext(
  11408. ExpressionEvaluationContext::PotentiallyEvaluated);
  11409. QualType ReductionType = DRD->getType();
  11410. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  11411. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  11412. // uses semantics of argument handles by value, but it should be passed by
  11413. // reference. C lang does not support references, so pass all parameters as
  11414. // pointers.
  11415. // Create 'T omp_in;' variable.
  11416. auto *OmpInParm =
  11417. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  11418. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  11419. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  11420. // uses semantics of argument handles by value, but it should be passed by
  11421. // reference. C lang does not support references, so pass all parameters as
  11422. // pointers.
  11423. // Create 'T omp_out;' variable.
  11424. auto *OmpOutParm =
  11425. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  11426. if (S != nullptr) {
  11427. PushOnScopeChains(OmpInParm, S);
  11428. PushOnScopeChains(OmpOutParm, S);
  11429. } else {
  11430. DRD->addDecl(OmpInParm);
  11431. DRD->addDecl(OmpOutParm);
  11432. }
  11433. }
  11434. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  11435. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11436. DiscardCleanupsInEvaluationContext();
  11437. PopExpressionEvaluationContext();
  11438. PopDeclContext();
  11439. PopFunctionScopeInfo();
  11440. if (Combiner != nullptr)
  11441. DRD->setCombiner(Combiner);
  11442. else
  11443. DRD->setInvalidDecl();
  11444. }
  11445. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  11446. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11447. // Enter new function scope.
  11448. PushFunctionScope();
  11449. getCurFunction()->setHasBranchProtectedScope();
  11450. if (S != nullptr)
  11451. PushDeclContext(S, DRD);
  11452. else
  11453. CurContext = DRD;
  11454. PushExpressionEvaluationContext(
  11455. ExpressionEvaluationContext::PotentiallyEvaluated);
  11456. QualType ReductionType = DRD->getType();
  11457. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  11458. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  11459. // uses semantics of argument handles by value, but it should be passed by
  11460. // reference. C lang does not support references, so pass all parameters as
  11461. // pointers.
  11462. // Create 'T omp_priv;' variable.
  11463. auto *OmpPrivParm =
  11464. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  11465. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  11466. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  11467. // uses semantics of argument handles by value, but it should be passed by
  11468. // reference. C lang does not support references, so pass all parameters as
  11469. // pointers.
  11470. // Create 'T omp_orig;' variable.
  11471. auto *OmpOrigParm =
  11472. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  11473. if (S != nullptr) {
  11474. PushOnScopeChains(OmpPrivParm, S);
  11475. PushOnScopeChains(OmpOrigParm, S);
  11476. } else {
  11477. DRD->addDecl(OmpPrivParm);
  11478. DRD->addDecl(OmpOrigParm);
  11479. }
  11480. return OmpPrivParm;
  11481. }
  11482. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  11483. VarDecl *OmpPrivParm) {
  11484. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11485. DiscardCleanupsInEvaluationContext();
  11486. PopExpressionEvaluationContext();
  11487. PopDeclContext();
  11488. PopFunctionScopeInfo();
  11489. if (Initializer != nullptr) {
  11490. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  11491. } else if (OmpPrivParm->hasInit()) {
  11492. DRD->setInitializer(OmpPrivParm->getInit(),
  11493. OmpPrivParm->isDirectInit()
  11494. ? OMPDeclareReductionDecl::DirectInit
  11495. : OMPDeclareReductionDecl::CopyInit);
  11496. } else {
  11497. DRD->setInvalidDecl();
  11498. }
  11499. }
  11500. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  11501. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  11502. for (auto *D : DeclReductions.get()) {
  11503. if (IsValid) {
  11504. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11505. if (S != nullptr)
  11506. PushOnScopeChains(DRD, S, /*AddToContext=*/false);
  11507. } else
  11508. D->setInvalidDecl();
  11509. }
  11510. return DeclReductions;
  11511. }
  11512. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  11513. SourceLocation StartLoc,
  11514. SourceLocation LParenLoc,
  11515. SourceLocation EndLoc) {
  11516. Expr *ValExpr = NumTeams;
  11517. Stmt *HelperValStmt = nullptr;
  11518. // OpenMP [teams Constrcut, Restrictions]
  11519. // The num_teams expression must evaluate to a positive integer value.
  11520. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  11521. /*StrictlyPositive=*/true))
  11522. return nullptr;
  11523. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11524. OpenMPDirectiveKind CaptureRegion =
  11525. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  11526. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11527. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11528. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11529. HelperValStmt = buildPreInits(Context, Captures);
  11530. }
  11531. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  11532. StartLoc, LParenLoc, EndLoc);
  11533. }
  11534. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  11535. SourceLocation StartLoc,
  11536. SourceLocation LParenLoc,
  11537. SourceLocation EndLoc) {
  11538. Expr *ValExpr = ThreadLimit;
  11539. Stmt *HelperValStmt = nullptr;
  11540. // OpenMP [teams Constrcut, Restrictions]
  11541. // The thread_limit expression must evaluate to a positive integer value.
  11542. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  11543. /*StrictlyPositive=*/true))
  11544. return nullptr;
  11545. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11546. OpenMPDirectiveKind CaptureRegion =
  11547. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  11548. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11549. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11550. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11551. HelperValStmt = buildPreInits(Context, Captures);
  11552. }
  11553. return new (Context) OMPThreadLimitClause(
  11554. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  11555. }
  11556. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  11557. SourceLocation StartLoc,
  11558. SourceLocation LParenLoc,
  11559. SourceLocation EndLoc) {
  11560. Expr *ValExpr = Priority;
  11561. // OpenMP [2.9.1, task Constrcut]
  11562. // The priority-value is a non-negative numerical scalar expression.
  11563. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  11564. /*StrictlyPositive=*/false))
  11565. return nullptr;
  11566. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11567. }
  11568. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  11569. SourceLocation StartLoc,
  11570. SourceLocation LParenLoc,
  11571. SourceLocation EndLoc) {
  11572. Expr *ValExpr = Grainsize;
  11573. // OpenMP [2.9.2, taskloop Constrcut]
  11574. // The parameter of the grainsize clause must be a positive integer
  11575. // expression.
  11576. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  11577. /*StrictlyPositive=*/true))
  11578. return nullptr;
  11579. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11580. }
  11581. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  11582. SourceLocation StartLoc,
  11583. SourceLocation LParenLoc,
  11584. SourceLocation EndLoc) {
  11585. Expr *ValExpr = NumTasks;
  11586. // OpenMP [2.9.2, taskloop Constrcut]
  11587. // The parameter of the num_tasks clause must be a positive integer
  11588. // expression.
  11589. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  11590. /*StrictlyPositive=*/true))
  11591. return nullptr;
  11592. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11593. }
  11594. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  11595. SourceLocation LParenLoc,
  11596. SourceLocation EndLoc) {
  11597. // OpenMP [2.13.2, critical construct, Description]
  11598. // ... where hint-expression is an integer constant expression that evaluates
  11599. // to a valid lock hint.
  11600. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  11601. if (HintExpr.isInvalid())
  11602. return nullptr;
  11603. return new (Context)
  11604. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  11605. }
  11606. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  11607. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  11608. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  11609. SourceLocation EndLoc) {
  11610. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  11611. std::string Values;
  11612. Values += "'";
  11613. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  11614. Values += "'";
  11615. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  11616. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  11617. return nullptr;
  11618. }
  11619. Expr *ValExpr = ChunkSize;
  11620. Stmt *HelperValStmt = nullptr;
  11621. if (ChunkSize) {
  11622. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  11623. !ChunkSize->isInstantiationDependent() &&
  11624. !ChunkSize->containsUnexpandedParameterPack()) {
  11625. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  11626. ExprResult Val =
  11627. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  11628. if (Val.isInvalid())
  11629. return nullptr;
  11630. ValExpr = Val.get();
  11631. // OpenMP [2.7.1, Restrictions]
  11632. // chunk_size must be a loop invariant integer expression with a positive
  11633. // value.
  11634. llvm::APSInt Result;
  11635. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  11636. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  11637. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  11638. << "dist_schedule" << ChunkSize->getSourceRange();
  11639. return nullptr;
  11640. }
  11641. } else if (getOpenMPCaptureRegionForClause(
  11642. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  11643. OMPD_unknown &&
  11644. !CurContext->isDependentContext()) {
  11645. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11646. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11647. HelperValStmt = buildPreInits(Context, Captures);
  11648. }
  11649. }
  11650. }
  11651. return new (Context)
  11652. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  11653. Kind, ValExpr, HelperValStmt);
  11654. }
  11655. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  11656. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  11657. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  11658. SourceLocation KindLoc, SourceLocation EndLoc) {
  11659. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  11660. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  11661. std::string Value;
  11662. SourceLocation Loc;
  11663. Value += "'";
  11664. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  11665. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11666. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  11667. Loc = MLoc;
  11668. } else {
  11669. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11670. OMPC_DEFAULTMAP_scalar);
  11671. Loc = KindLoc;
  11672. }
  11673. Value += "'";
  11674. Diag(Loc, diag::err_omp_unexpected_clause_value)
  11675. << Value << getOpenMPClauseName(OMPC_defaultmap);
  11676. return nullptr;
  11677. }
  11678. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  11679. return new (Context)
  11680. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  11681. }
  11682. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  11683. DeclContext *CurLexicalContext = getCurLexicalContext();
  11684. if (!CurLexicalContext->isFileContext() &&
  11685. !CurLexicalContext->isExternCContext() &&
  11686. !CurLexicalContext->isExternCXXContext() &&
  11687. !isa<CXXRecordDecl>(CurLexicalContext) &&
  11688. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  11689. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  11690. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  11691. Diag(Loc, diag::err_omp_region_not_file_context);
  11692. return false;
  11693. }
  11694. if (IsInOpenMPDeclareTargetContext) {
  11695. Diag(Loc, diag::err_omp_enclosed_declare_target);
  11696. return false;
  11697. }
  11698. IsInOpenMPDeclareTargetContext = true;
  11699. return true;
  11700. }
  11701. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  11702. assert(IsInOpenMPDeclareTargetContext &&
  11703. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  11704. IsInOpenMPDeclareTargetContext = false;
  11705. }
  11706. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  11707. CXXScopeSpec &ScopeSpec,
  11708. const DeclarationNameInfo &Id,
  11709. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  11710. NamedDeclSetType &SameDirectiveDecls) {
  11711. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  11712. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  11713. if (Lookup.isAmbiguous())
  11714. return;
  11715. Lookup.suppressDiagnostics();
  11716. if (!Lookup.isSingleResult()) {
  11717. if (TypoCorrection Corrected =
  11718. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  11719. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  11720. CTK_ErrorRecovery)) {
  11721. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  11722. << Id.getName());
  11723. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  11724. return;
  11725. }
  11726. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  11727. return;
  11728. }
  11729. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  11730. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  11731. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  11732. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  11733. if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
  11734. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  11735. ND->addAttr(A);
  11736. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11737. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  11738. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  11739. } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
  11740. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  11741. << Id.getName();
  11742. }
  11743. } else
  11744. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  11745. }
  11746. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  11747. Sema &SemaRef, Decl *D) {
  11748. if (!D)
  11749. return;
  11750. Decl *LD = nullptr;
  11751. if (isa<TagDecl>(D)) {
  11752. LD = cast<TagDecl>(D)->getDefinition();
  11753. } else if (isa<VarDecl>(D)) {
  11754. LD = cast<VarDecl>(D)->getDefinition();
  11755. // If this is an implicit variable that is legal and we do not need to do
  11756. // anything.
  11757. if (cast<VarDecl>(D)->isImplicit()) {
  11758. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11759. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11760. D->addAttr(A);
  11761. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11762. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11763. return;
  11764. }
  11765. } else if (isa<FunctionDecl>(D)) {
  11766. const FunctionDecl *FD = nullptr;
  11767. if (cast<FunctionDecl>(D)->hasBody(FD))
  11768. LD = const_cast<FunctionDecl *>(FD);
  11769. // If the definition is associated with the current declaration in the
  11770. // target region (it can be e.g. a lambda) that is legal and we do not need
  11771. // to do anything else.
  11772. if (LD == D) {
  11773. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11774. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11775. D->addAttr(A);
  11776. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11777. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11778. return;
  11779. }
  11780. }
  11781. if (!LD)
  11782. LD = D;
  11783. if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11784. (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
  11785. // Outlined declaration is not declared target.
  11786. if (LD->isOutOfLine()) {
  11787. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11788. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11789. } else {
  11790. DeclContext *DC = LD->getDeclContext();
  11791. while (DC) {
  11792. if (isa<FunctionDecl>(DC) &&
  11793. cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
  11794. break;
  11795. DC = DC->getParent();
  11796. }
  11797. if (DC)
  11798. return;
  11799. // Is not declared in target context.
  11800. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11801. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11802. }
  11803. // Mark decl as declared target to prevent further diagnostic.
  11804. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11805. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11806. D->addAttr(A);
  11807. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11808. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11809. }
  11810. }
  11811. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  11812. Sema &SemaRef, DSAStackTy *Stack,
  11813. ValueDecl *VD) {
  11814. if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
  11815. return true;
  11816. if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
  11817. return false;
  11818. return true;
  11819. }
  11820. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  11821. SourceLocation IdLoc) {
  11822. if (!D || D->isInvalidDecl())
  11823. return;
  11824. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  11825. SourceLocation SL = E ? E->getLocStart() : D->getLocation();
  11826. // 2.10.6: threadprivate variable cannot appear in a declare target directive.
  11827. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  11828. if (DSAStack->isThreadPrivate(VD)) {
  11829. Diag(SL, diag::err_omp_threadprivate_in_target);
  11830. ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  11831. return;
  11832. }
  11833. }
  11834. if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  11835. // Problem if any with var declared with incomplete type will be reported
  11836. // as normal, so no need to check it here.
  11837. if ((E || !VD->getType()->isIncompleteType()) &&
  11838. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
  11839. // Mark decl as declared target to prevent further diagnostic.
  11840. if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
  11841. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11842. Context, OMPDeclareTargetDeclAttr::MT_To);
  11843. VD->addAttr(A);
  11844. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11845. ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
  11846. }
  11847. return;
  11848. }
  11849. }
  11850. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  11851. if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11852. (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
  11853. OMPDeclareTargetDeclAttr::MT_Link)) {
  11854. assert(IdLoc.isValid() && "Source location is expected");
  11855. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  11856. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  11857. return;
  11858. }
  11859. }
  11860. if (!E) {
  11861. // Checking declaration inside declare target region.
  11862. if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11863. (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
  11864. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11865. Context, OMPDeclareTargetDeclAttr::MT_To);
  11866. D->addAttr(A);
  11867. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11868. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11869. }
  11870. return;
  11871. }
  11872. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  11873. }
  11874. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  11875. SourceLocation StartLoc,
  11876. SourceLocation LParenLoc,
  11877. SourceLocation EndLoc) {
  11878. MappableVarListInfo MVLI(VarList);
  11879. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  11880. if (MVLI.ProcessedVarList.empty())
  11881. return nullptr;
  11882. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11883. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11884. MVLI.VarComponents);
  11885. }
  11886. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  11887. SourceLocation StartLoc,
  11888. SourceLocation LParenLoc,
  11889. SourceLocation EndLoc) {
  11890. MappableVarListInfo MVLI(VarList);
  11891. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  11892. if (MVLI.ProcessedVarList.empty())
  11893. return nullptr;
  11894. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11895. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11896. MVLI.VarComponents);
  11897. }
  11898. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  11899. SourceLocation StartLoc,
  11900. SourceLocation LParenLoc,
  11901. SourceLocation EndLoc) {
  11902. MappableVarListInfo MVLI(VarList);
  11903. SmallVector<Expr *, 8> PrivateCopies;
  11904. SmallVector<Expr *, 8> Inits;
  11905. for (auto &RefExpr : VarList) {
  11906. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  11907. SourceLocation ELoc;
  11908. SourceRange ERange;
  11909. Expr *SimpleRefExpr = RefExpr;
  11910. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11911. if (Res.second) {
  11912. // It will be analyzed later.
  11913. MVLI.ProcessedVarList.push_back(RefExpr);
  11914. PrivateCopies.push_back(nullptr);
  11915. Inits.push_back(nullptr);
  11916. }
  11917. ValueDecl *D = Res.first;
  11918. if (!D)
  11919. continue;
  11920. QualType Type = D->getType();
  11921. Type = Type.getNonReferenceType().getUnqualifiedType();
  11922. auto *VD = dyn_cast<VarDecl>(D);
  11923. // Item should be a pointer or reference to pointer.
  11924. if (!Type->isPointerType()) {
  11925. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  11926. << 0 << RefExpr->getSourceRange();
  11927. continue;
  11928. }
  11929. // Build the private variable and the expression that refers to it.
  11930. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  11931. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11932. if (VDPrivate->isInvalidDecl())
  11933. continue;
  11934. CurContext->addDecl(VDPrivate);
  11935. auto VDPrivateRefExpr = buildDeclRefExpr(
  11936. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11937. // Add temporary variable to initialize the private copy of the pointer.
  11938. auto *VDInit =
  11939. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  11940. auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11941. RefExpr->getExprLoc());
  11942. AddInitializerToDecl(VDPrivate,
  11943. DefaultLvalueConversion(VDInitRefExpr).get(),
  11944. /*DirectInit=*/false);
  11945. // If required, build a capture to implement the privatization initialized
  11946. // with the current list item value.
  11947. DeclRefExpr *Ref = nullptr;
  11948. if (!VD)
  11949. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11950. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  11951. PrivateCopies.push_back(VDPrivateRefExpr);
  11952. Inits.push_back(VDInitRefExpr);
  11953. // We need to add a data sharing attribute for this variable to make sure it
  11954. // is correctly captured. A variable that shows up in a use_device_ptr has
  11955. // similar properties of a first private variable.
  11956. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11957. // Create a mappable component for the list item. List items in this clause
  11958. // only need a component.
  11959. MVLI.VarBaseDeclarations.push_back(D);
  11960. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11961. MVLI.VarComponents.back().push_back(
  11962. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  11963. }
  11964. if (MVLI.ProcessedVarList.empty())
  11965. return nullptr;
  11966. return OMPUseDevicePtrClause::Create(
  11967. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  11968. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  11969. }
  11970. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  11971. SourceLocation StartLoc,
  11972. SourceLocation LParenLoc,
  11973. SourceLocation EndLoc) {
  11974. MappableVarListInfo MVLI(VarList);
  11975. for (auto &RefExpr : VarList) {
  11976. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  11977. SourceLocation ELoc;
  11978. SourceRange ERange;
  11979. Expr *SimpleRefExpr = RefExpr;
  11980. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11981. if (Res.second) {
  11982. // It will be analyzed later.
  11983. MVLI.ProcessedVarList.push_back(RefExpr);
  11984. }
  11985. ValueDecl *D = Res.first;
  11986. if (!D)
  11987. continue;
  11988. QualType Type = D->getType();
  11989. // item should be a pointer or array or reference to pointer or array
  11990. if (!Type.getNonReferenceType()->isPointerType() &&
  11991. !Type.getNonReferenceType()->isArrayType()) {
  11992. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  11993. << 0 << RefExpr->getSourceRange();
  11994. continue;
  11995. }
  11996. // Check if the declaration in the clause does not show up in any data
  11997. // sharing attribute.
  11998. auto DVar = DSAStack->getTopDSA(D, false);
  11999. if (isOpenMPPrivate(DVar.CKind)) {
  12000. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12001. << getOpenMPClauseName(DVar.CKind)
  12002. << getOpenMPClauseName(OMPC_is_device_ptr)
  12003. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  12004. ReportOriginalDSA(*this, DSAStack, D, DVar);
  12005. continue;
  12006. }
  12007. Expr *ConflictExpr;
  12008. if (DSAStack->checkMappableExprComponentListsForDecl(
  12009. D, /*CurrentRegionOnly=*/true,
  12010. [&ConflictExpr](
  12011. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  12012. OpenMPClauseKind) -> bool {
  12013. ConflictExpr = R.front().getAssociatedExpression();
  12014. return true;
  12015. })) {
  12016. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  12017. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  12018. << ConflictExpr->getSourceRange();
  12019. continue;
  12020. }
  12021. // Store the components in the stack so that they can be used to check
  12022. // against other clauses later on.
  12023. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  12024. DSAStack->addMappableExpressionComponents(
  12025. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  12026. // Record the expression we've just processed.
  12027. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  12028. // Create a mappable component for the list item. List items in this clause
  12029. // only need a component. We use a null declaration to signal fields in
  12030. // 'this'.
  12031. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  12032. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  12033. "Unexpected device pointer expression!");
  12034. MVLI.VarBaseDeclarations.push_back(
  12035. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  12036. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12037. MVLI.VarComponents.back().push_back(MC);
  12038. }
  12039. if (MVLI.ProcessedVarList.empty())
  12040. return nullptr;
  12041. return OMPIsDevicePtrClause::Create(
  12042. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12043. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12044. }