SemaOpenMP.cpp 296 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256
  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/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/StmtCXX.h"
  21. #include "clang/AST/StmtOpenMP.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/Basic/OpenMPKinds.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Lex/Preprocessor.h"
  26. #include "clang/Sema/Initialization.h"
  27. #include "clang/Sema/Lookup.h"
  28. #include "clang/Sema/Scope.h"
  29. #include "clang/Sema/ScopeInfo.h"
  30. #include "clang/Sema/SemaInternal.h"
  31. using namespace clang;
  32. // HLSL Change Starts
  33. // No OpenMP Sema support, so simply skip all of this compilation.
  34. // Here are enough stubs to link the current targets.
  35. #if 1
  36. //===----------------------------------------------------------------------===//
  37. // Stack of data-sharing attributes for variables
  38. //===----------------------------------------------------------------------===//
  39. void Sema::InitDataSharingAttributesStack() {
  40. llvm_unreachable("HLSL does not support OpenMP constructs");
  41. }
  42. bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
  43. llvm_unreachable("HLSL does not support OpenMP constructs");
  44. }
  45. bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
  46. llvm_unreachable("HLSL does not support OpenMP constructs");
  47. }
  48. void Sema::DestroyDataSharingAttributesStack() {
  49. llvm_unreachable("HLSL does not support OpenMP constructs");
  50. }
  51. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  52. const DeclarationNameInfo &DirName,
  53. Scope *CurScope, SourceLocation Loc) {
  54. llvm_unreachable("HLSL does not support OpenMP constructs");
  55. }
  56. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  57. llvm_unreachable("HLSL does not support OpenMP constructs");
  58. }
  59. void Sema::EndOpenMPClause() {
  60. llvm_unreachable("HLSL does not support OpenMP constructs");
  61. }
  62. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  63. llvm_unreachable("HLSL does not support OpenMP constructs");
  64. }
  65. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  66. CXXScopeSpec &ScopeSpec,
  67. const DeclarationNameInfo &Id) {
  68. llvm_unreachable("HLSL does not support OpenMP constructs");
  69. }
  70. Sema::DeclGroupPtrTy
  71. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  72. ArrayRef<Expr *> VarList) {
  73. llvm_unreachable("HLSL does not support OpenMP constructs");
  74. }
  75. OMPThreadPrivateDecl *
  76. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  77. llvm_unreachable("HLSL does not support OpenMP constructs");
  78. }
  79. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  80. llvm_unreachable("HLSL does not support OpenMP constructs");
  81. }
  82. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  83. ArrayRef<OMPClause *> Clauses) {
  84. llvm_unreachable("HLSL does not support OpenMP constructs");
  85. }
  86. StmtResult Sema::ActOnOpenMPExecutableDirective(
  87. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  88. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  89. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  90. llvm_unreachable("HLSL does not support OpenMP constructs");
  91. }
  92. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  93. Stmt *AStmt,
  94. SourceLocation StartLoc,
  95. SourceLocation EndLoc) {
  96. llvm_unreachable("HLSL does not support OpenMP constructs");
  97. }
  98. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  99. llvm_unreachable("HLSL does not support OpenMP constructs");
  100. }
  101. StmtResult Sema::ActOnOpenMPSimdDirective(
  102. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  103. SourceLocation EndLoc,
  104. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  105. llvm_unreachable("HLSL does not support OpenMP constructs");
  106. }
  107. StmtResult Sema::ActOnOpenMPForDirective(
  108. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  109. SourceLocation EndLoc,
  110. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  111. llvm_unreachable("HLSL does not support OpenMP constructs");
  112. }
  113. StmtResult Sema::ActOnOpenMPForSimdDirective(
  114. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  115. SourceLocation EndLoc,
  116. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  117. llvm_unreachable("HLSL does not support OpenMP constructs");
  118. }
  119. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  120. Stmt *AStmt,
  121. SourceLocation StartLoc,
  122. SourceLocation EndLoc) {
  123. llvm_unreachable("HLSL does not support OpenMP constructs");
  124. }
  125. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  126. SourceLocation StartLoc,
  127. SourceLocation EndLoc) {
  128. llvm_unreachable("HLSL does not support OpenMP constructs");
  129. }
  130. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  131. Stmt *AStmt,
  132. SourceLocation StartLoc,
  133. SourceLocation EndLoc) {
  134. llvm_unreachable("HLSL does not support OpenMP constructs");
  135. }
  136. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  137. SourceLocation StartLoc,
  138. SourceLocation EndLoc) {
  139. llvm_unreachable("HLSL does not support OpenMP constructs");
  140. }
  141. StmtResult
  142. Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
  143. Stmt *AStmt, SourceLocation StartLoc,
  144. SourceLocation EndLoc) {
  145. llvm_unreachable("HLSL does not support OpenMP constructs");
  146. }
  147. StmtResult Sema::ActOnOpenMPParallelForDirective(
  148. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  149. SourceLocation EndLoc,
  150. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  151. llvm_unreachable("HLSL does not support OpenMP constructs");
  152. }
  153. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  154. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  155. SourceLocation EndLoc,
  156. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  157. llvm_unreachable("HLSL does not support OpenMP constructs");
  158. }
  159. StmtResult
  160. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  161. Stmt *AStmt, SourceLocation StartLoc,
  162. SourceLocation EndLoc) {
  163. llvm_unreachable("HLSL does not support OpenMP constructs");
  164. }
  165. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  166. Stmt *AStmt, SourceLocation StartLoc,
  167. SourceLocation EndLoc) {
  168. llvm_unreachable("HLSL does not support OpenMP constructs");
  169. }
  170. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  171. SourceLocation EndLoc) {
  172. llvm_unreachable("HLSL does not support OpenMP constructs");
  173. }
  174. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  175. SourceLocation EndLoc) {
  176. llvm_unreachable("HLSL does not support OpenMP constructs");
  177. }
  178. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  179. SourceLocation EndLoc) {
  180. llvm_unreachable("HLSL does not support OpenMP constructs");
  181. }
  182. StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
  183. SourceLocation StartLoc,
  184. SourceLocation EndLoc) {
  185. llvm_unreachable("HLSL does not support OpenMP constructs");
  186. }
  187. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  188. SourceLocation StartLoc,
  189. SourceLocation EndLoc) {
  190. llvm_unreachable("HLSL does not support OpenMP constructs");
  191. }
  192. StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
  193. SourceLocation StartLoc,
  194. SourceLocation EndLoc) {
  195. llvm_unreachable("HLSL does not support OpenMP constructs");
  196. }
  197. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  198. Stmt *AStmt,
  199. SourceLocation StartLoc,
  200. SourceLocation EndLoc) {
  201. llvm_unreachable("HLSL does not support OpenMP constructs");
  202. }
  203. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  204. Stmt *AStmt,
  205. SourceLocation StartLoc,
  206. SourceLocation EndLoc) {
  207. llvm_unreachable("HLSL does not support OpenMP constructs");
  208. }
  209. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  210. Stmt *AStmt, SourceLocation StartLoc,
  211. SourceLocation EndLoc) {
  212. llvm_unreachable("HLSL does not support OpenMP constructs");
  213. }
  214. StmtResult
  215. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  216. SourceLocation EndLoc,
  217. OpenMPDirectiveKind CancelRegion) {
  218. llvm_unreachable("HLSL does not support OpenMP constructs");
  219. }
  220. StmtResult Sema::ActOnOpenMPCancelDirective(SourceLocation StartLoc,
  221. SourceLocation EndLoc,
  222. OpenMPDirectiveKind CancelRegion) {
  223. llvm_unreachable("HLSL does not support OpenMP constructs");
  224. }
  225. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  226. SourceLocation StartLoc,
  227. SourceLocation LParenLoc,
  228. SourceLocation EndLoc) {
  229. llvm_unreachable("HLSL does not support OpenMP constructs");
  230. }
  231. OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
  232. SourceLocation LParenLoc,
  233. SourceLocation EndLoc) {
  234. llvm_unreachable("HLSL does not support OpenMP constructs");
  235. }
  236. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  237. SourceLocation StartLoc,
  238. SourceLocation LParenLoc,
  239. SourceLocation EndLoc) {
  240. llvm_unreachable("HLSL does not support OpenMP constructs");
  241. }
  242. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  243. Expr *Op) {
  244. llvm_unreachable("HLSL does not support OpenMP constructs");
  245. }
  246. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  247. SourceLocation StartLoc,
  248. SourceLocation LParenLoc,
  249. SourceLocation EndLoc) {
  250. llvm_unreachable("HLSL does not support OpenMP constructs");
  251. }
  252. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  253. OpenMPClauseKind CKind) {
  254. llvm_unreachable("HLSL does not support OpenMP constructs");
  255. }
  256. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  257. SourceLocation LParenLoc,
  258. SourceLocation EndLoc) {
  259. llvm_unreachable("HLSL does not support OpenMP constructs");
  260. }
  261. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  262. SourceLocation StartLoc,
  263. SourceLocation LParenLoc,
  264. SourceLocation EndLoc) {
  265. llvm_unreachable("HLSL does not support OpenMP constructs");
  266. }
  267. OMPClause *Sema::ActOnOpenMPSimpleClause(
  268. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  269. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  270. llvm_unreachable("HLSL does not support OpenMP constructs");
  271. }
  272. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  273. SourceLocation KindKwLoc,
  274. SourceLocation StartLoc,
  275. SourceLocation LParenLoc,
  276. SourceLocation EndLoc) {
  277. llvm_unreachable("HLSL does not support OpenMP constructs");
  278. }
  279. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  280. SourceLocation KindKwLoc,
  281. SourceLocation StartLoc,
  282. SourceLocation LParenLoc,
  283. SourceLocation EndLoc) {
  284. llvm_unreachable("HLSL does not support OpenMP constructs");
  285. }
  286. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  287. OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
  288. SourceLocation StartLoc, SourceLocation LParenLoc,
  289. SourceLocation ArgumentLoc, SourceLocation CommaLoc,
  290. SourceLocation EndLoc) {
  291. llvm_unreachable("HLSL does not support OpenMP constructs");
  292. }
  293. OMPClause *Sema::ActOnOpenMPScheduleClause(
  294. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  295. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  296. SourceLocation EndLoc) {
  297. llvm_unreachable("HLSL does not support OpenMP constructs");
  298. }
  299. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  300. SourceLocation StartLoc,
  301. SourceLocation EndLoc) {
  302. llvm_unreachable("HLSL does not support OpenMP constructs");
  303. }
  304. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  305. SourceLocation EndLoc) {
  306. llvm_unreachable("HLSL does not support OpenMP constructs");
  307. }
  308. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  309. SourceLocation EndLoc) {
  310. llvm_unreachable("HLSL does not support OpenMP constructs");
  311. }
  312. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  313. SourceLocation EndLoc) {
  314. llvm_unreachable("HLSL does not support OpenMP constructs");
  315. }
  316. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  317. SourceLocation EndLoc) {
  318. llvm_unreachable("HLSL does not support OpenMP constructs");
  319. }
  320. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  321. SourceLocation EndLoc) {
  322. llvm_unreachable("HLSL does not support OpenMP constructs");
  323. }
  324. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  325. SourceLocation EndLoc) {
  326. llvm_unreachable("HLSL does not support OpenMP constructs");
  327. }
  328. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  329. SourceLocation EndLoc) {
  330. llvm_unreachable("HLSL does not support OpenMP constructs");
  331. }
  332. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  333. SourceLocation EndLoc) {
  334. llvm_unreachable("HLSL does not support OpenMP constructs");
  335. }
  336. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  337. SourceLocation EndLoc) {
  338. llvm_unreachable("HLSL does not support OpenMP constructs");
  339. }
  340. OMPClause *Sema::ActOnOpenMPVarListClause(
  341. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  342. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  343. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  344. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  345. SourceLocation DepLoc) {
  346. llvm_unreachable("HLSL does not support OpenMP constructs");
  347. }
  348. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  349. SourceLocation StartLoc,
  350. SourceLocation LParenLoc,
  351. SourceLocation EndLoc) {
  352. llvm_unreachable("HLSL does not support OpenMP constructs");
  353. }
  354. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  355. SourceLocation StartLoc,
  356. SourceLocation LParenLoc,
  357. SourceLocation EndLoc) {
  358. llvm_unreachable("HLSL does not support OpenMP constructs");
  359. }
  360. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  361. SourceLocation StartLoc,
  362. SourceLocation LParenLoc,
  363. SourceLocation EndLoc) {
  364. llvm_unreachable("HLSL does not support OpenMP constructs");
  365. }
  366. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  367. SourceLocation StartLoc,
  368. SourceLocation LParenLoc,
  369. SourceLocation EndLoc) {
  370. llvm_unreachable("HLSL does not support OpenMP constructs");
  371. }
  372. OMPClause *Sema::ActOnOpenMPReductionClause(
  373. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  374. SourceLocation ColonLoc, SourceLocation EndLoc,
  375. CXXScopeSpec &ReductionIdScopeSpec,
  376. const DeclarationNameInfo &ReductionId) {
  377. llvm_unreachable("HLSL does not support OpenMP constructs");
  378. }
  379. OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
  380. SourceLocation StartLoc,
  381. SourceLocation LParenLoc,
  382. SourceLocation ColonLoc,
  383. SourceLocation EndLoc) {
  384. llvm_unreachable("HLSL does not support OpenMP constructs");
  385. }
  386. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  387. Expr *NumIterations, Sema &SemaRef,
  388. Scope *S) {
  389. llvm_unreachable("HLSL does not support OpenMP constructs");
  390. }
  391. OMPClause *Sema::ActOnOpenMPAlignedClause(
  392. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  393. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  394. llvm_unreachable("HLSL does not support OpenMP constructs");
  395. }
  396. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  397. SourceLocation StartLoc,
  398. SourceLocation LParenLoc,
  399. SourceLocation EndLoc) {
  400. llvm_unreachable("HLSL does not support OpenMP constructs");
  401. }
  402. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  403. SourceLocation StartLoc,
  404. SourceLocation LParenLoc,
  405. SourceLocation EndLoc) {
  406. llvm_unreachable("HLSL does not support OpenMP constructs");
  407. }
  408. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  409. SourceLocation StartLoc,
  410. SourceLocation LParenLoc,
  411. SourceLocation EndLoc) {
  412. llvm_unreachable("HLSL does not support OpenMP constructs");
  413. }
  414. OMPClause *
  415. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  416. SourceLocation DepLoc, SourceLocation ColonLoc,
  417. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  418. SourceLocation LParenLoc, SourceLocation EndLoc) {
  419. llvm_unreachable("HLSL does not support OpenMP constructs");
  420. }
  421. #else
  422. // HLSL Change Ends
  423. //===----------------------------------------------------------------------===//
  424. // Stack of data-sharing attributes for variables
  425. //===----------------------------------------------------------------------===//
  426. namespace {
  427. /// \brief Default data sharing attributes, which can be applied to directive.
  428. enum DefaultDataSharingAttributes {
  429. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  430. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  431. DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
  432. };
  433. template <class T> struct MatchesAny {
  434. explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
  435. bool operator()(T Kind) {
  436. for (auto KindEl : Arr)
  437. if (KindEl == Kind)
  438. return true;
  439. return false;
  440. }
  441. private:
  442. ArrayRef<T> Arr;
  443. };
  444. struct MatchesAlways {
  445. MatchesAlways() {}
  446. template <class T> bool operator()(T) { return true; }
  447. };
  448. typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
  449. typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
  450. /// \brief Stack for tracking declarations used in OpenMP directives and
  451. /// clauses and their data-sharing attributes.
  452. class DSAStackTy {
  453. public:
  454. struct DSAVarData {
  455. OpenMPDirectiveKind DKind;
  456. OpenMPClauseKind CKind;
  457. DeclRefExpr *RefExpr;
  458. SourceLocation ImplicitDSALoc;
  459. DSAVarData()
  460. : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
  461. ImplicitDSALoc() {}
  462. };
  463. private:
  464. struct DSAInfo {
  465. OpenMPClauseKind Attributes;
  466. DeclRefExpr *RefExpr;
  467. };
  468. typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
  469. typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
  470. typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
  471. struct SharingMapTy {
  472. DeclSAMapTy SharingMap;
  473. AlignedMapTy AlignedMap;
  474. LoopControlVariablesSetTy LCVSet;
  475. DefaultDataSharingAttributes DefaultAttr;
  476. SourceLocation DefaultAttrLoc;
  477. OpenMPDirectiveKind Directive;
  478. DeclarationNameInfo DirectiveName;
  479. Scope *CurScope;
  480. SourceLocation ConstructLoc;
  481. bool OrderedRegion;
  482. bool NowaitRegion;
  483. unsigned CollapseNumber;
  484. SourceLocation InnerTeamsRegionLoc;
  485. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  486. Scope *CurScope, SourceLocation Loc)
  487. : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
  488. Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
  489. ConstructLoc(Loc), OrderedRegion(false), NowaitRegion(false),
  490. CollapseNumber(1), InnerTeamsRegionLoc() {}
  491. SharingMapTy()
  492. : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
  493. Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
  494. ConstructLoc(), OrderedRegion(false), NowaitRegion(false),
  495. CollapseNumber(1), InnerTeamsRegionLoc() {}
  496. };
  497. typedef SmallVector<SharingMapTy, 64> StackTy;
  498. /// \brief Stack of used declaration and their data-sharing attributes.
  499. StackTy Stack;
  500. /// \brief true, if check for DSA must be from parent directive, false, if
  501. /// from current directive.
  502. OpenMPClauseKind ClauseKindMode;
  503. Sema &SemaRef;
  504. bool ForceCapturing;
  505. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  506. DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
  507. /// \brief Checks if the variable is a local for OpenMP region.
  508. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  509. public:
  510. explicit DSAStackTy(Sema &S)
  511. : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
  512. ForceCapturing(false) {}
  513. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  514. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  515. bool isForceVarCapturing() const { return ForceCapturing; }
  516. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  517. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  518. Scope *CurScope, SourceLocation Loc) {
  519. Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
  520. Stack.back().DefaultAttrLoc = Loc;
  521. }
  522. void pop() {
  523. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
  524. Stack.pop_back();
  525. }
  526. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  527. /// add it and return NULL; otherwise return previous occurrence's expression
  528. /// for diagnostics.
  529. DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
  530. /// \brief Register specified variable as loop control variable.
  531. void addLoopControlVariable(VarDecl *D);
  532. /// \brief Check if the specified variable is a loop control variable for
  533. /// current region.
  534. bool isLoopControlVariable(VarDecl *D);
  535. /// \brief Adds explicit data sharing attribute to the specified declaration.
  536. void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
  537. /// \brief Returns data sharing attributes from top of the stack for the
  538. /// specified declaration.
  539. DSAVarData getTopDSA(VarDecl *D, bool FromParent);
  540. /// \brief Returns data-sharing attributes for the specified declaration.
  541. DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
  542. /// \brief Checks if the specified variables has data-sharing attributes which
  543. /// match specified \a CPred predicate in any directive which matches \a DPred
  544. /// predicate.
  545. template <class ClausesPredicate, class DirectivesPredicate>
  546. DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
  547. DirectivesPredicate DPred, bool FromParent);
  548. /// \brief Checks if the specified variables has data-sharing attributes which
  549. /// match specified \a CPred predicate in any innermost directive which
  550. /// matches \a DPred predicate.
  551. template <class ClausesPredicate, class DirectivesPredicate>
  552. DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
  553. DirectivesPredicate DPred,
  554. bool FromParent);
  555. /// \brief Checks if the specified variables has explicit data-sharing
  556. /// attributes which match specified \a CPred predicate at the specified
  557. /// OpenMP region.
  558. bool hasExplicitDSA(VarDecl *D,
  559. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  560. unsigned Level);
  561. /// \brief Finds a directive which matches specified \a DPred predicate.
  562. template <class NamedDirectivesPredicate>
  563. bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
  564. /// \brief Returns currently analyzed directive.
  565. OpenMPDirectiveKind getCurrentDirective() const {
  566. return Stack.back().Directive;
  567. }
  568. /// \brief Returns parent directive.
  569. OpenMPDirectiveKind getParentDirective() const {
  570. if (Stack.size() > 2)
  571. return Stack[Stack.size() - 2].Directive;
  572. return OMPD_unknown;
  573. }
  574. /// \brief Set default data sharing attribute to none.
  575. void setDefaultDSANone(SourceLocation Loc) {
  576. Stack.back().DefaultAttr = DSA_none;
  577. Stack.back().DefaultAttrLoc = Loc;
  578. }
  579. /// \brief Set default data sharing attribute to shared.
  580. void setDefaultDSAShared(SourceLocation Loc) {
  581. Stack.back().DefaultAttr = DSA_shared;
  582. Stack.back().DefaultAttrLoc = Loc;
  583. }
  584. DefaultDataSharingAttributes getDefaultDSA() const {
  585. return Stack.back().DefaultAttr;
  586. }
  587. SourceLocation getDefaultDSALocation() const {
  588. return Stack.back().DefaultAttrLoc;
  589. }
  590. /// \brief Checks if the specified variable is a threadprivate.
  591. bool isThreadPrivate(VarDecl *D) {
  592. DSAVarData DVar = getTopDSA(D, false);
  593. return isOpenMPThreadPrivate(DVar.CKind);
  594. }
  595. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  596. void setOrderedRegion(bool IsOrdered = true) {
  597. Stack.back().OrderedRegion = IsOrdered;
  598. }
  599. /// \brief Returns true, if parent region is ordered (has associated
  600. /// 'ordered' clause), false - otherwise.
  601. bool isParentOrderedRegion() const {
  602. if (Stack.size() > 2)
  603. return Stack[Stack.size() - 2].OrderedRegion;
  604. return false;
  605. }
  606. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  607. void setNowaitRegion(bool IsNowait = true) {
  608. Stack.back().NowaitRegion = IsNowait;
  609. }
  610. /// \brief Returns true, if parent region is nowait (has associated
  611. /// 'nowait' clause), false - otherwise.
  612. bool isParentNowaitRegion() const {
  613. if (Stack.size() > 2)
  614. return Stack[Stack.size() - 2].NowaitRegion;
  615. return false;
  616. }
  617. /// \brief Set collapse value for the region.
  618. void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
  619. /// \brief Return collapse value for region.
  620. unsigned getCollapseNumber() const {
  621. return Stack.back().CollapseNumber;
  622. }
  623. /// \brief Marks current target region as one with closely nested teams
  624. /// region.
  625. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  626. if (Stack.size() > 2)
  627. Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
  628. }
  629. /// \brief Returns true, if current region has closely nested teams region.
  630. bool hasInnerTeamsRegion() const {
  631. return getInnerTeamsRegionLoc().isValid();
  632. }
  633. /// \brief Returns location of the nested teams region (if any).
  634. SourceLocation getInnerTeamsRegionLoc() const {
  635. if (Stack.size() > 1)
  636. return Stack.back().InnerTeamsRegionLoc;
  637. return SourceLocation();
  638. }
  639. Scope *getCurScope() const { return Stack.back().CurScope; }
  640. Scope *getCurScope() { return Stack.back().CurScope; }
  641. SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
  642. };
  643. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  644. return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
  645. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  646. }
  647. } // namespace
  648. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
  649. VarDecl *D) {
  650. D = D->getCanonicalDecl();
  651. DSAVarData DVar;
  652. if (Iter == std::prev(Stack.rend())) {
  653. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  654. // in a region but not in construct]
  655. // File-scope or namespace-scope variables referenced in called routines
  656. // in the region are shared unless they appear in a threadprivate
  657. // directive.
  658. if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  659. DVar.CKind = OMPC_shared;
  660. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  661. // in a region but not in construct]
  662. // Variables with static storage duration that are declared in called
  663. // routines in the region are shared.
  664. if (D->hasGlobalStorage())
  665. DVar.CKind = OMPC_shared;
  666. return DVar;
  667. }
  668. DVar.DKind = Iter->Directive;
  669. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  670. // in a Construct, C/C++, predetermined, p.1]
  671. // Variables with automatic storage duration that are declared in a scope
  672. // inside the construct are private.
  673. if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
  674. (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
  675. DVar.CKind = OMPC_private;
  676. return DVar;
  677. }
  678. // Explicitly specified attributes and local variables with predetermined
  679. // attributes.
  680. if (Iter->SharingMap.count(D)) {
  681. DVar.RefExpr = Iter->SharingMap[D].RefExpr;
  682. DVar.CKind = Iter->SharingMap[D].Attributes;
  683. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  684. return DVar;
  685. }
  686. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  687. // in a Construct, C/C++, implicitly determined, p.1]
  688. // In a parallel or task construct, the data-sharing attributes of these
  689. // variables are determined by the default clause, if present.
  690. switch (Iter->DefaultAttr) {
  691. case DSA_shared:
  692. DVar.CKind = OMPC_shared;
  693. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  694. return DVar;
  695. case DSA_none:
  696. return DVar;
  697. case DSA_unspecified:
  698. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  699. // in a Construct, implicitly determined, p.2]
  700. // In a parallel construct, if no default clause is present, these
  701. // variables are shared.
  702. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  703. if (isOpenMPParallelDirective(DVar.DKind) ||
  704. isOpenMPTeamsDirective(DVar.DKind)) {
  705. DVar.CKind = OMPC_shared;
  706. return DVar;
  707. }
  708. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  709. // in a Construct, implicitly determined, p.4]
  710. // In a task construct, if no default clause is present, a variable that in
  711. // the enclosing context is determined to be shared by all implicit tasks
  712. // bound to the current team is shared.
  713. if (DVar.DKind == OMPD_task) {
  714. DSAVarData DVarTemp;
  715. for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
  716. I != EE; ++I) {
  717. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  718. // Referenced
  719. // in a Construct, implicitly determined, p.6]
  720. // In a task construct, if no default clause is present, a variable
  721. // whose data-sharing attribute is not determined by the rules above is
  722. // firstprivate.
  723. DVarTemp = getDSA(I, D);
  724. if (DVarTemp.CKind != OMPC_shared) {
  725. DVar.RefExpr = nullptr;
  726. DVar.DKind = OMPD_task;
  727. DVar.CKind = OMPC_firstprivate;
  728. return DVar;
  729. }
  730. if (isParallelOrTaskRegion(I->Directive))
  731. break;
  732. }
  733. DVar.DKind = OMPD_task;
  734. DVar.CKind =
  735. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  736. return DVar;
  737. }
  738. }
  739. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  740. // in a Construct, implicitly determined, p.3]
  741. // For constructs other than task, if no default clause is present, these
  742. // variables inherit their data-sharing attributes from the enclosing
  743. // context.
  744. return getDSA(std::next(Iter), D);
  745. }
  746. DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
  747. assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
  748. D = D->getCanonicalDecl();
  749. auto It = Stack.back().AlignedMap.find(D);
  750. if (It == Stack.back().AlignedMap.end()) {
  751. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  752. Stack.back().AlignedMap[D] = NewDE;
  753. return nullptr;
  754. } else {
  755. assert(It->second && "Unexpected nullptr expr in the aligned map");
  756. return It->second;
  757. }
  758. return nullptr;
  759. }
  760. void DSAStackTy::addLoopControlVariable(VarDecl *D) {
  761. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  762. D = D->getCanonicalDecl();
  763. Stack.back().LCVSet.insert(D);
  764. }
  765. bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
  766. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  767. D = D->getCanonicalDecl();
  768. return Stack.back().LCVSet.count(D) > 0;
  769. }
  770. void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
  771. D = D->getCanonicalDecl();
  772. if (A == OMPC_threadprivate) {
  773. Stack[0].SharingMap[D].Attributes = A;
  774. Stack[0].SharingMap[D].RefExpr = E;
  775. } else {
  776. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  777. Stack.back().SharingMap[D].Attributes = A;
  778. Stack.back().SharingMap[D].RefExpr = E;
  779. }
  780. }
  781. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  782. D = D->getCanonicalDecl();
  783. if (Stack.size() > 2) {
  784. reverse_iterator I = Iter, E = std::prev(Stack.rend());
  785. Scope *TopScope = nullptr;
  786. while (I != E && !isParallelOrTaskRegion(I->Directive)) {
  787. ++I;
  788. }
  789. if (I == E)
  790. return false;
  791. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  792. Scope *CurScope = getCurScope();
  793. while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
  794. CurScope = CurScope->getParent();
  795. }
  796. return CurScope != TopScope;
  797. }
  798. return false;
  799. }
  800. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  801. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  802. StringRef Name) {
  803. DeclContext *DC = SemaRef.CurContext;
  804. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  805. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  806. VarDecl *Decl =
  807. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  808. Decl->setImplicit();
  809. return Decl;
  810. }
  811. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  812. SourceLocation Loc,
  813. bool RefersToCapture = false) {
  814. D->setReferenced();
  815. D->markUsed(S.Context);
  816. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  817. SourceLocation(), D, RefersToCapture, Loc, Ty,
  818. VK_LValue);
  819. }
  820. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
  821. D = D->getCanonicalDecl();
  822. DSAVarData DVar;
  823. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  824. // in a Construct, C/C++, predetermined, p.1]
  825. // Variables appearing in threadprivate directives are threadprivate.
  826. if ((D->getTLSKind() != VarDecl::TLS_None &&
  827. !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
  828. SemaRef.getLangOpts().OpenMPUseTLS &&
  829. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  830. (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
  831. !D->isLocalVarDecl())) {
  832. addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
  833. D->getLocation()),
  834. OMPC_threadprivate);
  835. }
  836. if (Stack[0].SharingMap.count(D)) {
  837. DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
  838. DVar.CKind = OMPC_threadprivate;
  839. return DVar;
  840. }
  841. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  842. // in a Construct, C/C++, predetermined, p.1]
  843. // Variables with automatic storage duration that are declared in a scope
  844. // inside the construct are private.
  845. OpenMPDirectiveKind Kind =
  846. FromParent ? getParentDirective() : getCurrentDirective();
  847. auto StartI = std::next(Stack.rbegin());
  848. auto EndI = std::prev(Stack.rend());
  849. if (FromParent && StartI != EndI) {
  850. StartI = std::next(StartI);
  851. }
  852. if (!isParallelOrTaskRegion(Kind)) {
  853. if (isOpenMPLocal(D, StartI) &&
  854. ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
  855. D->getStorageClass() == SC_None)) ||
  856. isa<ParmVarDecl>(D))) {
  857. DVar.CKind = OMPC_private;
  858. return DVar;
  859. }
  860. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  861. // in a Construct, C/C++, predetermined, p.4]
  862. // Static data members are shared.
  863. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  864. // in a Construct, C/C++, predetermined, p.7]
  865. // Variables with static storage duration that are declared in a scope
  866. // inside the construct are shared.
  867. if (D->isStaticDataMember() || D->isStaticLocal()) {
  868. DSAVarData DVarTemp =
  869. hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
  870. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  871. return DVar;
  872. DVar.CKind = OMPC_shared;
  873. return DVar;
  874. }
  875. }
  876. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  877. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  878. Type = SemaRef.getASTContext().getBaseElementType(Type);
  879. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  880. // in a Construct, C/C++, predetermined, p.6]
  881. // Variables with const qualified type having no mutable member are
  882. // shared.
  883. CXXRecordDecl *RD =
  884. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  885. if (IsConstant &&
  886. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
  887. // Variables with const-qualified type having no mutable member may be
  888. // listed in a firstprivate clause, even if they are static data members.
  889. DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
  890. MatchesAlways(), FromParent);
  891. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  892. return DVar;
  893. DVar.CKind = OMPC_shared;
  894. return DVar;
  895. }
  896. // Explicitly specified attributes and local variables with predetermined
  897. // attributes.
  898. auto I = std::prev(StartI);
  899. if (I->SharingMap.count(D)) {
  900. DVar.RefExpr = I->SharingMap[D].RefExpr;
  901. DVar.CKind = I->SharingMap[D].Attributes;
  902. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  903. }
  904. return DVar;
  905. }
  906. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
  907. D = D->getCanonicalDecl();
  908. auto StartI = Stack.rbegin();
  909. auto EndI = std::prev(Stack.rend());
  910. if (FromParent && StartI != EndI) {
  911. StartI = std::next(StartI);
  912. }
  913. return getDSA(StartI, D);
  914. }
  915. template <class ClausesPredicate, class DirectivesPredicate>
  916. DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
  917. DirectivesPredicate DPred,
  918. bool FromParent) {
  919. D = D->getCanonicalDecl();
  920. auto StartI = std::next(Stack.rbegin());
  921. auto EndI = std::prev(Stack.rend());
  922. if (FromParent && StartI != EndI) {
  923. StartI = std::next(StartI);
  924. }
  925. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  926. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  927. continue;
  928. DSAVarData DVar = getDSA(I, D);
  929. if (CPred(DVar.CKind))
  930. return DVar;
  931. }
  932. return DSAVarData();
  933. }
  934. template <class ClausesPredicate, class DirectivesPredicate>
  935. DSAStackTy::DSAVarData
  936. DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
  937. DirectivesPredicate DPred, bool FromParent) {
  938. D = D->getCanonicalDecl();
  939. auto StartI = std::next(Stack.rbegin());
  940. auto EndI = std::prev(Stack.rend());
  941. if (FromParent && StartI != EndI) {
  942. StartI = std::next(StartI);
  943. }
  944. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  945. if (!DPred(I->Directive))
  946. break;
  947. DSAVarData DVar = getDSA(I, D);
  948. if (CPred(DVar.CKind))
  949. return DVar;
  950. return DSAVarData();
  951. }
  952. return DSAVarData();
  953. }
  954. bool DSAStackTy::hasExplicitDSA(
  955. VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  956. unsigned Level) {
  957. if (CPred(ClauseKindMode))
  958. return true;
  959. if (isClauseParsingMode())
  960. ++Level;
  961. D = D->getCanonicalDecl();
  962. auto StartI = Stack.rbegin();
  963. auto EndI = std::prev(Stack.rend());
  964. if (std::distance(StartI, EndI) <= (int)Level)
  965. return false;
  966. std::advance(StartI, Level);
  967. return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
  968. CPred(StartI->SharingMap[D].Attributes);
  969. }
  970. template <class NamedDirectivesPredicate>
  971. bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
  972. auto StartI = std::next(Stack.rbegin());
  973. auto EndI = std::prev(Stack.rend());
  974. if (FromParent && StartI != EndI) {
  975. StartI = std::next(StartI);
  976. }
  977. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  978. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  979. return true;
  980. }
  981. return false;
  982. }
  983. void Sema::InitDataSharingAttributesStack() {
  984. VarDataSharingAttributesStack = new DSAStackTy(*this);
  985. }
  986. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  987. bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
  988. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  989. VD = VD->getCanonicalDecl();
  990. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  991. (!DSAStack->isClauseParsingMode() ||
  992. DSAStack->getParentDirective() != OMPD_unknown)) {
  993. if (DSAStack->isLoopControlVariable(VD) ||
  994. (VD->hasLocalStorage() &&
  995. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  996. DSAStack->isForceVarCapturing())
  997. return true;
  998. auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
  999. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1000. return true;
  1001. DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
  1002. DSAStack->isClauseParsingMode());
  1003. return DVarPrivate.CKind != OMPC_unknown;
  1004. }
  1005. return false;
  1006. }
  1007. bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
  1008. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1009. return DSAStack->hasExplicitDSA(
  1010. VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
  1011. }
  1012. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1013. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1014. const DeclarationNameInfo &DirName,
  1015. Scope *CurScope, SourceLocation Loc) {
  1016. DSAStack->push(DKind, DirName, CurScope, Loc);
  1017. PushExpressionEvaluationContext(PotentiallyEvaluated);
  1018. }
  1019. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1020. DSAStack->setClauseParsingMode(K);
  1021. }
  1022. void Sema::EndOpenMPClause() {
  1023. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1024. }
  1025. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1026. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1027. // A variable of class type (or array thereof) that appears in a lastprivate
  1028. // clause requires an accessible, unambiguous default constructor for the
  1029. // class type, unless the list item is also specified in a firstprivate
  1030. // clause.
  1031. if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1032. for (auto *C : D->clauses()) {
  1033. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1034. SmallVector<Expr *, 8> PrivateCopies;
  1035. for (auto *DE : Clause->varlists()) {
  1036. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1037. PrivateCopies.push_back(nullptr);
  1038. continue;
  1039. }
  1040. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
  1041. QualType Type = VD->getType();
  1042. auto DVar = DSAStack->getTopDSA(VD, false);
  1043. if (DVar.CKind == OMPC_lastprivate) {
  1044. // Generate helper private variable and initialize it with the
  1045. // default value. The address of the original variable is replaced
  1046. // by the address of the new private variable in CodeGen. This new
  1047. // variable is not added to IdResolver, so the code in the OpenMP
  1048. // region uses original variable for proper diagnostics.
  1049. auto *VDPrivate =
  1050. buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1051. VD->getName());
  1052. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
  1053. if (VDPrivate->isInvalidDecl())
  1054. continue;
  1055. PrivateCopies.push_back(buildDeclRefExpr(
  1056. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1057. } else {
  1058. // The variable is also a firstprivate, so initialization sequence
  1059. // for private copy is generated already.
  1060. PrivateCopies.push_back(nullptr);
  1061. }
  1062. }
  1063. // Set initializers to private copies if no errors were found.
  1064. if (PrivateCopies.size() == Clause->varlist_size()) {
  1065. Clause->setPrivateCopies(PrivateCopies);
  1066. }
  1067. }
  1068. }
  1069. }
  1070. DSAStack->pop();
  1071. DiscardCleanupsInEvaluationContext();
  1072. PopExpressionEvaluationContext();
  1073. }
  1074. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1075. Expr *NumIterations, Sema &SemaRef,
  1076. Scope *S);
  1077. namespace {
  1078. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  1079. private:
  1080. Sema &SemaRef;
  1081. public:
  1082. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1083. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1084. NamedDecl *ND = Candidate.getCorrectionDecl();
  1085. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1086. return VD->hasGlobalStorage() &&
  1087. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1088. SemaRef.getCurScope());
  1089. }
  1090. return false;
  1091. }
  1092. };
  1093. } // namespace
  1094. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1095. CXXScopeSpec &ScopeSpec,
  1096. const DeclarationNameInfo &Id) {
  1097. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1098. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1099. if (Lookup.isAmbiguous())
  1100. return ExprError();
  1101. VarDecl *VD;
  1102. if (!Lookup.isSingleResult()) {
  1103. if (TypoCorrection Corrected = CorrectTypo(
  1104. Id, LookupOrdinaryName, CurScope, nullptr,
  1105. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1106. diagnoseTypo(Corrected,
  1107. PDiag(Lookup.empty()
  1108. ? diag::err_undeclared_var_use_suggest
  1109. : diag::err_omp_expected_var_arg_suggest)
  1110. << Id.getName());
  1111. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1112. } else {
  1113. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1114. : diag::err_omp_expected_var_arg)
  1115. << Id.getName();
  1116. return ExprError();
  1117. }
  1118. } else {
  1119. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1120. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1121. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1122. return ExprError();
  1123. }
  1124. }
  1125. Lookup.suppressDiagnostics();
  1126. // OpenMP [2.9.2, Syntax, C/C++]
  1127. // Variables must be file-scope, namespace-scope, or static block-scope.
  1128. if (!VD->hasGlobalStorage()) {
  1129. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1130. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1131. bool IsDecl =
  1132. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1133. Diag(VD->getLocation(),
  1134. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1135. << VD;
  1136. return ExprError();
  1137. }
  1138. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1139. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1140. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1141. // A threadprivate directive for file-scope variables must appear outside
  1142. // any definition or declaration.
  1143. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1144. !getCurLexicalContext()->isTranslationUnit()) {
  1145. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1146. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1147. bool IsDecl =
  1148. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1149. Diag(VD->getLocation(),
  1150. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1151. << VD;
  1152. return ExprError();
  1153. }
  1154. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1155. // A threadprivate directive for static class member variables must appear
  1156. // in the class definition, in the same scope in which the member
  1157. // variables are declared.
  1158. if (CanonicalVD->isStaticDataMember() &&
  1159. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1160. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1161. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1162. bool IsDecl =
  1163. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1164. Diag(VD->getLocation(),
  1165. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1166. << VD;
  1167. return ExprError();
  1168. }
  1169. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1170. // A threadprivate directive for namespace-scope variables must appear
  1171. // outside any definition or declaration other than the namespace
  1172. // definition itself.
  1173. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1174. (!getCurLexicalContext()->isFileContext() ||
  1175. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1176. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1177. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1178. bool IsDecl =
  1179. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1180. Diag(VD->getLocation(),
  1181. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1182. << VD;
  1183. return ExprError();
  1184. }
  1185. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1186. // A threadprivate directive for static block-scope variables must appear
  1187. // in the scope of the variable and not in a nested scope.
  1188. if (CanonicalVD->isStaticLocal() && CurScope &&
  1189. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1190. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1191. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1192. bool IsDecl =
  1193. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1194. Diag(VD->getLocation(),
  1195. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1196. << VD;
  1197. return ExprError();
  1198. }
  1199. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1200. // A threadprivate directive must lexically precede all references to any
  1201. // of the variables in its list.
  1202. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1203. Diag(Id.getLoc(), diag::err_omp_var_used)
  1204. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1205. return ExprError();
  1206. }
  1207. QualType ExprType = VD->getType().getNonReferenceType();
  1208. ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
  1209. return DE;
  1210. }
  1211. Sema::DeclGroupPtrTy
  1212. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1213. ArrayRef<Expr *> VarList) {
  1214. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1215. CurContext->addDecl(D);
  1216. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1217. }
  1218. return DeclGroupPtrTy();
  1219. }
  1220. namespace {
  1221. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1222. Sema &SemaRef;
  1223. public:
  1224. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1225. if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
  1226. if (VD->hasLocalStorage()) {
  1227. SemaRef.Diag(E->getLocStart(),
  1228. diag::err_omp_local_var_in_threadprivate_init)
  1229. << E->getSourceRange();
  1230. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1231. << VD << VD->getSourceRange();
  1232. return true;
  1233. }
  1234. }
  1235. return false;
  1236. }
  1237. bool VisitStmt(const Stmt *S) {
  1238. for (auto Child : S->children()) {
  1239. if (Child && Visit(Child))
  1240. return true;
  1241. }
  1242. return false;
  1243. }
  1244. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1245. };
  1246. } // namespace
  1247. OMPThreadPrivateDecl *
  1248. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1249. SmallVector<Expr *, 8> Vars;
  1250. for (auto &RefExpr : VarList) {
  1251. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1252. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1253. SourceLocation ILoc = DE->getExprLoc();
  1254. QualType QType = VD->getType();
  1255. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1256. // It will be analyzed later.
  1257. Vars.push_back(DE);
  1258. continue;
  1259. }
  1260. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1261. // A threadprivate variable must not have an incomplete type.
  1262. if (RequireCompleteType(ILoc, VD->getType(),
  1263. diag::err_omp_threadprivate_incomplete_type)) {
  1264. continue;
  1265. }
  1266. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1267. // A threadprivate variable must not have a reference type.
  1268. if (VD->getType()->isReferenceType()) {
  1269. Diag(ILoc, diag::err_omp_ref_type_arg)
  1270. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1271. bool IsDecl =
  1272. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1273. Diag(VD->getLocation(),
  1274. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1275. << VD;
  1276. continue;
  1277. }
  1278. // Check if this is a TLS variable. If TLS is not being supported, produce
  1279. // the corresponding diagnostic.
  1280. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1281. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1282. getLangOpts().OpenMPUseTLS &&
  1283. getASTContext().getTargetInfo().isTLSSupported())) ||
  1284. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1285. !VD->isLocalVarDecl())) {
  1286. Diag(ILoc, diag::err_omp_var_thread_local)
  1287. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1288. bool IsDecl =
  1289. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1290. Diag(VD->getLocation(),
  1291. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1292. << VD;
  1293. continue;
  1294. }
  1295. // Check if initial value of threadprivate variable reference variable with
  1296. // local storage (it is not supported by runtime).
  1297. if (auto Init = VD->getAnyInitializer()) {
  1298. LocalVarRefChecker Checker(*this);
  1299. if (Checker.Visit(Init))
  1300. continue;
  1301. }
  1302. Vars.push_back(RefExpr);
  1303. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1304. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1305. Context, SourceRange(Loc, Loc)));
  1306. if (auto *ML = Context.getASTMutationListener())
  1307. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1308. }
  1309. OMPThreadPrivateDecl *D = nullptr;
  1310. if (!Vars.empty()) {
  1311. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1312. Vars);
  1313. D->setAccess(AS_public);
  1314. }
  1315. return D;
  1316. }
  1317. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1318. const VarDecl *VD, DSAStackTy::DSAVarData DVar,
  1319. bool IsLoopIterVar = false) {
  1320. if (DVar.RefExpr) {
  1321. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1322. << getOpenMPClauseName(DVar.CKind);
  1323. return;
  1324. }
  1325. enum {
  1326. PDSA_StaticMemberShared,
  1327. PDSA_StaticLocalVarShared,
  1328. PDSA_LoopIterVarPrivate,
  1329. PDSA_LoopIterVarLinear,
  1330. PDSA_LoopIterVarLastprivate,
  1331. PDSA_ConstVarShared,
  1332. PDSA_GlobalVarShared,
  1333. PDSA_TaskVarFirstprivate,
  1334. PDSA_LocalVarPrivate,
  1335. PDSA_Implicit
  1336. } Reason = PDSA_Implicit;
  1337. bool ReportHint = false;
  1338. auto ReportLoc = VD->getLocation();
  1339. if (IsLoopIterVar) {
  1340. if (DVar.CKind == OMPC_private)
  1341. Reason = PDSA_LoopIterVarPrivate;
  1342. else if (DVar.CKind == OMPC_lastprivate)
  1343. Reason = PDSA_LoopIterVarLastprivate;
  1344. else
  1345. Reason = PDSA_LoopIterVarLinear;
  1346. } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
  1347. Reason = PDSA_TaskVarFirstprivate;
  1348. ReportLoc = DVar.ImplicitDSALoc;
  1349. } else if (VD->isStaticLocal())
  1350. Reason = PDSA_StaticLocalVarShared;
  1351. else if (VD->isStaticDataMember())
  1352. Reason = PDSA_StaticMemberShared;
  1353. else if (VD->isFileVarDecl())
  1354. Reason = PDSA_GlobalVarShared;
  1355. else if (VD->getType().isConstant(SemaRef.getASTContext()))
  1356. Reason = PDSA_ConstVarShared;
  1357. else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1358. ReportHint = true;
  1359. Reason = PDSA_LocalVarPrivate;
  1360. }
  1361. if (Reason != PDSA_Implicit) {
  1362. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1363. << Reason << ReportHint
  1364. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1365. } else if (DVar.ImplicitDSALoc.isValid()) {
  1366. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1367. << getOpenMPClauseName(DVar.CKind);
  1368. }
  1369. }
  1370. namespace {
  1371. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1372. DSAStackTy *Stack;
  1373. Sema &SemaRef;
  1374. bool ErrorFound;
  1375. CapturedStmt *CS;
  1376. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1377. llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
  1378. public:
  1379. void VisitDeclRefExpr(DeclRefExpr *E) {
  1380. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1381. // Skip internally declared variables.
  1382. if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
  1383. return;
  1384. auto DVar = Stack->getTopDSA(VD, false);
  1385. // Check if the variable has explicit DSA set and stop analysis if it so.
  1386. if (DVar.RefExpr) return;
  1387. auto ELoc = E->getExprLoc();
  1388. auto DKind = Stack->getCurrentDirective();
  1389. // The default(none) clause requires that each variable that is referenced
  1390. // in the construct, and does not have a predetermined data-sharing
  1391. // attribute, must have its data-sharing attribute explicitly determined
  1392. // by being listed in a data-sharing attribute clause.
  1393. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1394. isParallelOrTaskRegion(DKind) &&
  1395. VarsWithInheritedDSA.count(VD) == 0) {
  1396. VarsWithInheritedDSA[VD] = E;
  1397. return;
  1398. }
  1399. // OpenMP [2.9.3.6, Restrictions, p.2]
  1400. // A list item that appears in a reduction clause of the innermost
  1401. // enclosing worksharing or parallel construct may not be accessed in an
  1402. // explicit task.
  1403. DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  1404. [](OpenMPDirectiveKind K) -> bool {
  1405. return isOpenMPParallelDirective(K) ||
  1406. isOpenMPWorksharingDirective(K) ||
  1407. isOpenMPTeamsDirective(K);
  1408. },
  1409. false);
  1410. if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
  1411. ErrorFound = true;
  1412. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1413. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1414. return;
  1415. }
  1416. // Define implicit data-sharing attributes for task.
  1417. DVar = Stack->getImplicitDSA(VD, false);
  1418. if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
  1419. ImplicitFirstprivate.push_back(E);
  1420. }
  1421. }
  1422. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1423. for (auto *C : S->clauses()) {
  1424. // Skip analysis of arguments of implicitly defined firstprivate clause
  1425. // for task directives.
  1426. if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
  1427. for (auto *CC : C->children()) {
  1428. if (CC)
  1429. Visit(CC);
  1430. }
  1431. }
  1432. }
  1433. void VisitStmt(Stmt *S) {
  1434. for (auto *C : S->children()) {
  1435. if (C && !isa<OMPExecutableDirective>(C))
  1436. Visit(C);
  1437. }
  1438. }
  1439. bool isErrorFound() { return ErrorFound; }
  1440. ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
  1441. llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
  1442. return VarsWithInheritedDSA;
  1443. }
  1444. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1445. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1446. };
  1447. } // namespace
  1448. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1449. switch (DKind) {
  1450. case OMPD_parallel: {
  1451. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1452. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1453. Sema::CapturedParamNameType Params[] = {
  1454. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1455. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1456. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1457. };
  1458. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1459. Params);
  1460. break;
  1461. }
  1462. case OMPD_simd: {
  1463. Sema::CapturedParamNameType Params[] = {
  1464. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1465. };
  1466. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1467. Params);
  1468. break;
  1469. }
  1470. case OMPD_for: {
  1471. Sema::CapturedParamNameType Params[] = {
  1472. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1473. };
  1474. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1475. Params);
  1476. break;
  1477. }
  1478. case OMPD_for_simd: {
  1479. Sema::CapturedParamNameType Params[] = {
  1480. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1481. };
  1482. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1483. Params);
  1484. break;
  1485. }
  1486. case OMPD_sections: {
  1487. Sema::CapturedParamNameType Params[] = {
  1488. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1489. };
  1490. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1491. Params);
  1492. break;
  1493. }
  1494. case OMPD_section: {
  1495. Sema::CapturedParamNameType Params[] = {
  1496. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1497. };
  1498. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1499. Params);
  1500. break;
  1501. }
  1502. case OMPD_single: {
  1503. Sema::CapturedParamNameType Params[] = {
  1504. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1505. };
  1506. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1507. Params);
  1508. break;
  1509. }
  1510. case OMPD_master: {
  1511. Sema::CapturedParamNameType Params[] = {
  1512. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1513. };
  1514. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1515. Params);
  1516. break;
  1517. }
  1518. case OMPD_critical: {
  1519. Sema::CapturedParamNameType Params[] = {
  1520. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1521. };
  1522. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1523. Params);
  1524. break;
  1525. }
  1526. case OMPD_parallel_for: {
  1527. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1528. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1529. Sema::CapturedParamNameType Params[] = {
  1530. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1531. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1532. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1533. };
  1534. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1535. Params);
  1536. break;
  1537. }
  1538. case OMPD_parallel_for_simd: {
  1539. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1540. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1541. Sema::CapturedParamNameType Params[] = {
  1542. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1543. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1544. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1545. };
  1546. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1547. Params);
  1548. break;
  1549. }
  1550. case OMPD_parallel_sections: {
  1551. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1552. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1553. Sema::CapturedParamNameType Params[] = {
  1554. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1555. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1556. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1557. };
  1558. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1559. Params);
  1560. break;
  1561. }
  1562. case OMPD_task: {
  1563. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1564. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  1565. FunctionProtoType::ExtProtoInfo EPI;
  1566. EPI.Variadic = true;
  1567. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  1568. Sema::CapturedParamNameType Params[] = {
  1569. std::make_pair(".global_tid.", KmpInt32Ty),
  1570. std::make_pair(".part_id.", KmpInt32Ty),
  1571. std::make_pair(".privates.",
  1572. Context.VoidPtrTy.withConst().withRestrict()),
  1573. std::make_pair(
  1574. ".copy_fn.",
  1575. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  1576. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1577. };
  1578. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1579. Params);
  1580. // Mark this captured region as inlined, because we don't use outlined
  1581. // function directly.
  1582. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  1583. AlwaysInlineAttr::CreateImplicit(
  1584. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  1585. break;
  1586. }
  1587. case OMPD_ordered: {
  1588. Sema::CapturedParamNameType Params[] = {
  1589. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1590. };
  1591. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1592. Params);
  1593. break;
  1594. }
  1595. case OMPD_atomic: {
  1596. Sema::CapturedParamNameType Params[] = {
  1597. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1598. };
  1599. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1600. Params);
  1601. break;
  1602. }
  1603. case OMPD_target: {
  1604. Sema::CapturedParamNameType Params[] = {
  1605. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1606. };
  1607. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1608. Params);
  1609. break;
  1610. }
  1611. case OMPD_teams: {
  1612. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1613. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1614. Sema::CapturedParamNameType Params[] = {
  1615. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1616. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1617. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1618. };
  1619. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1620. Params);
  1621. break;
  1622. }
  1623. case OMPD_taskgroup: {
  1624. Sema::CapturedParamNameType Params[] = {
  1625. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1626. };
  1627. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1628. Params);
  1629. break;
  1630. }
  1631. case OMPD_threadprivate:
  1632. case OMPD_taskyield:
  1633. case OMPD_barrier:
  1634. case OMPD_taskwait:
  1635. case OMPD_cancellation_point:
  1636. case OMPD_cancel:
  1637. case OMPD_flush:
  1638. llvm_unreachable("OpenMP Directive is not allowed");
  1639. case OMPD_unknown:
  1640. llvm_unreachable("Unknown OpenMP directive");
  1641. }
  1642. }
  1643. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  1644. ArrayRef<OMPClause *> Clauses) {
  1645. if (!S.isUsable()) {
  1646. ActOnCapturedRegionError();
  1647. return StmtError();
  1648. }
  1649. // This is required for proper codegen.
  1650. for (auto *Clause : Clauses) {
  1651. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  1652. Clause->getClauseKind() == OMPC_copyprivate ||
  1653. (getLangOpts().OpenMPUseTLS &&
  1654. getASTContext().getTargetInfo().isTLSSupported() &&
  1655. Clause->getClauseKind() == OMPC_copyin)) {
  1656. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  1657. // Mark all variables in private list clauses as used in inner region.
  1658. for (auto *VarRef : Clause->children()) {
  1659. if (auto *E = cast_or_null<Expr>(VarRef)) {
  1660. MarkDeclarationsReferencedInExpr(E);
  1661. }
  1662. }
  1663. DSAStack->setForceVarCapturing(/*V=*/false);
  1664. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
  1665. Clause->getClauseKind() == OMPC_schedule) {
  1666. // Mark all variables in private list clauses as used in inner region.
  1667. // Required for proper codegen of combined directives.
  1668. // TODO: add processing for other clauses.
  1669. if (auto *E = cast_or_null<Expr>(
  1670. cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
  1671. MarkDeclarationsReferencedInExpr(E);
  1672. }
  1673. }
  1674. }
  1675. return ActOnCapturedRegionEnd(S.get());
  1676. }
  1677. static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  1678. OpenMPDirectiveKind CurrentRegion,
  1679. const DeclarationNameInfo &CurrentName,
  1680. OpenMPDirectiveKind CancelRegion,
  1681. SourceLocation StartLoc) {
  1682. // Allowed nesting of constructs
  1683. // +------------------+-----------------+------------------------------------+
  1684. // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
  1685. // +------------------+-----------------+------------------------------------+
  1686. // | parallel | parallel | * |
  1687. // | parallel | for | * |
  1688. // | parallel | for simd | * |
  1689. // | parallel | master | * |
  1690. // | parallel | critical | * |
  1691. // | parallel | simd | * |
  1692. // | parallel | sections | * |
  1693. // | parallel | section | + |
  1694. // | parallel | single | * |
  1695. // | parallel | parallel for | * |
  1696. // | parallel |parallel for simd| * |
  1697. // | parallel |parallel sections| * |
  1698. // | parallel | task | * |
  1699. // | parallel | taskyield | * |
  1700. // | parallel | barrier | * |
  1701. // | parallel | taskwait | * |
  1702. // | parallel | taskgroup | * |
  1703. // | parallel | flush | * |
  1704. // | parallel | ordered | + |
  1705. // | parallel | atomic | * |
  1706. // | parallel | target | * |
  1707. // | parallel | teams | + |
  1708. // | parallel | cancellation | |
  1709. // | | point | ! |
  1710. // | parallel | cancel | ! |
  1711. // +------------------+-----------------+------------------------------------+
  1712. // | for | parallel | * |
  1713. // | for | for | + |
  1714. // | for | for simd | + |
  1715. // | for | master | + |
  1716. // | for | critical | * |
  1717. // | for | simd | * |
  1718. // | for | sections | + |
  1719. // | for | section | + |
  1720. // | for | single | + |
  1721. // | for | parallel for | * |
  1722. // | for |parallel for simd| * |
  1723. // | for |parallel sections| * |
  1724. // | for | task | * |
  1725. // | for | taskyield | * |
  1726. // | for | barrier | + |
  1727. // | for | taskwait | * |
  1728. // | for | taskgroup | * |
  1729. // | for | flush | * |
  1730. // | for | ordered | * (if construct is ordered) |
  1731. // | for | atomic | * |
  1732. // | for | target | * |
  1733. // | for | teams | + |
  1734. // | for | cancellation | |
  1735. // | | point | ! |
  1736. // | for | cancel | ! |
  1737. // +------------------+-----------------+------------------------------------+
  1738. // | master | parallel | * |
  1739. // | master | for | + |
  1740. // | master | for simd | + |
  1741. // | master | master | * |
  1742. // | master | critical | * |
  1743. // | master | simd | * |
  1744. // | master | sections | + |
  1745. // | master | section | + |
  1746. // | master | single | + |
  1747. // | master | parallel for | * |
  1748. // | master |parallel for simd| * |
  1749. // | master |parallel sections| * |
  1750. // | master | task | * |
  1751. // | master | taskyield | * |
  1752. // | master | barrier | + |
  1753. // | master | taskwait | * |
  1754. // | master | taskgroup | * |
  1755. // | master | flush | * |
  1756. // | master | ordered | + |
  1757. // | master | atomic | * |
  1758. // | master | target | * |
  1759. // | master | teams | + |
  1760. // | master | cancellation | |
  1761. // | | point | |
  1762. // | master | cancel | |
  1763. // +------------------+-----------------+------------------------------------+
  1764. // | critical | parallel | * |
  1765. // | critical | for | + |
  1766. // | critical | for simd | + |
  1767. // | critical | master | * |
  1768. // | critical | critical | * (should have different names) |
  1769. // | critical | simd | * |
  1770. // | critical | sections | + |
  1771. // | critical | section | + |
  1772. // | critical | single | + |
  1773. // | critical | parallel for | * |
  1774. // | critical |parallel for simd| * |
  1775. // | critical |parallel sections| * |
  1776. // | critical | task | * |
  1777. // | critical | taskyield | * |
  1778. // | critical | barrier | + |
  1779. // | critical | taskwait | * |
  1780. // | critical | taskgroup | * |
  1781. // | critical | ordered | + |
  1782. // | critical | atomic | * |
  1783. // | critical | target | * |
  1784. // | critical | teams | + |
  1785. // | critical | cancellation | |
  1786. // | | point | |
  1787. // | critical | cancel | |
  1788. // +------------------+-----------------+------------------------------------+
  1789. // | simd | parallel | |
  1790. // | simd | for | |
  1791. // | simd | for simd | |
  1792. // | simd | master | |
  1793. // | simd | critical | |
  1794. // | simd | simd | |
  1795. // | simd | sections | |
  1796. // | simd | section | |
  1797. // | simd | single | |
  1798. // | simd | parallel for | |
  1799. // | simd |parallel for simd| |
  1800. // | simd |parallel sections| |
  1801. // | simd | task | |
  1802. // | simd | taskyield | |
  1803. // | simd | barrier | |
  1804. // | simd | taskwait | |
  1805. // | simd | taskgroup | |
  1806. // | simd | flush | |
  1807. // | simd | ordered | |
  1808. // | simd | atomic | |
  1809. // | simd | target | |
  1810. // | simd | teams | |
  1811. // | simd | cancellation | |
  1812. // | | point | |
  1813. // | simd | cancel | |
  1814. // +------------------+-----------------+------------------------------------+
  1815. // | for simd | parallel | |
  1816. // | for simd | for | |
  1817. // | for simd | for simd | |
  1818. // | for simd | master | |
  1819. // | for simd | critical | |
  1820. // | for simd | simd | |
  1821. // | for simd | sections | |
  1822. // | for simd | section | |
  1823. // | for simd | single | |
  1824. // | for simd | parallel for | |
  1825. // | for simd |parallel for simd| |
  1826. // | for simd |parallel sections| |
  1827. // | for simd | task | |
  1828. // | for simd | taskyield | |
  1829. // | for simd | barrier | |
  1830. // | for simd | taskwait | |
  1831. // | for simd | taskgroup | |
  1832. // | for simd | flush | |
  1833. // | for simd | ordered | |
  1834. // | for simd | atomic | |
  1835. // | for simd | target | |
  1836. // | for simd | teams | |
  1837. // | for simd | cancellation | |
  1838. // | | point | |
  1839. // | for simd | cancel | |
  1840. // +------------------+-----------------+------------------------------------+
  1841. // | parallel for simd| parallel | |
  1842. // | parallel for simd| for | |
  1843. // | parallel for simd| for simd | |
  1844. // | parallel for simd| master | |
  1845. // | parallel for simd| critical | |
  1846. // | parallel for simd| simd | |
  1847. // | parallel for simd| sections | |
  1848. // | parallel for simd| section | |
  1849. // | parallel for simd| single | |
  1850. // | parallel for simd| parallel for | |
  1851. // | parallel for simd|parallel for simd| |
  1852. // | parallel for simd|parallel sections| |
  1853. // | parallel for simd| task | |
  1854. // | parallel for simd| taskyield | |
  1855. // | parallel for simd| barrier | |
  1856. // | parallel for simd| taskwait | |
  1857. // | parallel for simd| taskgroup | |
  1858. // | parallel for simd| flush | |
  1859. // | parallel for simd| ordered | |
  1860. // | parallel for simd| atomic | |
  1861. // | parallel for simd| target | |
  1862. // | parallel for simd| teams | |
  1863. // | parallel for simd| cancellation | |
  1864. // | | point | |
  1865. // | parallel for simd| cancel | |
  1866. // +------------------+-----------------+------------------------------------+
  1867. // | sections | parallel | * |
  1868. // | sections | for | + |
  1869. // | sections | for simd | + |
  1870. // | sections | master | + |
  1871. // | sections | critical | * |
  1872. // | sections | simd | * |
  1873. // | sections | sections | + |
  1874. // | sections | section | * |
  1875. // | sections | single | + |
  1876. // | sections | parallel for | * |
  1877. // | sections |parallel for simd| * |
  1878. // | sections |parallel sections| * |
  1879. // | sections | task | * |
  1880. // | sections | taskyield | * |
  1881. // | sections | barrier | + |
  1882. // | sections | taskwait | * |
  1883. // | sections | taskgroup | * |
  1884. // | sections | flush | * |
  1885. // | sections | ordered | + |
  1886. // | sections | atomic | * |
  1887. // | sections | target | * |
  1888. // | sections | teams | + |
  1889. // | sections | cancellation | |
  1890. // | | point | ! |
  1891. // | sections | cancel | ! |
  1892. // +------------------+-----------------+------------------------------------+
  1893. // | section | parallel | * |
  1894. // | section | for | + |
  1895. // | section | for simd | + |
  1896. // | section | master | + |
  1897. // | section | critical | * |
  1898. // | section | simd | * |
  1899. // | section | sections | + |
  1900. // | section | section | + |
  1901. // | section | single | + |
  1902. // | section | parallel for | * |
  1903. // | section |parallel for simd| * |
  1904. // | section |parallel sections| * |
  1905. // | section | task | * |
  1906. // | section | taskyield | * |
  1907. // | section | barrier | + |
  1908. // | section | taskwait | * |
  1909. // | section | taskgroup | * |
  1910. // | section | flush | * |
  1911. // | section | ordered | + |
  1912. // | section | atomic | * |
  1913. // | section | target | * |
  1914. // | section | teams | + |
  1915. // | section | cancellation | |
  1916. // | | point | ! |
  1917. // | section | cancel | ! |
  1918. // +------------------+-----------------+------------------------------------+
  1919. // | single | parallel | * |
  1920. // | single | for | + |
  1921. // | single | for simd | + |
  1922. // | single | master | + |
  1923. // | single | critical | * |
  1924. // | single | simd | * |
  1925. // | single | sections | + |
  1926. // | single | section | + |
  1927. // | single | single | + |
  1928. // | single | parallel for | * |
  1929. // | single |parallel for simd| * |
  1930. // | single |parallel sections| * |
  1931. // | single | task | * |
  1932. // | single | taskyield | * |
  1933. // | single | barrier | + |
  1934. // | single | taskwait | * |
  1935. // | single | taskgroup | * |
  1936. // | single | flush | * |
  1937. // | single | ordered | + |
  1938. // | single | atomic | * |
  1939. // | single | target | * |
  1940. // | single | teams | + |
  1941. // | single | cancellation | |
  1942. // | | point | |
  1943. // | single | cancel | |
  1944. // +------------------+-----------------+------------------------------------+
  1945. // | parallel for | parallel | * |
  1946. // | parallel for | for | + |
  1947. // | parallel for | for simd | + |
  1948. // | parallel for | master | + |
  1949. // | parallel for | critical | * |
  1950. // | parallel for | simd | * |
  1951. // | parallel for | sections | + |
  1952. // | parallel for | section | + |
  1953. // | parallel for | single | + |
  1954. // | parallel for | parallel for | * |
  1955. // | parallel for |parallel for simd| * |
  1956. // | parallel for |parallel sections| * |
  1957. // | parallel for | task | * |
  1958. // | parallel for | taskyield | * |
  1959. // | parallel for | barrier | + |
  1960. // | parallel for | taskwait | * |
  1961. // | parallel for | taskgroup | * |
  1962. // | parallel for | flush | * |
  1963. // | parallel for | ordered | * (if construct is ordered) |
  1964. // | parallel for | atomic | * |
  1965. // | parallel for | target | * |
  1966. // | parallel for | teams | + |
  1967. // | parallel for | cancellation | |
  1968. // | | point | ! |
  1969. // | parallel for | cancel | ! |
  1970. // +------------------+-----------------+------------------------------------+
  1971. // | parallel sections| parallel | * |
  1972. // | parallel sections| for | + |
  1973. // | parallel sections| for simd | + |
  1974. // | parallel sections| master | + |
  1975. // | parallel sections| critical | + |
  1976. // | parallel sections| simd | * |
  1977. // | parallel sections| sections | + |
  1978. // | parallel sections| section | * |
  1979. // | parallel sections| single | + |
  1980. // | parallel sections| parallel for | * |
  1981. // | parallel sections|parallel for simd| * |
  1982. // | parallel sections|parallel sections| * |
  1983. // | parallel sections| task | * |
  1984. // | parallel sections| taskyield | * |
  1985. // | parallel sections| barrier | + |
  1986. // | parallel sections| taskwait | * |
  1987. // | parallel sections| taskgroup | * |
  1988. // | parallel sections| flush | * |
  1989. // | parallel sections| ordered | + |
  1990. // | parallel sections| atomic | * |
  1991. // | parallel sections| target | * |
  1992. // | parallel sections| teams | + |
  1993. // | parallel sections| cancellation | |
  1994. // | | point | ! |
  1995. // | parallel sections| cancel | ! |
  1996. // +------------------+-----------------+------------------------------------+
  1997. // | task | parallel | * |
  1998. // | task | for | + |
  1999. // | task | for simd | + |
  2000. // | task | master | + |
  2001. // | task | critical | * |
  2002. // | task | simd | * |
  2003. // | task | sections | + |
  2004. // | task | section | + |
  2005. // | task | single | + |
  2006. // | task | parallel for | * |
  2007. // | task |parallel for simd| * |
  2008. // | task |parallel sections| * |
  2009. // | task | task | * |
  2010. // | task | taskyield | * |
  2011. // | task | barrier | + |
  2012. // | task | taskwait | * |
  2013. // | task | taskgroup | * |
  2014. // | task | flush | * |
  2015. // | task | ordered | + |
  2016. // | task | atomic | * |
  2017. // | task | target | * |
  2018. // | task | teams | + |
  2019. // | task | cancellation | |
  2020. // | | point | ! |
  2021. // | task | cancel | ! |
  2022. // +------------------+-----------------+------------------------------------+
  2023. // | ordered | parallel | * |
  2024. // | ordered | for | + |
  2025. // | ordered | for simd | + |
  2026. // | ordered | master | * |
  2027. // | ordered | critical | * |
  2028. // | ordered | simd | * |
  2029. // | ordered | sections | + |
  2030. // | ordered | section | + |
  2031. // | ordered | single | + |
  2032. // | ordered | parallel for | * |
  2033. // | ordered |parallel for simd| * |
  2034. // | ordered |parallel sections| * |
  2035. // | ordered | task | * |
  2036. // | ordered | taskyield | * |
  2037. // | ordered | barrier | + |
  2038. // | ordered | taskwait | * |
  2039. // | ordered | taskgroup | * |
  2040. // | ordered | flush | * |
  2041. // | ordered | ordered | + |
  2042. // | ordered | atomic | * |
  2043. // | ordered | target | * |
  2044. // | ordered | teams | + |
  2045. // | ordered | cancellation | |
  2046. // | | point | |
  2047. // | ordered | cancel | |
  2048. // +------------------+-----------------+------------------------------------+
  2049. // | atomic | parallel | |
  2050. // | atomic | for | |
  2051. // | atomic | for simd | |
  2052. // | atomic | master | |
  2053. // | atomic | critical | |
  2054. // | atomic | simd | |
  2055. // | atomic | sections | |
  2056. // | atomic | section | |
  2057. // | atomic | single | |
  2058. // | atomic | parallel for | |
  2059. // | atomic |parallel for simd| |
  2060. // | atomic |parallel sections| |
  2061. // | atomic | task | |
  2062. // | atomic | taskyield | |
  2063. // | atomic | barrier | |
  2064. // | atomic | taskwait | |
  2065. // | atomic | taskgroup | |
  2066. // | atomic | flush | |
  2067. // | atomic | ordered | |
  2068. // | atomic | atomic | |
  2069. // | atomic | target | |
  2070. // | atomic | teams | |
  2071. // | atomic | cancellation | |
  2072. // | | point | |
  2073. // | atomic | cancel | |
  2074. // +------------------+-----------------+------------------------------------+
  2075. // | target | parallel | * |
  2076. // | target | for | * |
  2077. // | target | for simd | * |
  2078. // | target | master | * |
  2079. // | target | critical | * |
  2080. // | target | simd | * |
  2081. // | target | sections | * |
  2082. // | target | section | * |
  2083. // | target | single | * |
  2084. // | target | parallel for | * |
  2085. // | target |parallel for simd| * |
  2086. // | target |parallel sections| * |
  2087. // | target | task | * |
  2088. // | target | taskyield | * |
  2089. // | target | barrier | * |
  2090. // | target | taskwait | * |
  2091. // | target | taskgroup | * |
  2092. // | target | flush | * |
  2093. // | target | ordered | * |
  2094. // | target | atomic | * |
  2095. // | target | target | * |
  2096. // | target | teams | * |
  2097. // | target | cancellation | |
  2098. // | | point | |
  2099. // | target | cancel | |
  2100. // +------------------+-----------------+------------------------------------+
  2101. // | teams | parallel | * |
  2102. // | teams | for | + |
  2103. // | teams | for simd | + |
  2104. // | teams | master | + |
  2105. // | teams | critical | + |
  2106. // | teams | simd | + |
  2107. // | teams | sections | + |
  2108. // | teams | section | + |
  2109. // | teams | single | + |
  2110. // | teams | parallel for | * |
  2111. // | teams |parallel for simd| * |
  2112. // | teams |parallel sections| * |
  2113. // | teams | task | + |
  2114. // | teams | taskyield | + |
  2115. // | teams | barrier | + |
  2116. // | teams | taskwait | + |
  2117. // | teams | taskgroup | + |
  2118. // | teams | flush | + |
  2119. // | teams | ordered | + |
  2120. // | teams | atomic | + |
  2121. // | teams | target | + |
  2122. // | teams | teams | + |
  2123. // | teams | cancellation | |
  2124. // | | point | |
  2125. // | teams | cancel | |
  2126. // +------------------+-----------------+------------------------------------+
  2127. if (Stack->getCurScope()) {
  2128. auto ParentRegion = Stack->getParentDirective();
  2129. bool NestingProhibited = false;
  2130. bool CloseNesting = true;
  2131. enum {
  2132. NoRecommend,
  2133. ShouldBeInParallelRegion,
  2134. ShouldBeInOrderedRegion,
  2135. ShouldBeInTargetRegion
  2136. } Recommend = NoRecommend;
  2137. if (isOpenMPSimdDirective(ParentRegion)) {
  2138. // OpenMP [2.16, Nesting of Regions]
  2139. // OpenMP constructs may not be nested inside a simd region.
  2140. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  2141. return true;
  2142. }
  2143. if (ParentRegion == OMPD_atomic) {
  2144. // OpenMP [2.16, Nesting of Regions]
  2145. // OpenMP constructs may not be nested inside an atomic region.
  2146. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2147. return true;
  2148. }
  2149. if (CurrentRegion == OMPD_section) {
  2150. // OpenMP [2.7.2, sections Construct, Restrictions]
  2151. // Orphaned section directives are prohibited. That is, the section
  2152. // directives must appear within the sections construct and must not be
  2153. // encountered elsewhere in the sections region.
  2154. if (ParentRegion != OMPD_sections &&
  2155. ParentRegion != OMPD_parallel_sections) {
  2156. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2157. << (ParentRegion != OMPD_unknown)
  2158. << getOpenMPDirectiveName(ParentRegion);
  2159. return true;
  2160. }
  2161. return false;
  2162. }
  2163. // Allow some constructs to be orphaned (they could be used in functions,
  2164. // called from OpenMP regions with the required preconditions).
  2165. if (ParentRegion == OMPD_unknown)
  2166. return false;
  2167. if (CurrentRegion == OMPD_cancellation_point ||
  2168. CurrentRegion == OMPD_cancel) {
  2169. // OpenMP [2.16, Nesting of Regions]
  2170. // A cancellation point construct for which construct-type-clause is
  2171. // taskgroup must be nested inside a task construct. A cancellation
  2172. // point construct for which construct-type-clause is not taskgroup must
  2173. // be closely nested inside an OpenMP construct that matches the type
  2174. // specified in construct-type-clause.
  2175. // A cancel construct for which construct-type-clause is taskgroup must be
  2176. // nested inside a task construct. A cancel construct for which
  2177. // construct-type-clause is not taskgroup must be closely nested inside an
  2178. // OpenMP construct that matches the type specified in
  2179. // construct-type-clause.
  2180. NestingProhibited =
  2181. !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
  2182. (CancelRegion == OMPD_for && ParentRegion == OMPD_for) ||
  2183. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2184. (CancelRegion == OMPD_sections &&
  2185. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections)));
  2186. } else if (CurrentRegion == OMPD_master) {
  2187. // OpenMP [2.16, Nesting of Regions]
  2188. // A master region may not be closely nested inside a worksharing,
  2189. // atomic, or explicit task region.
  2190. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2191. ParentRegion == OMPD_task;
  2192. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2193. // OpenMP [2.16, Nesting of Regions]
  2194. // A critical region may not be nested (closely or otherwise) inside a
  2195. // critical region with the same name. Note that this restriction is not
  2196. // sufficient to prevent deadlock.
  2197. SourceLocation PreviousCriticalLoc;
  2198. bool DeadLock =
  2199. Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
  2200. OpenMPDirectiveKind K,
  2201. const DeclarationNameInfo &DNI,
  2202. SourceLocation Loc)
  2203. ->bool {
  2204. if (K == OMPD_critical &&
  2205. DNI.getName() == CurrentName.getName()) {
  2206. PreviousCriticalLoc = Loc;
  2207. return true;
  2208. } else
  2209. return false;
  2210. },
  2211. false /* skip top directive */);
  2212. if (DeadLock) {
  2213. SemaRef.Diag(StartLoc,
  2214. diag::err_omp_prohibited_region_critical_same_name)
  2215. << CurrentName.getName();
  2216. if (PreviousCriticalLoc.isValid())
  2217. SemaRef.Diag(PreviousCriticalLoc,
  2218. diag::note_omp_previous_critical_region);
  2219. return true;
  2220. }
  2221. } else if (CurrentRegion == OMPD_barrier) {
  2222. // OpenMP [2.16, Nesting of Regions]
  2223. // A barrier region may not be closely nested inside a worksharing,
  2224. // explicit task, critical, ordered, atomic, or master region.
  2225. NestingProhibited =
  2226. isOpenMPWorksharingDirective(ParentRegion) ||
  2227. ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
  2228. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  2229. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2230. !isOpenMPParallelDirective(CurrentRegion)) {
  2231. // OpenMP [2.16, Nesting of Regions]
  2232. // A worksharing region may not be closely nested inside a worksharing,
  2233. // explicit task, critical, ordered, atomic, or master region.
  2234. NestingProhibited =
  2235. isOpenMPWorksharingDirective(ParentRegion) ||
  2236. ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
  2237. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  2238. Recommend = ShouldBeInParallelRegion;
  2239. } else if (CurrentRegion == OMPD_ordered) {
  2240. // OpenMP [2.16, Nesting of Regions]
  2241. // An ordered region may not be closely nested inside a critical,
  2242. // atomic, or explicit task region.
  2243. // An ordered region must be closely nested inside a loop region (or
  2244. // parallel loop region) with an ordered clause.
  2245. NestingProhibited = ParentRegion == OMPD_critical ||
  2246. ParentRegion == OMPD_task ||
  2247. !Stack->isParentOrderedRegion();
  2248. Recommend = ShouldBeInOrderedRegion;
  2249. } else if (isOpenMPTeamsDirective(CurrentRegion)) {
  2250. // OpenMP [2.16, Nesting of Regions]
  2251. // If specified, a teams construct must be contained within a target
  2252. // construct.
  2253. NestingProhibited = ParentRegion != OMPD_target;
  2254. Recommend = ShouldBeInTargetRegion;
  2255. Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
  2256. }
  2257. if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
  2258. // OpenMP [2.16, Nesting of Regions]
  2259. // distribute, parallel, parallel sections, parallel workshare, and the
  2260. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2261. // constructs that can be closely nested in the teams region.
  2262. // TODO: add distribute directive.
  2263. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
  2264. Recommend = ShouldBeInParallelRegion;
  2265. }
  2266. if (NestingProhibited) {
  2267. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2268. << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
  2269. << getOpenMPDirectiveName(CurrentRegion);
  2270. return true;
  2271. }
  2272. }
  2273. return false;
  2274. }
  2275. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2276. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2277. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2278. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2279. StmtResult Res = StmtError();
  2280. if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2281. StartLoc))
  2282. return StmtError();
  2283. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2284. llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
  2285. bool ErrorFound = false;
  2286. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2287. if (AStmt) {
  2288. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2289. // Check default data sharing attributes for referenced variables.
  2290. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2291. DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
  2292. if (DSAChecker.isErrorFound())
  2293. return StmtError();
  2294. // Generate list of implicitly defined firstprivate variables.
  2295. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2296. if (!DSAChecker.getImplicitFirstprivate().empty()) {
  2297. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2298. DSAChecker.getImplicitFirstprivate(), SourceLocation(),
  2299. SourceLocation(), SourceLocation())) {
  2300. ClausesWithImplicit.push_back(Implicit);
  2301. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2302. DSAChecker.getImplicitFirstprivate().size();
  2303. } else
  2304. ErrorFound = true;
  2305. }
  2306. }
  2307. switch (Kind) {
  2308. case OMPD_parallel:
  2309. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2310. EndLoc);
  2311. break;
  2312. case OMPD_simd:
  2313. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2314. VarsWithInheritedDSA);
  2315. break;
  2316. case OMPD_for:
  2317. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2318. VarsWithInheritedDSA);
  2319. break;
  2320. case OMPD_for_simd:
  2321. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2322. EndLoc, VarsWithInheritedDSA);
  2323. break;
  2324. case OMPD_sections:
  2325. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2326. EndLoc);
  2327. break;
  2328. case OMPD_section:
  2329. assert(ClausesWithImplicit.empty() &&
  2330. "No clauses are allowed for 'omp section' directive");
  2331. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2332. break;
  2333. case OMPD_single:
  2334. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2335. EndLoc);
  2336. break;
  2337. case OMPD_master:
  2338. assert(ClausesWithImplicit.empty() &&
  2339. "No clauses are allowed for 'omp master' directive");
  2340. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2341. break;
  2342. case OMPD_critical:
  2343. assert(ClausesWithImplicit.empty() &&
  2344. "No clauses are allowed for 'omp critical' directive");
  2345. Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
  2346. break;
  2347. case OMPD_parallel_for:
  2348. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2349. EndLoc, VarsWithInheritedDSA);
  2350. break;
  2351. case OMPD_parallel_for_simd:
  2352. Res = ActOnOpenMPParallelForSimdDirective(
  2353. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2354. break;
  2355. case OMPD_parallel_sections:
  2356. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2357. StartLoc, EndLoc);
  2358. break;
  2359. case OMPD_task:
  2360. Res =
  2361. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2362. break;
  2363. case OMPD_taskyield:
  2364. assert(ClausesWithImplicit.empty() &&
  2365. "No clauses are allowed for 'omp taskyield' directive");
  2366. assert(AStmt == nullptr &&
  2367. "No associated statement allowed for 'omp taskyield' directive");
  2368. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2369. break;
  2370. case OMPD_barrier:
  2371. assert(ClausesWithImplicit.empty() &&
  2372. "No clauses are allowed for 'omp barrier' directive");
  2373. assert(AStmt == nullptr &&
  2374. "No associated statement allowed for 'omp barrier' directive");
  2375. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2376. break;
  2377. case OMPD_taskwait:
  2378. assert(ClausesWithImplicit.empty() &&
  2379. "No clauses are allowed for 'omp taskwait' directive");
  2380. assert(AStmt == nullptr &&
  2381. "No associated statement allowed for 'omp taskwait' directive");
  2382. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2383. break;
  2384. case OMPD_taskgroup:
  2385. assert(ClausesWithImplicit.empty() &&
  2386. "No clauses are allowed for 'omp taskgroup' directive");
  2387. Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
  2388. break;
  2389. case OMPD_flush:
  2390. assert(AStmt == nullptr &&
  2391. "No associated statement allowed for 'omp flush' directive");
  2392. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2393. break;
  2394. case OMPD_ordered:
  2395. assert(ClausesWithImplicit.empty() &&
  2396. "No clauses are allowed for 'omp ordered' directive");
  2397. Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
  2398. break;
  2399. case OMPD_atomic:
  2400. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2401. EndLoc);
  2402. break;
  2403. case OMPD_teams:
  2404. Res =
  2405. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2406. break;
  2407. case OMPD_target:
  2408. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2409. EndLoc);
  2410. break;
  2411. case OMPD_cancellation_point:
  2412. assert(ClausesWithImplicit.empty() &&
  2413. "No clauses are allowed for 'omp cancellation point' directive");
  2414. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2415. "cancellation point' directive");
  2416. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2417. break;
  2418. case OMPD_cancel:
  2419. assert(ClausesWithImplicit.empty() &&
  2420. "No clauses are allowed for 'omp cancel' directive");
  2421. assert(AStmt == nullptr &&
  2422. "No associated statement allowed for 'omp cancel' directive");
  2423. Res = ActOnOpenMPCancelDirective(StartLoc, EndLoc, CancelRegion);
  2424. break;
  2425. case OMPD_threadprivate:
  2426. llvm_unreachable("OpenMP Directive is not allowed");
  2427. case OMPD_unknown:
  2428. llvm_unreachable("Unknown OpenMP directive");
  2429. }
  2430. for (auto P : VarsWithInheritedDSA) {
  2431. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2432. << P.first << P.second->getSourceRange();
  2433. }
  2434. if (!VarsWithInheritedDSA.empty())
  2435. return StmtError();
  2436. if (ErrorFound)
  2437. return StmtError();
  2438. return Res;
  2439. }
  2440. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  2441. Stmt *AStmt,
  2442. SourceLocation StartLoc,
  2443. SourceLocation EndLoc) {
  2444. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2445. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  2446. // 1.2.2 OpenMP Language Terminology
  2447. // Structured block - An executable statement with a single entry at the
  2448. // top and a single exit at the bottom.
  2449. // The point of exit cannot be a branch out of the structured block.
  2450. // longjmp() and throw() must not violate the entry/exit criteria.
  2451. CS->getCapturedDecl()->setNothrow();
  2452. getCurFunction()->setHasBranchProtectedScope();
  2453. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  2454. AStmt);
  2455. }
  2456. namespace {
  2457. /// \brief Helper class for checking canonical form of the OpenMP loops and
  2458. /// extracting iteration space of each loop in the loop nest, that will be used
  2459. /// for IR generation.
  2460. class OpenMPIterationSpaceChecker {
  2461. /// \brief Reference to Sema.
  2462. Sema &SemaRef;
  2463. /// \brief A location for diagnostics (when there is no some better location).
  2464. SourceLocation DefaultLoc;
  2465. /// \brief A location for diagnostics (when increment is not compatible).
  2466. SourceLocation ConditionLoc;
  2467. /// \brief A source location for referring to loop init later.
  2468. SourceRange InitSrcRange;
  2469. /// \brief A source location for referring to condition later.
  2470. SourceRange ConditionSrcRange;
  2471. /// \brief A source location for referring to increment later.
  2472. SourceRange IncrementSrcRange;
  2473. /// \brief Loop variable.
  2474. VarDecl *Var;
  2475. /// \brief Reference to loop variable.
  2476. DeclRefExpr *VarRef;
  2477. /// \brief Lower bound (initializer for the var).
  2478. Expr *LB;
  2479. /// \brief Upper bound.
  2480. Expr *UB;
  2481. /// \brief Loop step (increment).
  2482. Expr *Step;
  2483. /// \brief This flag is true when condition is one of:
  2484. /// Var < UB
  2485. /// Var <= UB
  2486. /// UB > Var
  2487. /// UB >= Var
  2488. bool TestIsLessOp;
  2489. /// \brief This flag is true when condition is strict ( < or > ).
  2490. bool TestIsStrictOp;
  2491. /// \brief This flag is true when step is subtracted on each iteration.
  2492. bool SubtractStep;
  2493. public:
  2494. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  2495. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
  2496. InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
  2497. IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
  2498. LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
  2499. TestIsStrictOp(false), SubtractStep(false) {}
  2500. /// \brief Check init-expr for canonical loop form and save loop counter
  2501. /// variable - #Var and its initialization value - #LB.
  2502. bool CheckInit(Stmt *S, bool EmitDiags = true);
  2503. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  2504. /// for less/greater and for strict/non-strict comparison.
  2505. bool CheckCond(Expr *S);
  2506. /// \brief Check incr-expr for canonical loop form and return true if it
  2507. /// does not conform, otherwise save loop step (#Step).
  2508. bool CheckInc(Expr *S);
  2509. /// \brief Return the loop counter variable.
  2510. VarDecl *GetLoopVar() const { return Var; }
  2511. /// \brief Return the reference expression to loop counter variable.
  2512. DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
  2513. /// \brief Source range of the loop init.
  2514. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  2515. /// \brief Source range of the loop condition.
  2516. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  2517. /// \brief Source range of the loop increment.
  2518. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  2519. /// \brief True if the step should be subtracted.
  2520. bool ShouldSubtractStep() const { return SubtractStep; }
  2521. /// \brief Build the expression to calculate the number of iterations.
  2522. Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
  2523. /// \brief Build the precondition expression for the loops.
  2524. Expr *BuildPreCond(Scope *S, Expr *Cond) const;
  2525. /// \brief Build reference expression to the counter be used for codegen.
  2526. Expr *BuildCounterVar() const;
  2527. /// \brief Build initization of the counter be used for codegen.
  2528. Expr *BuildCounterInit() const;
  2529. /// \brief Build step of the counter be used for codegen.
  2530. Expr *BuildCounterStep() const;
  2531. /// \brief Return true if any expression is dependent.
  2532. bool Dependent() const;
  2533. private:
  2534. /// \brief Check the right-hand side of an assignment in the increment
  2535. /// expression.
  2536. bool CheckIncRHS(Expr *RHS);
  2537. /// \brief Helper to set loop counter variable and its initializer.
  2538. bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
  2539. /// \brief Helper to set upper bound.
  2540. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
  2541. const SourceLocation &SL);
  2542. /// \brief Helper to set loop increment.
  2543. bool SetStep(Expr *NewStep, bool Subtract);
  2544. };
  2545. bool OpenMPIterationSpaceChecker::Dependent() const {
  2546. if (!Var) {
  2547. assert(!LB && !UB && !Step);
  2548. return false;
  2549. }
  2550. return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
  2551. (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
  2552. }
  2553. template <typename T>
  2554. static T *getExprAsWritten(T *E) {
  2555. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  2556. E = ExprTemp->getSubExpr();
  2557. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  2558. E = MTE->GetTemporaryExpr();
  2559. while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  2560. E = Binder->getSubExpr();
  2561. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  2562. E = ICE->getSubExprAsWritten();
  2563. return E->IgnoreParens();
  2564. }
  2565. bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
  2566. DeclRefExpr *NewVarRefExpr,
  2567. Expr *NewLB) {
  2568. // State consistency checking to ensure correct usage.
  2569. assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
  2570. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  2571. if (!NewVar || !NewLB)
  2572. return true;
  2573. Var = NewVar;
  2574. VarRef = NewVarRefExpr;
  2575. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  2576. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  2577. if ((Ctor->isCopyOrMoveConstructor() ||
  2578. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  2579. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  2580. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  2581. LB = NewLB;
  2582. return false;
  2583. }
  2584. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  2585. const SourceRange &SR,
  2586. const SourceLocation &SL) {
  2587. // State consistency checking to ensure correct usage.
  2588. assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
  2589. !TestIsLessOp && !TestIsStrictOp);
  2590. if (!NewUB)
  2591. return true;
  2592. UB = NewUB;
  2593. TestIsLessOp = LessOp;
  2594. TestIsStrictOp = StrictOp;
  2595. ConditionSrcRange = SR;
  2596. ConditionLoc = SL;
  2597. return false;
  2598. }
  2599. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  2600. // State consistency checking to ensure correct usage.
  2601. assert(Var != nullptr && LB != nullptr && Step == nullptr);
  2602. if (!NewStep)
  2603. return true;
  2604. if (!NewStep->isValueDependent()) {
  2605. // Check that the step is integer expression.
  2606. SourceLocation StepLoc = NewStep->getLocStart();
  2607. ExprResult Val =
  2608. SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
  2609. if (Val.isInvalid())
  2610. return true;
  2611. NewStep = Val.get();
  2612. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  2613. // If test-expr is of form var relational-op b and relational-op is < or
  2614. // <= then incr-expr must cause var to increase on each iteration of the
  2615. // loop. If test-expr is of form var relational-op b and relational-op is
  2616. // > or >= then incr-expr must cause var to decrease on each iteration of
  2617. // the loop.
  2618. // If test-expr is of form b relational-op var and relational-op is < or
  2619. // <= then incr-expr must cause var to decrease on each iteration of the
  2620. // loop. If test-expr is of form b relational-op var and relational-op is
  2621. // > or >= then incr-expr must cause var to increase on each iteration of
  2622. // the loop.
  2623. llvm::APSInt Result;
  2624. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  2625. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  2626. bool IsConstNeg =
  2627. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  2628. bool IsConstPos =
  2629. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  2630. bool IsConstZero = IsConstant && !Result.getBoolValue();
  2631. if (UB && (IsConstZero ||
  2632. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  2633. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  2634. SemaRef.Diag(NewStep->getExprLoc(),
  2635. diag::err_omp_loop_incr_not_compatible)
  2636. << Var << TestIsLessOp << NewStep->getSourceRange();
  2637. SemaRef.Diag(ConditionLoc,
  2638. diag::note_omp_loop_cond_requres_compatible_incr)
  2639. << TestIsLessOp << ConditionSrcRange;
  2640. return true;
  2641. }
  2642. if (TestIsLessOp == Subtract) {
  2643. NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
  2644. NewStep).get();
  2645. Subtract = !Subtract;
  2646. }
  2647. }
  2648. Step = NewStep;
  2649. SubtractStep = Subtract;
  2650. return false;
  2651. }
  2652. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  2653. // Check init-expr for canonical loop form and save loop counter
  2654. // variable - #Var and its initialization value - #LB.
  2655. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  2656. // var = lb
  2657. // integer-type var = lb
  2658. // random-access-iterator-type var = lb
  2659. // pointer-type var = lb
  2660. //
  2661. if (!S) {
  2662. if (EmitDiags) {
  2663. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  2664. }
  2665. return true;
  2666. }
  2667. InitSrcRange = S->getSourceRange();
  2668. if (Expr *E = dyn_cast<Expr>(S))
  2669. S = E->IgnoreParens();
  2670. if (auto BO = dyn_cast<BinaryOperator>(S)) {
  2671. if (BO->getOpcode() == BO_Assign)
  2672. if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
  2673. return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
  2674. BO->getRHS());
  2675. } else if (auto DS = dyn_cast<DeclStmt>(S)) {
  2676. if (DS->isSingleDecl()) {
  2677. if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  2678. if (Var->hasInit()) {
  2679. // Accept non-canonical init form here but emit ext. warning.
  2680. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  2681. SemaRef.Diag(S->getLocStart(),
  2682. diag::ext_omp_loop_not_canonical_init)
  2683. << S->getSourceRange();
  2684. return SetVarAndLB(Var, nullptr, Var->getInit());
  2685. }
  2686. }
  2687. }
  2688. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
  2689. if (CE->getOperator() == OO_Equal)
  2690. if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
  2691. return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
  2692. CE->getArg(1));
  2693. if (EmitDiags) {
  2694. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  2695. << S->getSourceRange();
  2696. }
  2697. return true;
  2698. }
  2699. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  2700. /// variable (which may be the loop variable) if possible.
  2701. static const VarDecl *GetInitVarDecl(const Expr *E) {
  2702. if (!E)
  2703. return nullptr;
  2704. E = getExprAsWritten(E);
  2705. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  2706. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  2707. if ((Ctor->isCopyOrMoveConstructor() ||
  2708. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  2709. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  2710. E = CE->getArg(0)->IgnoreParenImpCasts();
  2711. auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
  2712. if (!DRE)
  2713. return nullptr;
  2714. return dyn_cast<VarDecl>(DRE->getDecl());
  2715. }
  2716. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  2717. // Check test-expr for canonical form, save upper-bound UB, flags for
  2718. // less/greater and for strict/non-strict comparison.
  2719. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  2720. // var relational-op b
  2721. // b relational-op var
  2722. //
  2723. if (!S) {
  2724. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
  2725. return true;
  2726. }
  2727. S = getExprAsWritten(S);
  2728. SourceLocation CondLoc = S->getLocStart();
  2729. if (auto BO = dyn_cast<BinaryOperator>(S)) {
  2730. if (BO->isRelationalOp()) {
  2731. if (GetInitVarDecl(BO->getLHS()) == Var)
  2732. return SetUB(BO->getRHS(),
  2733. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  2734. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  2735. BO->getSourceRange(), BO->getOperatorLoc());
  2736. if (GetInitVarDecl(BO->getRHS()) == Var)
  2737. return SetUB(BO->getLHS(),
  2738. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  2739. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  2740. BO->getSourceRange(), BO->getOperatorLoc());
  2741. }
  2742. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2743. if (CE->getNumArgs() == 2) {
  2744. auto Op = CE->getOperator();
  2745. switch (Op) {
  2746. case OO_Greater:
  2747. case OO_GreaterEqual:
  2748. case OO_Less:
  2749. case OO_LessEqual:
  2750. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2751. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  2752. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  2753. CE->getOperatorLoc());
  2754. if (GetInitVarDecl(CE->getArg(1)) == Var)
  2755. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  2756. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  2757. CE->getOperatorLoc());
  2758. break;
  2759. default:
  2760. break;
  2761. }
  2762. }
  2763. }
  2764. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  2765. << S->getSourceRange() << Var;
  2766. return true;
  2767. }
  2768. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  2769. // RHS of canonical loop form increment can be:
  2770. // var + incr
  2771. // incr + var
  2772. // var - incr
  2773. //
  2774. RHS = RHS->IgnoreParenImpCasts();
  2775. if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
  2776. if (BO->isAdditiveOp()) {
  2777. bool IsAdd = BO->getOpcode() == BO_Add;
  2778. if (GetInitVarDecl(BO->getLHS()) == Var)
  2779. return SetStep(BO->getRHS(), !IsAdd);
  2780. if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
  2781. return SetStep(BO->getLHS(), false);
  2782. }
  2783. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  2784. bool IsAdd = CE->getOperator() == OO_Plus;
  2785. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  2786. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2787. return SetStep(CE->getArg(1), !IsAdd);
  2788. if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
  2789. return SetStep(CE->getArg(0), false);
  2790. }
  2791. }
  2792. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  2793. << RHS->getSourceRange() << Var;
  2794. return true;
  2795. }
  2796. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  2797. // Check incr-expr for canonical loop form and return true if it
  2798. // does not conform.
  2799. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  2800. // ++var
  2801. // var++
  2802. // --var
  2803. // var--
  2804. // var += incr
  2805. // var -= incr
  2806. // var = var + incr
  2807. // var = incr + var
  2808. // var = var - incr
  2809. //
  2810. if (!S) {
  2811. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
  2812. return true;
  2813. }
  2814. IncrementSrcRange = S->getSourceRange();
  2815. S = S->IgnoreParens();
  2816. if (auto UO = dyn_cast<UnaryOperator>(S)) {
  2817. if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
  2818. return SetStep(
  2819. SemaRef.ActOnIntegerConstant(UO->getLocStart(),
  2820. (UO->isDecrementOp() ? -1 : 1)).get(),
  2821. false);
  2822. } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
  2823. switch (BO->getOpcode()) {
  2824. case BO_AddAssign:
  2825. case BO_SubAssign:
  2826. if (GetInitVarDecl(BO->getLHS()) == Var)
  2827. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  2828. break;
  2829. case BO_Assign:
  2830. if (GetInitVarDecl(BO->getLHS()) == Var)
  2831. return CheckIncRHS(BO->getRHS());
  2832. break;
  2833. default:
  2834. break;
  2835. }
  2836. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2837. switch (CE->getOperator()) {
  2838. case OO_PlusPlus:
  2839. case OO_MinusMinus:
  2840. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2841. return SetStep(
  2842. SemaRef.ActOnIntegerConstant(
  2843. CE->getLocStart(),
  2844. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
  2845. false);
  2846. break;
  2847. case OO_PlusEqual:
  2848. case OO_MinusEqual:
  2849. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2850. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  2851. break;
  2852. case OO_Equal:
  2853. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2854. return CheckIncRHS(CE->getArg(1));
  2855. break;
  2856. default:
  2857. break;
  2858. }
  2859. }
  2860. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  2861. << S->getSourceRange() << Var;
  2862. return true;
  2863. }
  2864. namespace {
  2865. // Transform variables declared in GNU statement expressions to new ones to
  2866. // avoid crash on codegen.
  2867. class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
  2868. typedef TreeTransform<TransformToNewDefs> BaseTransform;
  2869. public:
  2870. TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
  2871. Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
  2872. if (auto *VD = cast<VarDecl>(D))
  2873. if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
  2874. !isa<ImplicitParamDecl>(D)) {
  2875. auto *NewVD = VarDecl::Create(
  2876. SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
  2877. VD->getLocation(), VD->getIdentifier(), VD->getType(),
  2878. VD->getTypeSourceInfo(), VD->getStorageClass());
  2879. NewVD->setTSCSpec(VD->getTSCSpec());
  2880. NewVD->setInit(VD->getInit());
  2881. NewVD->setInitStyle(VD->getInitStyle());
  2882. NewVD->setExceptionVariable(VD->isExceptionVariable());
  2883. NewVD->setNRVOVariable(VD->isNRVOVariable());
  2884. NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
  2885. NewVD->setConstexpr(VD->isConstexpr());
  2886. NewVD->setInitCapture(VD->isInitCapture());
  2887. NewVD->setPreviousDeclInSameBlockScope(
  2888. VD->isPreviousDeclInSameBlockScope());
  2889. VD->getDeclContext()->addHiddenDecl(NewVD);
  2890. transformedLocalDecl(VD, NewVD);
  2891. return NewVD;
  2892. }
  2893. return BaseTransform::TransformDefinition(Loc, D);
  2894. }
  2895. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  2896. if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
  2897. if (E->getDecl() != NewD) {
  2898. NewD->setReferenced();
  2899. NewD->markUsed(SemaRef.Context);
  2900. return DeclRefExpr::Create(
  2901. SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
  2902. cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
  2903. E->getNameInfo(), E->getType(), E->getValueKind());
  2904. }
  2905. return BaseTransform::TransformDeclRefExpr(E);
  2906. }
  2907. };
  2908. }
  2909. /// \brief Build the expression to calculate the number of iterations.
  2910. Expr *
  2911. OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
  2912. const bool LimitedType) const {
  2913. TransformToNewDefs Transform(SemaRef);
  2914. ExprResult Diff;
  2915. auto VarType = Var->getType().getNonReferenceType();
  2916. if (VarType->isIntegerType() || VarType->isPointerType() ||
  2917. SemaRef.getLangOpts().CPlusPlus) {
  2918. // Upper - Lower
  2919. auto *UBExpr = TestIsLessOp ? UB : LB;
  2920. auto *LBExpr = TestIsLessOp ? LB : UB;
  2921. Expr *Upper = Transform.TransformExpr(UBExpr).get();
  2922. Expr *Lower = Transform.TransformExpr(LBExpr).get();
  2923. if (!Upper || !Lower)
  2924. return nullptr;
  2925. Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
  2926. Sema::AA_Converting,
  2927. /*AllowExplicit=*/true)
  2928. .get();
  2929. Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
  2930. Sema::AA_Converting,
  2931. /*AllowExplicit=*/true)
  2932. .get();
  2933. if (!Upper || !Lower)
  2934. return nullptr;
  2935. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  2936. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  2937. // BuildBinOp already emitted error, this one is to point user to upper
  2938. // and lower bound, and to tell what is passed to 'operator-'.
  2939. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  2940. << Upper->getSourceRange() << Lower->getSourceRange();
  2941. return nullptr;
  2942. }
  2943. }
  2944. if (!Diff.isUsable())
  2945. return nullptr;
  2946. // Upper - Lower [- 1]
  2947. if (TestIsStrictOp)
  2948. Diff = SemaRef.BuildBinOp(
  2949. S, DefaultLoc, BO_Sub, Diff.get(),
  2950. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  2951. if (!Diff.isUsable())
  2952. return nullptr;
  2953. // Upper - Lower [- 1] + Step
  2954. auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
  2955. if (NewStep.isInvalid())
  2956. return nullptr;
  2957. NewStep = SemaRef.PerformImplicitConversion(
  2958. NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
  2959. /*AllowExplicit=*/true);
  2960. if (NewStep.isInvalid())
  2961. return nullptr;
  2962. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  2963. if (!Diff.isUsable())
  2964. return nullptr;
  2965. // Parentheses (for dumping/debugging purposes only).
  2966. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  2967. if (!Diff.isUsable())
  2968. return nullptr;
  2969. // (Upper - Lower [- 1] + Step) / Step
  2970. NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
  2971. if (NewStep.isInvalid())
  2972. return nullptr;
  2973. NewStep = SemaRef.PerformImplicitConversion(
  2974. NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
  2975. /*AllowExplicit=*/true);
  2976. if (NewStep.isInvalid())
  2977. return nullptr;
  2978. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  2979. if (!Diff.isUsable())
  2980. return nullptr;
  2981. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  2982. QualType Type = Diff.get()->getType();
  2983. auto &C = SemaRef.Context;
  2984. bool UseVarType = VarType->hasIntegerRepresentation() &&
  2985. C.getTypeSize(Type) > C.getTypeSize(VarType);
  2986. if (!Type->isIntegerType() || UseVarType) {
  2987. unsigned NewSize =
  2988. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  2989. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  2990. : Type->hasSignedIntegerRepresentation();
  2991. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  2992. Diff = SemaRef.PerformImplicitConversion(
  2993. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  2994. if (!Diff.isUsable())
  2995. return nullptr;
  2996. }
  2997. if (LimitedType) {
  2998. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  2999. if (NewSize != C.getTypeSize(Type)) {
  3000. if (NewSize < C.getTypeSize(Type)) {
  3001. assert(NewSize == 64 && "incorrect loop var size");
  3002. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3003. << InitSrcRange << ConditionSrcRange;
  3004. }
  3005. QualType NewType = C.getIntTypeForBitwidth(
  3006. NewSize, Type->hasSignedIntegerRepresentation() ||
  3007. C.getTypeSize(Type) < NewSize);
  3008. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3009. Sema::AA_Converting, true);
  3010. if (!Diff.isUsable())
  3011. return nullptr;
  3012. }
  3013. }
  3014. return Diff.get();
  3015. }
  3016. Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
  3017. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3018. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3019. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3020. TransformToNewDefs Transform(SemaRef);
  3021. auto NewLB = Transform.TransformExpr(LB);
  3022. auto NewUB = Transform.TransformExpr(UB);
  3023. if (NewLB.isInvalid() || NewUB.isInvalid())
  3024. return Cond;
  3025. NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
  3026. Sema::AA_Converting,
  3027. /*AllowExplicit=*/true);
  3028. NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
  3029. Sema::AA_Converting,
  3030. /*AllowExplicit=*/true);
  3031. if (NewLB.isInvalid() || NewUB.isInvalid())
  3032. return Cond;
  3033. auto CondExpr = SemaRef.BuildBinOp(
  3034. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3035. : (TestIsStrictOp ? BO_GT : BO_GE),
  3036. NewLB.get(), NewUB.get());
  3037. if (CondExpr.isUsable()) {
  3038. CondExpr = SemaRef.PerformImplicitConversion(
  3039. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3040. /*AllowExplicit=*/true);
  3041. }
  3042. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3043. // Otherwise use original loop conditon and evaluate it in runtime.
  3044. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3045. }
  3046. /// \brief Build reference expression to the counter be used for codegen.
  3047. Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
  3048. return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
  3049. }
  3050. /// \brief Build initization of the counter be used for codegen.
  3051. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3052. /// \brief Build step of the counter be used for codegen.
  3053. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3054. /// \brief Iteration space of a single for loop.
  3055. struct LoopIterationSpace {
  3056. /// \brief Condition of the loop.
  3057. Expr *PreCond;
  3058. /// \brief This expression calculates the number of iterations in the loop.
  3059. /// It is always possible to calculate it before starting the loop.
  3060. Expr *NumIterations;
  3061. /// \brief The loop counter variable.
  3062. Expr *CounterVar;
  3063. /// \brief This is initializer for the initial value of #CounterVar.
  3064. Expr *CounterInit;
  3065. /// \brief This is step for the #CounterVar used to generate its update:
  3066. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3067. Expr *CounterStep;
  3068. /// \brief Should step be subtracted?
  3069. bool Subtract;
  3070. /// \brief Source range of the loop init.
  3071. SourceRange InitSrcRange;
  3072. /// \brief Source range of the loop condition.
  3073. SourceRange CondSrcRange;
  3074. /// \brief Source range of the loop increment.
  3075. SourceRange IncSrcRange;
  3076. };
  3077. } // namespace
  3078. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3079. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3080. assert(Init && "Expected loop in canonical form.");
  3081. unsigned CollapseIteration = DSAStack->getCollapseNumber();
  3082. if (CollapseIteration > 0 &&
  3083. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3084. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3085. if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
  3086. DSAStack->addLoopControlVariable(ISC.GetLoopVar());
  3087. }
  3088. DSAStack->setCollapseNumber(CollapseIteration - 1);
  3089. }
  3090. }
  3091. /// \brief Called on a for stmt to check and extract its iteration space
  3092. /// for further processing (such as collapsing).
  3093. static bool CheckOpenMPIterationSpace(
  3094. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3095. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3096. Expr *NestedLoopCountExpr,
  3097. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
  3098. LoopIterationSpace &ResultIterSpace) {
  3099. // OpenMP [2.6, Canonical Loop Form]
  3100. // for (init-expr; test-expr; incr-expr) structured-block
  3101. auto For = dyn_cast_or_null<ForStmt>(S);
  3102. if (!For) {
  3103. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3104. << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
  3105. << NestedLoopCount << (CurrentNestedLoopCount > 0)
  3106. << CurrentNestedLoopCount;
  3107. if (NestedLoopCount > 1)
  3108. SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
  3109. diag::note_omp_collapse_expr)
  3110. << NestedLoopCountExpr->getSourceRange();
  3111. return true;
  3112. }
  3113. assert(For->getBody());
  3114. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3115. // Check init.
  3116. auto Init = For->getInit();
  3117. if (ISC.CheckInit(Init)) {
  3118. return true;
  3119. }
  3120. bool HasErrors = false;
  3121. // Check loop variable's type.
  3122. auto Var = ISC.GetLoopVar();
  3123. // OpenMP [2.6, Canonical Loop Form]
  3124. // Var is one of the following:
  3125. // A variable of signed or unsigned integer type.
  3126. // For C++, a variable of a random access iterator type.
  3127. // For C, a variable of a pointer type.
  3128. auto VarType = Var->getType();
  3129. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3130. !VarType->isPointerType() &&
  3131. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3132. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3133. << SemaRef.getLangOpts().CPlusPlus;
  3134. HasErrors = true;
  3135. }
  3136. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
  3137. // Construct
  3138. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3139. // parallel for construct is (are) private.
  3140. // The loop iteration variable in the associated for-loop of a simd construct
  3141. // with just one associated for-loop is linear with a constant-linear-step
  3142. // that is the increment of the associated for-loop.
  3143. // Exclude loop var from the list of variables with implicitly defined data
  3144. // sharing attributes.
  3145. VarsWithImplicitDSA.erase(Var);
  3146. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
  3147. // a Construct, C/C++].
  3148. // The loop iteration variable in the associated for-loop of a simd construct
  3149. // with just one associated for-loop may be listed in a linear clause with a
  3150. // constant-linear-step that is the increment of the associated for-loop.
  3151. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3152. // parallel for construct may be listed in a private or lastprivate clause.
  3153. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
  3154. auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
  3155. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3156. // declared in the loop and it is predetermined as a private.
  3157. auto PredeterminedCKind =
  3158. isOpenMPSimdDirective(DKind)
  3159. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3160. : OMPC_private;
  3161. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3162. DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
  3163. (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
  3164. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
  3165. DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
  3166. ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
  3167. DVar.RefExpr != nullptr)) {
  3168. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3169. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3170. << getOpenMPClauseName(PredeterminedCKind);
  3171. if (DVar.RefExpr == nullptr)
  3172. DVar.CKind = PredeterminedCKind;
  3173. ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
  3174. HasErrors = true;
  3175. } else if (LoopVarRefExpr != nullptr) {
  3176. // Make the loop iteration variable private (for worksharing constructs),
  3177. // linear (for simd directives with the only one associated loop) or
  3178. // lastprivate (for simd directives with several collapsed loops).
  3179. if (DVar.CKind == OMPC_unknown)
  3180. DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
  3181. /*FromParent=*/false);
  3182. DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
  3183. }
  3184. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3185. // Check test-expr.
  3186. HasErrors |= ISC.CheckCond(For->getCond());
  3187. // Check incr-expr.
  3188. HasErrors |= ISC.CheckInc(For->getInc());
  3189. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  3190. return HasErrors;
  3191. // Build the loop's iteration space representation.
  3192. ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
  3193. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  3194. DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
  3195. ResultIterSpace.CounterVar = ISC.BuildCounterVar();
  3196. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  3197. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  3198. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  3199. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  3200. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  3201. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  3202. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  3203. ResultIterSpace.NumIterations == nullptr ||
  3204. ResultIterSpace.CounterVar == nullptr ||
  3205. ResultIterSpace.CounterInit == nullptr ||
  3206. ResultIterSpace.CounterStep == nullptr);
  3207. return HasErrors;
  3208. }
  3209. /// \brief Build 'VarRef = Start.
  3210. static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
  3211. ExprResult VarRef, ExprResult Start) {
  3212. TransformToNewDefs Transform(SemaRef);
  3213. // Build 'VarRef = Start.
  3214. auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
  3215. if (NewStart.isInvalid())
  3216. return ExprError();
  3217. NewStart = SemaRef.PerformImplicitConversion(
  3218. NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
  3219. Sema::AA_Converting,
  3220. /*AllowExplicit=*/true);
  3221. if (NewStart.isInvalid())
  3222. return ExprError();
  3223. NewStart = SemaRef.PerformImplicitConversion(
  3224. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  3225. /*AllowExplicit=*/true);
  3226. if (!NewStart.isUsable())
  3227. return ExprError();
  3228. auto Init =
  3229. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  3230. return Init;
  3231. }
  3232. /// \brief Build 'VarRef = Start + Iter * Step'.
  3233. static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
  3234. SourceLocation Loc, ExprResult VarRef,
  3235. ExprResult Start, ExprResult Iter,
  3236. ExprResult Step, bool Subtract) {
  3237. // Add parentheses (for debugging purposes only).
  3238. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  3239. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  3240. !Step.isUsable())
  3241. return ExprError();
  3242. TransformToNewDefs Transform(SemaRef);
  3243. auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
  3244. if (NewStep.isInvalid())
  3245. return ExprError();
  3246. NewStep = SemaRef.PerformImplicitConversion(
  3247. NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
  3248. Sema::AA_Converting,
  3249. /*AllowExplicit=*/true);
  3250. if (NewStep.isInvalid())
  3251. return ExprError();
  3252. ExprResult Update =
  3253. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  3254. if (!Update.isUsable())
  3255. return ExprError();
  3256. // Build 'VarRef = Start + Iter * Step'.
  3257. auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
  3258. if (NewStart.isInvalid())
  3259. return ExprError();
  3260. NewStart = SemaRef.PerformImplicitConversion(
  3261. NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
  3262. Sema::AA_Converting,
  3263. /*AllowExplicit=*/true);
  3264. if (NewStart.isInvalid())
  3265. return ExprError();
  3266. Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
  3267. NewStart.get(), Update.get());
  3268. if (!Update.isUsable())
  3269. return ExprError();
  3270. Update = SemaRef.PerformImplicitConversion(
  3271. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  3272. if (!Update.isUsable())
  3273. return ExprError();
  3274. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  3275. return Update;
  3276. }
  3277. /// \brief Convert integer expression \a E to make it have at least \a Bits
  3278. /// bits.
  3279. static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
  3280. Sema &SemaRef) {
  3281. if (E == nullptr)
  3282. return ExprError();
  3283. auto &C = SemaRef.Context;
  3284. QualType OldType = E->getType();
  3285. unsigned HasBits = C.getTypeSize(OldType);
  3286. if (HasBits >= Bits)
  3287. return ExprResult(E);
  3288. // OK to convert to signed, because new type has more bits than old.
  3289. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  3290. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  3291. true);
  3292. }
  3293. /// \brief Check if the given expression \a E is a constant integer that fits
  3294. /// into \a Bits bits.
  3295. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  3296. if (E == nullptr)
  3297. return false;
  3298. llvm::APSInt Result;
  3299. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  3300. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  3301. return false;
  3302. }
  3303. /// \brief Called on a for stmt to check itself and nested loops (if any).
  3304. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  3305. /// number of collapsed loops otherwise.
  3306. static unsigned
  3307. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
  3308. Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
  3309. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
  3310. OMPLoopDirective::HelperExprs &Built) {
  3311. unsigned NestedLoopCount = 1;
  3312. if (NestedLoopCountExpr) {
  3313. // Found 'collapse' clause - calculate collapse number.
  3314. llvm::APSInt Result;
  3315. if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  3316. NestedLoopCount = Result.getLimitedValue();
  3317. }
  3318. // This is helper routine for loop directives (e.g., 'for', 'simd',
  3319. // 'for simd', etc.).
  3320. SmallVector<LoopIterationSpace, 4> IterSpaces;
  3321. IterSpaces.resize(NestedLoopCount);
  3322. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  3323. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  3324. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  3325. NestedLoopCount, NestedLoopCountExpr,
  3326. VarsWithImplicitDSA, IterSpaces[Cnt]))
  3327. return 0;
  3328. // Move on to the next nested for loop, or to the loop body.
  3329. // OpenMP [2.8.1, simd construct, Restrictions]
  3330. // All loops associated with the construct must be perfectly nested; that
  3331. // is, there must be no intervening code nor any OpenMP directive between
  3332. // any two loops.
  3333. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  3334. }
  3335. Built.clear(/* size */ NestedLoopCount);
  3336. if (SemaRef.CurContext->isDependentContext())
  3337. return NestedLoopCount;
  3338. // An example of what is generated for the following code:
  3339. //
  3340. // #pragma omp simd collapse(2)
  3341. // for (i = 0; i < NI; ++i)
  3342. // for (j = J0; j < NJ; j+=2) {
  3343. // <loop body>
  3344. // }
  3345. //
  3346. // We generate the code below.
  3347. // Note: the loop body may be outlined in CodeGen.
  3348. // Note: some counters may be C++ classes, operator- is used to find number of
  3349. // iterations and operator+= to calculate counter value.
  3350. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  3351. // or i64 is currently supported).
  3352. //
  3353. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  3354. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  3355. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  3356. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  3357. // // similar updates for vars in clauses (e.g. 'linear')
  3358. // <loop body (using local i and j)>
  3359. // }
  3360. // i = NI; // assign final values of counters
  3361. // j = NJ;
  3362. //
  3363. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  3364. // the iteration counts of the collapsed for loops.
  3365. // Precondition tests if there is at least one iteration (all conditions are
  3366. // true).
  3367. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  3368. auto N0 = IterSpaces[0].NumIterations;
  3369. ExprResult LastIteration32 = WidenIterationCount(
  3370. 32 /* Bits */, SemaRef.PerformImplicitConversion(
  3371. N0->IgnoreImpCasts(), N0->getType(),
  3372. Sema::AA_Converting, /*AllowExplicit=*/true)
  3373. .get(),
  3374. SemaRef);
  3375. ExprResult LastIteration64 = WidenIterationCount(
  3376. 64 /* Bits */, SemaRef.PerformImplicitConversion(
  3377. N0->IgnoreImpCasts(), N0->getType(),
  3378. Sema::AA_Converting, /*AllowExplicit=*/true)
  3379. .get(),
  3380. SemaRef);
  3381. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  3382. return NestedLoopCount;
  3383. auto &C = SemaRef.Context;
  3384. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  3385. Scope *CurScope = DSA.getCurScope();
  3386. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  3387. if (PreCond.isUsable()) {
  3388. PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
  3389. PreCond.get(), IterSpaces[Cnt].PreCond);
  3390. }
  3391. auto N = IterSpaces[Cnt].NumIterations;
  3392. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  3393. if (LastIteration32.isUsable())
  3394. LastIteration32 = SemaRef.BuildBinOp(
  3395. CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
  3396. SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  3397. Sema::AA_Converting,
  3398. /*AllowExplicit=*/true)
  3399. .get());
  3400. if (LastIteration64.isUsable())
  3401. LastIteration64 = SemaRef.BuildBinOp(
  3402. CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
  3403. SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  3404. Sema::AA_Converting,
  3405. /*AllowExplicit=*/true)
  3406. .get());
  3407. }
  3408. // Choose either the 32-bit or 64-bit version.
  3409. ExprResult LastIteration = LastIteration64;
  3410. if (LastIteration32.isUsable() &&
  3411. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  3412. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  3413. FitsInto(
  3414. 32 /* Bits */,
  3415. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  3416. LastIteration64.get(), SemaRef)))
  3417. LastIteration = LastIteration32;
  3418. if (!LastIteration.isUsable())
  3419. return 0;
  3420. // Save the number of iterations.
  3421. ExprResult NumIterations = LastIteration;
  3422. {
  3423. LastIteration = SemaRef.BuildBinOp(
  3424. CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
  3425. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3426. if (!LastIteration.isUsable())
  3427. return 0;
  3428. }
  3429. // Calculate the last iteration number beforehand instead of doing this on
  3430. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  3431. llvm::APSInt Result;
  3432. bool IsConstant =
  3433. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  3434. ExprResult CalcLastIteration;
  3435. if (!IsConstant) {
  3436. SourceLocation SaveLoc;
  3437. VarDecl *SaveVar =
  3438. buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
  3439. ".omp.last.iteration");
  3440. ExprResult SaveRef = buildDeclRefExpr(
  3441. SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
  3442. CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
  3443. SaveRef.get(), LastIteration.get());
  3444. LastIteration = SaveRef;
  3445. // Prepare SaveRef + 1.
  3446. NumIterations = SemaRef.BuildBinOp(
  3447. CurScope, SaveLoc, BO_Add, SaveRef.get(),
  3448. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3449. if (!NumIterations.isUsable())
  3450. return 0;
  3451. }
  3452. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  3453. QualType VType = LastIteration.get()->getType();
  3454. // Build variables passed into runtime, nesessary for worksharing directives.
  3455. ExprResult LB, UB, IL, ST, EUB;
  3456. if (isOpenMPWorksharingDirective(DKind)) {
  3457. // Lower bound variable, initialized with zero.
  3458. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  3459. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  3460. SemaRef.AddInitializerToDecl(
  3461. LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  3462. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3463. // Upper bound variable, initialized with last iteration number.
  3464. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  3465. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  3466. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  3467. /*DirectInit*/ false,
  3468. /*TypeMayContainAuto*/ false);
  3469. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  3470. // This will be used to implement clause 'lastprivate'.
  3471. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  3472. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  3473. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  3474. SemaRef.AddInitializerToDecl(
  3475. ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  3476. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3477. // Stride variable returned by runtime (we initialize it to 1 by default).
  3478. VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
  3479. ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
  3480. SemaRef.AddInitializerToDecl(
  3481. STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  3482. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3483. // Build expression: UB = min(UB, LastIteration)
  3484. // It is nesessary for CodeGen of directives with static scheduling.
  3485. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  3486. UB.get(), LastIteration.get());
  3487. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  3488. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  3489. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  3490. CondOp.get());
  3491. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  3492. }
  3493. // Build the iteration variable and its initialization before loop.
  3494. ExprResult IV;
  3495. ExprResult Init;
  3496. {
  3497. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
  3498. IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
  3499. Expr *RHS = isOpenMPWorksharingDirective(DKind)
  3500. ? LB.get()
  3501. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  3502. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  3503. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  3504. }
  3505. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  3506. SourceLocation CondLoc;
  3507. ExprResult Cond =
  3508. isOpenMPWorksharingDirective(DKind)
  3509. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  3510. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  3511. NumIterations.get());
  3512. // Loop increment (IV = IV + 1)
  3513. SourceLocation IncLoc;
  3514. ExprResult Inc =
  3515. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  3516. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  3517. if (!Inc.isUsable())
  3518. return 0;
  3519. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  3520. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  3521. if (!Inc.isUsable())
  3522. return 0;
  3523. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  3524. // Used for directives with static scheduling.
  3525. ExprResult NextLB, NextUB;
  3526. if (isOpenMPWorksharingDirective(DKind)) {
  3527. // LB + ST
  3528. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  3529. if (!NextLB.isUsable())
  3530. return 0;
  3531. // LB = LB + ST
  3532. NextLB =
  3533. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  3534. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  3535. if (!NextLB.isUsable())
  3536. return 0;
  3537. // UB + ST
  3538. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  3539. if (!NextUB.isUsable())
  3540. return 0;
  3541. // UB = UB + ST
  3542. NextUB =
  3543. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  3544. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  3545. if (!NextUB.isUsable())
  3546. return 0;
  3547. }
  3548. // Build updates and final values of the loop counters.
  3549. bool HasErrors = false;
  3550. Built.Counters.resize(NestedLoopCount);
  3551. Built.Inits.resize(NestedLoopCount);
  3552. Built.Updates.resize(NestedLoopCount);
  3553. Built.Finals.resize(NestedLoopCount);
  3554. {
  3555. ExprResult Div;
  3556. // Go from inner nested loop to outer.
  3557. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  3558. LoopIterationSpace &IS = IterSpaces[Cnt];
  3559. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  3560. // Build: Iter = (IV / Div) % IS.NumIters
  3561. // where Div is product of previous iterations' IS.NumIters.
  3562. ExprResult Iter;
  3563. if (Div.isUsable()) {
  3564. Iter =
  3565. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  3566. } else {
  3567. Iter = IV;
  3568. assert((Cnt == (int)NestedLoopCount - 1) &&
  3569. "unusable div expected on first iteration only");
  3570. }
  3571. if (Cnt != 0 && Iter.isUsable())
  3572. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  3573. IS.NumIterations);
  3574. if (!Iter.isUsable()) {
  3575. HasErrors = true;
  3576. break;
  3577. }
  3578. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  3579. auto *CounterVar = buildDeclRefExpr(
  3580. SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
  3581. IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  3582. /*RefersToCapture=*/true);
  3583. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  3584. IS.CounterInit);
  3585. if (!Init.isUsable()) {
  3586. HasErrors = true;
  3587. break;
  3588. }
  3589. ExprResult Update =
  3590. BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  3591. IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
  3592. if (!Update.isUsable()) {
  3593. HasErrors = true;
  3594. break;
  3595. }
  3596. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  3597. ExprResult Final = BuildCounterUpdate(
  3598. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  3599. IS.NumIterations, IS.CounterStep, IS.Subtract);
  3600. if (!Final.isUsable()) {
  3601. HasErrors = true;
  3602. break;
  3603. }
  3604. // Build Div for the next iteration: Div <- Div * IS.NumIters
  3605. if (Cnt != 0) {
  3606. if (Div.isUnset())
  3607. Div = IS.NumIterations;
  3608. else
  3609. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  3610. IS.NumIterations);
  3611. // Add parentheses (for debugging purposes only).
  3612. if (Div.isUsable())
  3613. Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
  3614. if (!Div.isUsable()) {
  3615. HasErrors = true;
  3616. break;
  3617. }
  3618. }
  3619. if (!Update.isUsable() || !Final.isUsable()) {
  3620. HasErrors = true;
  3621. break;
  3622. }
  3623. // Save results
  3624. Built.Counters[Cnt] = IS.CounterVar;
  3625. Built.Inits[Cnt] = Init.get();
  3626. Built.Updates[Cnt] = Update.get();
  3627. Built.Finals[Cnt] = Final.get();
  3628. }
  3629. }
  3630. if (HasErrors)
  3631. return 0;
  3632. // Save results
  3633. Built.IterationVarRef = IV.get();
  3634. Built.LastIteration = LastIteration.get();
  3635. Built.NumIterations = NumIterations.get();
  3636. Built.CalcLastIteration =
  3637. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  3638. Built.PreCond = PreCond.get();
  3639. Built.Cond = Cond.get();
  3640. Built.Init = Init.get();
  3641. Built.Inc = Inc.get();
  3642. Built.LB = LB.get();
  3643. Built.UB = UB.get();
  3644. Built.IL = IL.get();
  3645. Built.ST = ST.get();
  3646. Built.EUB = EUB.get();
  3647. Built.NLB = NextLB.get();
  3648. Built.NUB = NextUB.get();
  3649. return NestedLoopCount;
  3650. }
  3651. static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  3652. auto &&CollapseFilter = [](const OMPClause *C) -> bool {
  3653. return C->getClauseKind() == OMPC_collapse;
  3654. };
  3655. OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
  3656. Clauses, std::move(CollapseFilter));
  3657. if (I)
  3658. return cast<OMPCollapseClause>(*I)->getNumForLoops();
  3659. return nullptr;
  3660. }
  3661. StmtResult Sema::ActOnOpenMPSimdDirective(
  3662. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3663. SourceLocation EndLoc,
  3664. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3665. OMPLoopDirective::HelperExprs B;
  3666. // In presence of clause 'collapse', it will define the nested loops number.
  3667. unsigned NestedLoopCount =
  3668. CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
  3669. *DSAStack, VarsWithImplicitDSA, B);
  3670. if (NestedLoopCount == 0)
  3671. return StmtError();
  3672. assert((CurContext->isDependentContext() || B.builtAll()) &&
  3673. "omp simd loop exprs were not built");
  3674. if (!CurContext->isDependentContext()) {
  3675. // Finalize the clauses that need pre-built expressions for CodeGen.
  3676. for (auto C : Clauses) {
  3677. if (auto LC = dyn_cast<OMPLinearClause>(C))
  3678. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  3679. B.NumIterations, *this, CurScope))
  3680. return StmtError();
  3681. }
  3682. }
  3683. getCurFunction()->setHasBranchProtectedScope();
  3684. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  3685. Clauses, AStmt, B);
  3686. }
  3687. StmtResult Sema::ActOnOpenMPForDirective(
  3688. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3689. SourceLocation EndLoc,
  3690. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3691. OMPLoopDirective::HelperExprs B;
  3692. // In presence of clause 'collapse', it will define the nested loops number.
  3693. unsigned NestedLoopCount =
  3694. CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
  3695. *DSAStack, VarsWithImplicitDSA, B);
  3696. if (NestedLoopCount == 0)
  3697. return StmtError();
  3698. assert((CurContext->isDependentContext() || B.builtAll()) &&
  3699. "omp for loop exprs were not built");
  3700. getCurFunction()->setHasBranchProtectedScope();
  3701. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  3702. Clauses, AStmt, B);
  3703. }
  3704. StmtResult Sema::ActOnOpenMPForSimdDirective(
  3705. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3706. SourceLocation EndLoc,
  3707. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3708. OMPLoopDirective::HelperExprs B;
  3709. // In presence of clause 'collapse', it will define the nested loops number.
  3710. unsigned NestedLoopCount =
  3711. CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
  3712. *this, *DSAStack, VarsWithImplicitDSA, B);
  3713. if (NestedLoopCount == 0)
  3714. return StmtError();
  3715. assert((CurContext->isDependentContext() || B.builtAll()) &&
  3716. "omp for simd loop exprs were not built");
  3717. if (!CurContext->isDependentContext()) {
  3718. // Finalize the clauses that need pre-built expressions for CodeGen.
  3719. for (auto C : Clauses) {
  3720. if (auto LC = dyn_cast<OMPLinearClause>(C))
  3721. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  3722. B.NumIterations, *this, CurScope))
  3723. return StmtError();
  3724. }
  3725. }
  3726. getCurFunction()->setHasBranchProtectedScope();
  3727. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  3728. Clauses, AStmt, B);
  3729. }
  3730. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  3731. Stmt *AStmt,
  3732. SourceLocation StartLoc,
  3733. SourceLocation EndLoc) {
  3734. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3735. auto BaseStmt = AStmt;
  3736. while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  3737. BaseStmt = CS->getCapturedStmt();
  3738. if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  3739. auto S = C->children();
  3740. if (!S)
  3741. return StmtError();
  3742. // All associated statements must be '#pragma omp section' except for
  3743. // the first one.
  3744. for (Stmt *SectionStmt : ++S) {
  3745. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  3746. if (SectionStmt)
  3747. Diag(SectionStmt->getLocStart(),
  3748. diag::err_omp_sections_substmt_not_section);
  3749. return StmtError();
  3750. }
  3751. }
  3752. } else {
  3753. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  3754. return StmtError();
  3755. }
  3756. getCurFunction()->setHasBranchProtectedScope();
  3757. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  3758. AStmt);
  3759. }
  3760. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  3761. SourceLocation StartLoc,
  3762. SourceLocation EndLoc) {
  3763. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3764. getCurFunction()->setHasBranchProtectedScope();
  3765. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
  3766. }
  3767. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  3768. Stmt *AStmt,
  3769. SourceLocation StartLoc,
  3770. SourceLocation EndLoc) {
  3771. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3772. getCurFunction()->setHasBranchProtectedScope();
  3773. // OpenMP [2.7.3, single Construct, Restrictions]
  3774. // The copyprivate clause must not be used with the nowait clause.
  3775. OMPClause *Nowait = nullptr;
  3776. OMPClause *Copyprivate = nullptr;
  3777. for (auto *Clause : Clauses) {
  3778. if (Clause->getClauseKind() == OMPC_nowait)
  3779. Nowait = Clause;
  3780. else if (Clause->getClauseKind() == OMPC_copyprivate)
  3781. Copyprivate = Clause;
  3782. if (Copyprivate && Nowait) {
  3783. Diag(Copyprivate->getLocStart(),
  3784. diag::err_omp_single_copyprivate_with_nowait);
  3785. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  3786. return StmtError();
  3787. }
  3788. }
  3789. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  3790. }
  3791. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  3792. SourceLocation StartLoc,
  3793. SourceLocation EndLoc) {
  3794. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3795. getCurFunction()->setHasBranchProtectedScope();
  3796. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  3797. }
  3798. StmtResult
  3799. Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
  3800. Stmt *AStmt, SourceLocation StartLoc,
  3801. SourceLocation EndLoc) {
  3802. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3803. getCurFunction()->setHasBranchProtectedScope();
  3804. return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  3805. AStmt);
  3806. }
  3807. StmtResult Sema::ActOnOpenMPParallelForDirective(
  3808. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3809. SourceLocation EndLoc,
  3810. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3811. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3812. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3813. // 1.2.2 OpenMP Language Terminology
  3814. // Structured block - An executable statement with a single entry at the
  3815. // top and a single exit at the bottom.
  3816. // The point of exit cannot be a branch out of the structured block.
  3817. // longjmp() and throw() must not violate the entry/exit criteria.
  3818. CS->getCapturedDecl()->setNothrow();
  3819. OMPLoopDirective::HelperExprs B;
  3820. // In presence of clause 'collapse', it will define the nested loops number.
  3821. unsigned NestedLoopCount =
  3822. CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
  3823. *this, *DSAStack, VarsWithImplicitDSA, B);
  3824. if (NestedLoopCount == 0)
  3825. return StmtError();
  3826. assert((CurContext->isDependentContext() || B.builtAll()) &&
  3827. "omp parallel for loop exprs were not built");
  3828. getCurFunction()->setHasBranchProtectedScope();
  3829. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  3830. NestedLoopCount, Clauses, AStmt, B);
  3831. }
  3832. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  3833. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3834. SourceLocation EndLoc,
  3835. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3836. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3837. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3838. // 1.2.2 OpenMP Language Terminology
  3839. // Structured block - An executable statement with a single entry at the
  3840. // top and a single exit at the bottom.
  3841. // The point of exit cannot be a branch out of the structured block.
  3842. // longjmp() and throw() must not violate the entry/exit criteria.
  3843. CS->getCapturedDecl()->setNothrow();
  3844. OMPLoopDirective::HelperExprs B;
  3845. // In presence of clause 'collapse', it will define the nested loops number.
  3846. unsigned NestedLoopCount =
  3847. CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
  3848. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  3849. if (NestedLoopCount == 0)
  3850. return StmtError();
  3851. if (!CurContext->isDependentContext()) {
  3852. // Finalize the clauses that need pre-built expressions for CodeGen.
  3853. for (auto C : Clauses) {
  3854. if (auto LC = dyn_cast<OMPLinearClause>(C))
  3855. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  3856. B.NumIterations, *this, CurScope))
  3857. return StmtError();
  3858. }
  3859. }
  3860. getCurFunction()->setHasBranchProtectedScope();
  3861. return OMPParallelForSimdDirective::Create(
  3862. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  3863. }
  3864. StmtResult
  3865. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  3866. Stmt *AStmt, SourceLocation StartLoc,
  3867. SourceLocation EndLoc) {
  3868. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3869. auto BaseStmt = AStmt;
  3870. while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  3871. BaseStmt = CS->getCapturedStmt();
  3872. if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  3873. auto S = C->children();
  3874. if (!S)
  3875. return StmtError();
  3876. // All associated statements must be '#pragma omp section' except for
  3877. // the first one.
  3878. for (Stmt *SectionStmt : ++S) {
  3879. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  3880. if (SectionStmt)
  3881. Diag(SectionStmt->getLocStart(),
  3882. diag::err_omp_parallel_sections_substmt_not_section);
  3883. return StmtError();
  3884. }
  3885. }
  3886. } else {
  3887. Diag(AStmt->getLocStart(),
  3888. diag::err_omp_parallel_sections_not_compound_stmt);
  3889. return StmtError();
  3890. }
  3891. getCurFunction()->setHasBranchProtectedScope();
  3892. return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
  3893. Clauses, AStmt);
  3894. }
  3895. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  3896. Stmt *AStmt, SourceLocation StartLoc,
  3897. SourceLocation EndLoc) {
  3898. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3899. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3900. // 1.2.2 OpenMP Language Terminology
  3901. // Structured block - An executable statement with a single entry at the
  3902. // top and a single exit at the bottom.
  3903. // The point of exit cannot be a branch out of the structured block.
  3904. // longjmp() and throw() must not violate the entry/exit criteria.
  3905. CS->getCapturedDecl()->setNothrow();
  3906. getCurFunction()->setHasBranchProtectedScope();
  3907. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  3908. }
  3909. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  3910. SourceLocation EndLoc) {
  3911. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  3912. }
  3913. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  3914. SourceLocation EndLoc) {
  3915. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  3916. }
  3917. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  3918. SourceLocation EndLoc) {
  3919. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  3920. }
  3921. StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
  3922. SourceLocation StartLoc,
  3923. SourceLocation EndLoc) {
  3924. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3925. getCurFunction()->setHasBranchProtectedScope();
  3926. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
  3927. }
  3928. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  3929. SourceLocation StartLoc,
  3930. SourceLocation EndLoc) {
  3931. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  3932. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  3933. }
  3934. StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
  3935. SourceLocation StartLoc,
  3936. SourceLocation EndLoc) {
  3937. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3938. getCurFunction()->setHasBranchProtectedScope();
  3939. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
  3940. }
  3941. namespace {
  3942. /// \brief Helper class for checking expression in 'omp atomic [update]'
  3943. /// construct.
  3944. class OpenMPAtomicUpdateChecker {
  3945. /// \brief Error results for atomic update expressions.
  3946. enum ExprAnalysisErrorCode {
  3947. /// \brief A statement is not an expression statement.
  3948. NotAnExpression,
  3949. /// \brief Expression is not builtin binary or unary operation.
  3950. NotABinaryOrUnaryExpression,
  3951. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  3952. NotAnUnaryIncDecExpression,
  3953. /// \brief An expression is not of scalar type.
  3954. NotAScalarType,
  3955. /// \brief A binary operation is not an assignment operation.
  3956. NotAnAssignmentOp,
  3957. /// \brief RHS part of the binary operation is not a binary expression.
  3958. NotABinaryExpression,
  3959. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  3960. /// expression.
  3961. NotABinaryOperator,
  3962. /// \brief RHS binary operation does not have reference to the updated LHS
  3963. /// part.
  3964. NotAnUpdateExpression,
  3965. /// \brief No errors is found.
  3966. NoError
  3967. };
  3968. /// \brief Reference to Sema.
  3969. Sema &SemaRef;
  3970. /// \brief A location for note diagnostics (when error is found).
  3971. SourceLocation NoteLoc;
  3972. /// \brief 'x' lvalue part of the source atomic expression.
  3973. Expr *X;
  3974. /// \brief 'expr' rvalue part of the source atomic expression.
  3975. Expr *E;
  3976. /// \brief Helper expression of the form
  3977. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  3978. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  3979. Expr *UpdateExpr;
  3980. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  3981. /// important for non-associative operations.
  3982. bool IsXLHSInRHSPart;
  3983. BinaryOperatorKind Op;
  3984. SourceLocation OpLoc;
  3985. /// \brief true if the source expression is a postfix unary operation, false
  3986. /// if it is a prefix unary operation.
  3987. bool IsPostfixUpdate;
  3988. public:
  3989. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  3990. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  3991. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  3992. /// \brief Check specified statement that it is suitable for 'atomic update'
  3993. /// constructs and extract 'x', 'expr' and Operation from the original
  3994. /// expression. If DiagId and NoteId == 0, then only check is performed
  3995. /// without error notification.
  3996. /// \param DiagId Diagnostic which should be emitted if error is found.
  3997. /// \param NoteId Diagnostic note for the main error message.
  3998. /// \return true if statement is not an update expression, false otherwise.
  3999. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  4000. /// \brief Return the 'x' lvalue part of the source atomic expression.
  4001. Expr *getX() const { return X; }
  4002. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  4003. Expr *getExpr() const { return E; }
  4004. /// \brief Return the update expression used in calculation of the updated
  4005. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  4006. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  4007. Expr *getUpdateExpr() const { return UpdateExpr; }
  4008. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  4009. /// false otherwise.
  4010. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  4011. /// \brief true if the source expression is a postfix unary operation, false
  4012. /// if it is a prefix unary operation.
  4013. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  4014. private:
  4015. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  4016. unsigned NoteId = 0);
  4017. };
  4018. } // namespace
  4019. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  4020. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  4021. ExprAnalysisErrorCode ErrorFound = NoError;
  4022. SourceLocation ErrorLoc, NoteLoc;
  4023. SourceRange ErrorRange, NoteRange;
  4024. // Allowed constructs are:
  4025. // x = x binop expr;
  4026. // x = expr binop x;
  4027. if (AtomicBinOp->getOpcode() == BO_Assign) {
  4028. X = AtomicBinOp->getLHS();
  4029. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  4030. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  4031. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  4032. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  4033. AtomicInnerBinOp->isBitwiseOp()) {
  4034. Op = AtomicInnerBinOp->getOpcode();
  4035. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  4036. auto *LHS = AtomicInnerBinOp->getLHS();
  4037. auto *RHS = AtomicInnerBinOp->getRHS();
  4038. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  4039. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  4040. /*Canonical=*/true);
  4041. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  4042. /*Canonical=*/true);
  4043. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  4044. /*Canonical=*/true);
  4045. if (XId == LHSId) {
  4046. E = RHS;
  4047. IsXLHSInRHSPart = true;
  4048. } else if (XId == RHSId) {
  4049. E = LHS;
  4050. IsXLHSInRHSPart = false;
  4051. } else {
  4052. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  4053. ErrorRange = AtomicInnerBinOp->getSourceRange();
  4054. NoteLoc = X->getExprLoc();
  4055. NoteRange = X->getSourceRange();
  4056. ErrorFound = NotAnUpdateExpression;
  4057. }
  4058. } else {
  4059. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  4060. ErrorRange = AtomicInnerBinOp->getSourceRange();
  4061. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  4062. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4063. ErrorFound = NotABinaryOperator;
  4064. }
  4065. } else {
  4066. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  4067. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  4068. ErrorFound = NotABinaryExpression;
  4069. }
  4070. } else {
  4071. ErrorLoc = AtomicBinOp->getExprLoc();
  4072. ErrorRange = AtomicBinOp->getSourceRange();
  4073. NoteLoc = AtomicBinOp->getOperatorLoc();
  4074. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4075. ErrorFound = NotAnAssignmentOp;
  4076. }
  4077. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  4078. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  4079. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  4080. return true;
  4081. } else if (SemaRef.CurContext->isDependentContext())
  4082. E = X = UpdateExpr = nullptr;
  4083. return ErrorFound != NoError;
  4084. }
  4085. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  4086. unsigned NoteId) {
  4087. ExprAnalysisErrorCode ErrorFound = NoError;
  4088. SourceLocation ErrorLoc, NoteLoc;
  4089. SourceRange ErrorRange, NoteRange;
  4090. // Allowed constructs are:
  4091. // x++;
  4092. // x--;
  4093. // ++x;
  4094. // --x;
  4095. // x binop= expr;
  4096. // x = x binop expr;
  4097. // x = expr binop x;
  4098. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  4099. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  4100. if (AtomicBody->getType()->isScalarType() ||
  4101. AtomicBody->isInstantiationDependent()) {
  4102. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  4103. AtomicBody->IgnoreParenImpCasts())) {
  4104. // Check for Compound Assignment Operation
  4105. Op = BinaryOperator::getOpForCompoundAssignment(
  4106. AtomicCompAssignOp->getOpcode());
  4107. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  4108. E = AtomicCompAssignOp->getRHS();
  4109. X = AtomicCompAssignOp->getLHS();
  4110. IsXLHSInRHSPart = true;
  4111. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  4112. AtomicBody->IgnoreParenImpCasts())) {
  4113. // Check for Binary Operation
  4114. if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  4115. return true;
  4116. } else if (auto *AtomicUnaryOp =
  4117. dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
  4118. // Check for Unary Operation
  4119. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  4120. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  4121. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  4122. OpLoc = AtomicUnaryOp->getOperatorLoc();
  4123. X = AtomicUnaryOp->getSubExpr();
  4124. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  4125. IsXLHSInRHSPart = true;
  4126. } else {
  4127. ErrorFound = NotAnUnaryIncDecExpression;
  4128. ErrorLoc = AtomicUnaryOp->getExprLoc();
  4129. ErrorRange = AtomicUnaryOp->getSourceRange();
  4130. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  4131. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4132. }
  4133. } else {
  4134. ErrorFound = NotABinaryOrUnaryExpression;
  4135. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  4136. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  4137. }
  4138. } else {
  4139. ErrorFound = NotAScalarType;
  4140. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  4141. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4142. }
  4143. } else {
  4144. ErrorFound = NotAnExpression;
  4145. NoteLoc = ErrorLoc = S->getLocStart();
  4146. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4147. }
  4148. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  4149. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  4150. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  4151. return true;
  4152. } else if (SemaRef.CurContext->isDependentContext())
  4153. E = X = UpdateExpr = nullptr;
  4154. if (ErrorFound == NoError && E && X) {
  4155. // Build an update expression of form 'OpaqueValueExpr(x) binop
  4156. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  4157. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  4158. auto *OVEX = new (SemaRef.getASTContext())
  4159. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  4160. auto *OVEExpr = new (SemaRef.getASTContext())
  4161. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  4162. auto Update =
  4163. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  4164. IsXLHSInRHSPart ? OVEExpr : OVEX);
  4165. if (Update.isInvalid())
  4166. return true;
  4167. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  4168. Sema::AA_Casting);
  4169. if (Update.isInvalid())
  4170. return true;
  4171. UpdateExpr = Update.get();
  4172. }
  4173. return ErrorFound != NoError;
  4174. }
  4175. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  4176. Stmt *AStmt,
  4177. SourceLocation StartLoc,
  4178. SourceLocation EndLoc) {
  4179. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4180. auto CS = cast<CapturedStmt>(AStmt);
  4181. // 1.2.2 OpenMP Language Terminology
  4182. // Structured block - An executable statement with a single entry at the
  4183. // top and a single exit at the bottom.
  4184. // The point of exit cannot be a branch out of the structured block.
  4185. // longjmp() and throw() must not violate the entry/exit criteria.
  4186. OpenMPClauseKind AtomicKind = OMPC_unknown;
  4187. SourceLocation AtomicKindLoc;
  4188. for (auto *C : Clauses) {
  4189. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  4190. C->getClauseKind() == OMPC_update ||
  4191. C->getClauseKind() == OMPC_capture) {
  4192. if (AtomicKind != OMPC_unknown) {
  4193. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  4194. << SourceRange(C->getLocStart(), C->getLocEnd());
  4195. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  4196. << getOpenMPClauseName(AtomicKind);
  4197. } else {
  4198. AtomicKind = C->getClauseKind();
  4199. AtomicKindLoc = C->getLocStart();
  4200. }
  4201. }
  4202. }
  4203. auto Body = CS->getCapturedStmt();
  4204. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  4205. Body = EWC->getSubExpr();
  4206. Expr *X = nullptr;
  4207. Expr *V = nullptr;
  4208. Expr *E = nullptr;
  4209. Expr *UE = nullptr;
  4210. bool IsXLHSInRHSPart = false;
  4211. bool IsPostfixUpdate = false;
  4212. // OpenMP [2.12.6, atomic Construct]
  4213. // In the next expressions:
  4214. // * x and v (as applicable) are both l-value expressions with scalar type.
  4215. // * During the execution of an atomic region, multiple syntactic
  4216. // occurrences of x must designate the same storage location.
  4217. // * Neither of v and expr (as applicable) may access the storage location
  4218. // designated by x.
  4219. // * Neither of x and expr (as applicable) may access the storage location
  4220. // designated by v.
  4221. // * expr is an expression with scalar type.
  4222. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  4223. // * binop, binop=, ++, and -- are not overloaded operators.
  4224. // * The expression x binop expr must be numerically equivalent to x binop
  4225. // (expr). This requirement is satisfied if the operators in expr have
  4226. // precedence greater than binop, or by using parentheses around expr or
  4227. // subexpressions of expr.
  4228. // * The expression expr binop x must be numerically equivalent to (expr)
  4229. // binop x. This requirement is satisfied if the operators in expr have
  4230. // precedence equal to or greater than binop, or by using parentheses around
  4231. // expr or subexpressions of expr.
  4232. // * For forms that allow multiple occurrences of x, the number of times
  4233. // that x is evaluated is unspecified.
  4234. if (AtomicKind == OMPC_read) {
  4235. enum {
  4236. NotAnExpression,
  4237. NotAnAssignmentOp,
  4238. NotAScalarType,
  4239. NotAnLValue,
  4240. NoError
  4241. } ErrorFound = NoError;
  4242. SourceLocation ErrorLoc, NoteLoc;
  4243. SourceRange ErrorRange, NoteRange;
  4244. // If clause is read:
  4245. // v = x;
  4246. if (auto AtomicBody = dyn_cast<Expr>(Body)) {
  4247. auto AtomicBinOp =
  4248. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4249. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4250. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  4251. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  4252. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  4253. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  4254. if (!X->isLValue() || !V->isLValue()) {
  4255. auto NotLValueExpr = X->isLValue() ? V : X;
  4256. ErrorFound = NotAnLValue;
  4257. ErrorLoc = AtomicBinOp->getExprLoc();
  4258. ErrorRange = AtomicBinOp->getSourceRange();
  4259. NoteLoc = NotLValueExpr->getExprLoc();
  4260. NoteRange = NotLValueExpr->getSourceRange();
  4261. }
  4262. } else if (!X->isInstantiationDependent() ||
  4263. !V->isInstantiationDependent()) {
  4264. auto NotScalarExpr =
  4265. (X->isInstantiationDependent() || X->getType()->isScalarType())
  4266. ? V
  4267. : X;
  4268. ErrorFound = NotAScalarType;
  4269. ErrorLoc = AtomicBinOp->getExprLoc();
  4270. ErrorRange = AtomicBinOp->getSourceRange();
  4271. NoteLoc = NotScalarExpr->getExprLoc();
  4272. NoteRange = NotScalarExpr->getSourceRange();
  4273. }
  4274. } else {
  4275. ErrorFound = NotAnAssignmentOp;
  4276. ErrorLoc = AtomicBody->getExprLoc();
  4277. ErrorRange = AtomicBody->getSourceRange();
  4278. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4279. : AtomicBody->getExprLoc();
  4280. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4281. : AtomicBody->getSourceRange();
  4282. }
  4283. } else {
  4284. ErrorFound = NotAnExpression;
  4285. NoteLoc = ErrorLoc = Body->getLocStart();
  4286. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4287. }
  4288. if (ErrorFound != NoError) {
  4289. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  4290. << ErrorRange;
  4291. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  4292. << NoteRange;
  4293. return StmtError();
  4294. } else if (CurContext->isDependentContext())
  4295. V = X = nullptr;
  4296. } else if (AtomicKind == OMPC_write) {
  4297. enum {
  4298. NotAnExpression,
  4299. NotAnAssignmentOp,
  4300. NotAScalarType,
  4301. NotAnLValue,
  4302. NoError
  4303. } ErrorFound = NoError;
  4304. SourceLocation ErrorLoc, NoteLoc;
  4305. SourceRange ErrorRange, NoteRange;
  4306. // If clause is write:
  4307. // x = expr;
  4308. if (auto AtomicBody = dyn_cast<Expr>(Body)) {
  4309. auto AtomicBinOp =
  4310. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4311. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4312. X = AtomicBinOp->getLHS();
  4313. E = AtomicBinOp->getRHS();
  4314. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  4315. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  4316. if (!X->isLValue()) {
  4317. ErrorFound = NotAnLValue;
  4318. ErrorLoc = AtomicBinOp->getExprLoc();
  4319. ErrorRange = AtomicBinOp->getSourceRange();
  4320. NoteLoc = X->getExprLoc();
  4321. NoteRange = X->getSourceRange();
  4322. }
  4323. } else if (!X->isInstantiationDependent() ||
  4324. !E->isInstantiationDependent()) {
  4325. auto NotScalarExpr =
  4326. (X->isInstantiationDependent() || X->getType()->isScalarType())
  4327. ? E
  4328. : X;
  4329. ErrorFound = NotAScalarType;
  4330. ErrorLoc = AtomicBinOp->getExprLoc();
  4331. ErrorRange = AtomicBinOp->getSourceRange();
  4332. NoteLoc = NotScalarExpr->getExprLoc();
  4333. NoteRange = NotScalarExpr->getSourceRange();
  4334. }
  4335. } else {
  4336. ErrorFound = NotAnAssignmentOp;
  4337. ErrorLoc = AtomicBody->getExprLoc();
  4338. ErrorRange = AtomicBody->getSourceRange();
  4339. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4340. : AtomicBody->getExprLoc();
  4341. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4342. : AtomicBody->getSourceRange();
  4343. }
  4344. } else {
  4345. ErrorFound = NotAnExpression;
  4346. NoteLoc = ErrorLoc = Body->getLocStart();
  4347. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4348. }
  4349. if (ErrorFound != NoError) {
  4350. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  4351. << ErrorRange;
  4352. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  4353. << NoteRange;
  4354. return StmtError();
  4355. } else if (CurContext->isDependentContext())
  4356. E = X = nullptr;
  4357. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  4358. // If clause is update:
  4359. // x++;
  4360. // x--;
  4361. // ++x;
  4362. // --x;
  4363. // x binop= expr;
  4364. // x = x binop expr;
  4365. // x = expr binop x;
  4366. OpenMPAtomicUpdateChecker Checker(*this);
  4367. if (Checker.checkStatement(
  4368. Body, (AtomicKind == OMPC_update)
  4369. ? diag::err_omp_atomic_update_not_expression_statement
  4370. : diag::err_omp_atomic_not_expression_statement,
  4371. diag::note_omp_atomic_update))
  4372. return StmtError();
  4373. if (!CurContext->isDependentContext()) {
  4374. E = Checker.getExpr();
  4375. X = Checker.getX();
  4376. UE = Checker.getUpdateExpr();
  4377. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4378. }
  4379. } else if (AtomicKind == OMPC_capture) {
  4380. enum {
  4381. NotAnAssignmentOp,
  4382. NotACompoundStatement,
  4383. NotTwoSubstatements,
  4384. NotASpecificExpression,
  4385. NoError
  4386. } ErrorFound = NoError;
  4387. SourceLocation ErrorLoc, NoteLoc;
  4388. SourceRange ErrorRange, NoteRange;
  4389. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  4390. // If clause is a capture:
  4391. // v = x++;
  4392. // v = x--;
  4393. // v = ++x;
  4394. // v = --x;
  4395. // v = x binop= expr;
  4396. // v = x = x binop expr;
  4397. // v = x = expr binop x;
  4398. auto *AtomicBinOp =
  4399. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4400. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4401. V = AtomicBinOp->getLHS();
  4402. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  4403. OpenMPAtomicUpdateChecker Checker(*this);
  4404. if (Checker.checkStatement(
  4405. Body, diag::err_omp_atomic_capture_not_expression_statement,
  4406. diag::note_omp_atomic_update))
  4407. return StmtError();
  4408. E = Checker.getExpr();
  4409. X = Checker.getX();
  4410. UE = Checker.getUpdateExpr();
  4411. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4412. IsPostfixUpdate = Checker.isPostfixUpdate();
  4413. } else {
  4414. ErrorLoc = AtomicBody->getExprLoc();
  4415. ErrorRange = AtomicBody->getSourceRange();
  4416. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4417. : AtomicBody->getExprLoc();
  4418. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4419. : AtomicBody->getSourceRange();
  4420. ErrorFound = NotAnAssignmentOp;
  4421. }
  4422. if (ErrorFound != NoError) {
  4423. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  4424. << ErrorRange;
  4425. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  4426. return StmtError();
  4427. } else if (CurContext->isDependentContext()) {
  4428. UE = V = E = X = nullptr;
  4429. }
  4430. } else {
  4431. // If clause is a capture:
  4432. // { v = x; x = expr; }
  4433. // { v = x; x++; }
  4434. // { v = x; x--; }
  4435. // { v = x; ++x; }
  4436. // { v = x; --x; }
  4437. // { v = x; x binop= expr; }
  4438. // { v = x; x = x binop expr; }
  4439. // { v = x; x = expr binop x; }
  4440. // { x++; v = x; }
  4441. // { x--; v = x; }
  4442. // { ++x; v = x; }
  4443. // { --x; v = x; }
  4444. // { x binop= expr; v = x; }
  4445. // { x = x binop expr; v = x; }
  4446. // { x = expr binop x; v = x; }
  4447. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  4448. // Check that this is { expr1; expr2; }
  4449. if (CS->size() == 2) {
  4450. auto *First = CS->body_front();
  4451. auto *Second = CS->body_back();
  4452. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  4453. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  4454. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  4455. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  4456. // Need to find what subexpression is 'v' and what is 'x'.
  4457. OpenMPAtomicUpdateChecker Checker(*this);
  4458. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  4459. BinaryOperator *BinOp = nullptr;
  4460. if (IsUpdateExprFound) {
  4461. BinOp = dyn_cast<BinaryOperator>(First);
  4462. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  4463. }
  4464. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  4465. // { v = x; x++; }
  4466. // { v = x; x--; }
  4467. // { v = x; ++x; }
  4468. // { v = x; --x; }
  4469. // { v = x; x binop= expr; }
  4470. // { v = x; x = x binop expr; }
  4471. // { v = x; x = expr binop x; }
  4472. // Check that the first expression has form v = x.
  4473. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  4474. llvm::FoldingSetNodeID XId, PossibleXId;
  4475. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  4476. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  4477. IsUpdateExprFound = XId == PossibleXId;
  4478. if (IsUpdateExprFound) {
  4479. V = BinOp->getLHS();
  4480. X = Checker.getX();
  4481. E = Checker.getExpr();
  4482. UE = Checker.getUpdateExpr();
  4483. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4484. IsPostfixUpdate = true;
  4485. }
  4486. }
  4487. if (!IsUpdateExprFound) {
  4488. IsUpdateExprFound = !Checker.checkStatement(First);
  4489. BinOp = nullptr;
  4490. if (IsUpdateExprFound) {
  4491. BinOp = dyn_cast<BinaryOperator>(Second);
  4492. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  4493. }
  4494. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  4495. // { x++; v = x; }
  4496. // { x--; v = x; }
  4497. // { ++x; v = x; }
  4498. // { --x; v = x; }
  4499. // { x binop= expr; v = x; }
  4500. // { x = x binop expr; v = x; }
  4501. // { x = expr binop x; v = x; }
  4502. // Check that the second expression has form v = x.
  4503. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  4504. llvm::FoldingSetNodeID XId, PossibleXId;
  4505. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  4506. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  4507. IsUpdateExprFound = XId == PossibleXId;
  4508. if (IsUpdateExprFound) {
  4509. V = BinOp->getLHS();
  4510. X = Checker.getX();
  4511. E = Checker.getExpr();
  4512. UE = Checker.getUpdateExpr();
  4513. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4514. IsPostfixUpdate = false;
  4515. }
  4516. }
  4517. }
  4518. if (!IsUpdateExprFound) {
  4519. // { v = x; x = expr; }
  4520. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  4521. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  4522. ErrorFound = NotAnAssignmentOp;
  4523. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  4524. : First->getLocStart();
  4525. NoteRange = ErrorRange = FirstBinOp
  4526. ? FirstBinOp->getSourceRange()
  4527. : SourceRange(ErrorLoc, ErrorLoc);
  4528. } else {
  4529. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  4530. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  4531. ErrorFound = NotAnAssignmentOp;
  4532. NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
  4533. : Second->getLocStart();
  4534. NoteRange = ErrorRange = SecondBinOp
  4535. ? SecondBinOp->getSourceRange()
  4536. : SourceRange(ErrorLoc, ErrorLoc);
  4537. } else {
  4538. auto *PossibleXRHSInFirst =
  4539. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  4540. auto *PossibleXLHSInSecond =
  4541. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  4542. llvm::FoldingSetNodeID X1Id, X2Id;
  4543. PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
  4544. PossibleXLHSInSecond->Profile(X2Id, Context,
  4545. /*Canonical=*/true);
  4546. IsUpdateExprFound = X1Id == X2Id;
  4547. if (IsUpdateExprFound) {
  4548. V = FirstBinOp->getLHS();
  4549. X = SecondBinOp->getLHS();
  4550. E = SecondBinOp->getRHS();
  4551. UE = nullptr;
  4552. IsXLHSInRHSPart = false;
  4553. IsPostfixUpdate = true;
  4554. } else {
  4555. ErrorFound = NotASpecificExpression;
  4556. ErrorLoc = FirstBinOp->getExprLoc();
  4557. ErrorRange = FirstBinOp->getSourceRange();
  4558. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  4559. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  4560. }
  4561. }
  4562. }
  4563. }
  4564. } else {
  4565. NoteLoc = ErrorLoc = Body->getLocStart();
  4566. NoteRange = ErrorRange =
  4567. SourceRange(Body->getLocStart(), Body->getLocStart());
  4568. ErrorFound = NotTwoSubstatements;
  4569. }
  4570. } else {
  4571. NoteLoc = ErrorLoc = Body->getLocStart();
  4572. NoteRange = ErrorRange =
  4573. SourceRange(Body->getLocStart(), Body->getLocStart());
  4574. ErrorFound = NotACompoundStatement;
  4575. }
  4576. if (ErrorFound != NoError) {
  4577. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  4578. << ErrorRange;
  4579. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  4580. return StmtError();
  4581. } else if (CurContext->isDependentContext()) {
  4582. UE = V = E = X = nullptr;
  4583. }
  4584. }
  4585. }
  4586. getCurFunction()->setHasBranchProtectedScope();
  4587. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4588. X, V, E, UE, IsXLHSInRHSPart,
  4589. IsPostfixUpdate);
  4590. }
  4591. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  4592. Stmt *AStmt,
  4593. SourceLocation StartLoc,
  4594. SourceLocation EndLoc) {
  4595. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4596. // OpenMP [2.16, Nesting of Regions]
  4597. // If specified, a teams construct must be contained within a target
  4598. // construct. That target construct must contain no statements or directives
  4599. // outside of the teams construct.
  4600. if (DSAStack->hasInnerTeamsRegion()) {
  4601. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  4602. bool OMPTeamsFound = true;
  4603. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  4604. auto I = CS->body_begin();
  4605. while (I != CS->body_end()) {
  4606. auto OED = dyn_cast<OMPExecutableDirective>(*I);
  4607. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  4608. OMPTeamsFound = false;
  4609. break;
  4610. }
  4611. ++I;
  4612. }
  4613. assert(I != CS->body_end() && "Not found statement");
  4614. S = *I;
  4615. }
  4616. if (!OMPTeamsFound) {
  4617. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  4618. Diag(DSAStack->getInnerTeamsRegionLoc(),
  4619. diag::note_omp_nested_teams_construct_here);
  4620. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  4621. << isa<OMPExecutableDirective>(S);
  4622. return StmtError();
  4623. }
  4624. }
  4625. getCurFunction()->setHasBranchProtectedScope();
  4626. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4627. }
  4628. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  4629. Stmt *AStmt, SourceLocation StartLoc,
  4630. SourceLocation EndLoc) {
  4631. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4632. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4633. // 1.2.2 OpenMP Language Terminology
  4634. // Structured block - An executable statement with a single entry at the
  4635. // top and a single exit at the bottom.
  4636. // The point of exit cannot be a branch out of the structured block.
  4637. // longjmp() and throw() must not violate the entry/exit criteria.
  4638. CS->getCapturedDecl()->setNothrow();
  4639. getCurFunction()->setHasBranchProtectedScope();
  4640. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4641. }
  4642. StmtResult
  4643. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  4644. SourceLocation EndLoc,
  4645. OpenMPDirectiveKind CancelRegion) {
  4646. if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
  4647. CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
  4648. Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  4649. << getOpenMPDirectiveName(CancelRegion);
  4650. return StmtError();
  4651. }
  4652. if (DSAStack->isParentNowaitRegion()) {
  4653. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  4654. return StmtError();
  4655. }
  4656. if (DSAStack->isParentOrderedRegion()) {
  4657. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  4658. return StmtError();
  4659. }
  4660. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  4661. CancelRegion);
  4662. }
  4663. StmtResult Sema::ActOnOpenMPCancelDirective(SourceLocation StartLoc,
  4664. SourceLocation EndLoc,
  4665. OpenMPDirectiveKind CancelRegion) {
  4666. if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
  4667. CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
  4668. Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  4669. << getOpenMPDirectiveName(CancelRegion);
  4670. return StmtError();
  4671. }
  4672. if (DSAStack->isParentNowaitRegion()) {
  4673. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  4674. return StmtError();
  4675. }
  4676. if (DSAStack->isParentOrderedRegion()) {
  4677. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  4678. return StmtError();
  4679. }
  4680. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, CancelRegion);
  4681. }
  4682. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  4683. SourceLocation StartLoc,
  4684. SourceLocation LParenLoc,
  4685. SourceLocation EndLoc) {
  4686. OMPClause *Res = nullptr;
  4687. switch (Kind) {
  4688. case OMPC_if:
  4689. Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
  4690. break;
  4691. case OMPC_final:
  4692. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  4693. break;
  4694. case OMPC_num_threads:
  4695. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  4696. break;
  4697. case OMPC_safelen:
  4698. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  4699. break;
  4700. case OMPC_collapse:
  4701. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  4702. break;
  4703. case OMPC_default:
  4704. case OMPC_proc_bind:
  4705. case OMPC_schedule:
  4706. case OMPC_private:
  4707. case OMPC_firstprivate:
  4708. case OMPC_lastprivate:
  4709. case OMPC_shared:
  4710. case OMPC_reduction:
  4711. case OMPC_linear:
  4712. case OMPC_aligned:
  4713. case OMPC_copyin:
  4714. case OMPC_copyprivate:
  4715. case OMPC_ordered:
  4716. case OMPC_nowait:
  4717. case OMPC_untied:
  4718. case OMPC_mergeable:
  4719. case OMPC_threadprivate:
  4720. case OMPC_flush:
  4721. case OMPC_read:
  4722. case OMPC_write:
  4723. case OMPC_update:
  4724. case OMPC_capture:
  4725. case OMPC_seq_cst:
  4726. case OMPC_depend:
  4727. case OMPC_unknown:
  4728. llvm_unreachable("Clause is not allowed.");
  4729. }
  4730. return Res;
  4731. }
  4732. OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
  4733. SourceLocation LParenLoc,
  4734. SourceLocation EndLoc) {
  4735. Expr *ValExpr = Condition;
  4736. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  4737. !Condition->isInstantiationDependent() &&
  4738. !Condition->containsUnexpandedParameterPack()) {
  4739. ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
  4740. Condition->getExprLoc(), Condition);
  4741. if (Val.isInvalid())
  4742. return nullptr;
  4743. ValExpr = Val.get();
  4744. }
  4745. return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  4746. }
  4747. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  4748. SourceLocation StartLoc,
  4749. SourceLocation LParenLoc,
  4750. SourceLocation EndLoc) {
  4751. Expr *ValExpr = Condition;
  4752. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  4753. !Condition->isInstantiationDependent() &&
  4754. !Condition->containsUnexpandedParameterPack()) {
  4755. ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
  4756. Condition->getExprLoc(), Condition);
  4757. if (Val.isInvalid())
  4758. return nullptr;
  4759. ValExpr = Val.get();
  4760. }
  4761. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  4762. }
  4763. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  4764. Expr *Op) {
  4765. if (!Op)
  4766. return ExprError();
  4767. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  4768. public:
  4769. IntConvertDiagnoser()
  4770. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  4771. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  4772. QualType T) override {
  4773. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  4774. }
  4775. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  4776. QualType T) override {
  4777. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  4778. }
  4779. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  4780. QualType T,
  4781. QualType ConvTy) override {
  4782. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  4783. }
  4784. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  4785. QualType ConvTy) override {
  4786. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  4787. << ConvTy->isEnumeralType() << ConvTy;
  4788. }
  4789. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  4790. QualType T) override {
  4791. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  4792. }
  4793. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  4794. QualType ConvTy) override {
  4795. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  4796. << ConvTy->isEnumeralType() << ConvTy;
  4797. }
  4798. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  4799. QualType) override {
  4800. llvm_unreachable("conversion functions are permitted");
  4801. }
  4802. } ConvertDiagnoser;
  4803. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  4804. }
  4805. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  4806. SourceLocation StartLoc,
  4807. SourceLocation LParenLoc,
  4808. SourceLocation EndLoc) {
  4809. Expr *ValExpr = NumThreads;
  4810. if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
  4811. !NumThreads->containsUnexpandedParameterPack()) {
  4812. SourceLocation NumThreadsLoc = NumThreads->getLocStart();
  4813. ExprResult Val =
  4814. PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
  4815. if (Val.isInvalid())
  4816. return nullptr;
  4817. ValExpr = Val.get();
  4818. // OpenMP [2.5, Restrictions]
  4819. // The num_threads expression must evaluate to a positive integer value.
  4820. llvm::APSInt Result;
  4821. if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
  4822. !Result.isStrictlyPositive()) {
  4823. Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
  4824. << "num_threads" << NumThreads->getSourceRange();
  4825. return nullptr;
  4826. }
  4827. }
  4828. return new (Context)
  4829. OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  4830. }
  4831. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  4832. OpenMPClauseKind CKind) {
  4833. if (!E)
  4834. return ExprError();
  4835. if (E->isValueDependent() || E->isTypeDependent() ||
  4836. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4837. return E;
  4838. llvm::APSInt Result;
  4839. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  4840. if (ICE.isInvalid())
  4841. return ExprError();
  4842. if (!Result.isStrictlyPositive()) {
  4843. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  4844. << getOpenMPClauseName(CKind) << E->getSourceRange();
  4845. return ExprError();
  4846. }
  4847. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  4848. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  4849. << E->getSourceRange();
  4850. return ExprError();
  4851. }
  4852. if (CKind == OMPC_collapse) {
  4853. DSAStack->setCollapseNumber(Result.getExtValue());
  4854. }
  4855. return ICE;
  4856. }
  4857. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  4858. SourceLocation LParenLoc,
  4859. SourceLocation EndLoc) {
  4860. // OpenMP [2.8.1, simd construct, Description]
  4861. // The parameter of the safelen clause must be a constant
  4862. // positive integer expression.
  4863. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  4864. if (Safelen.isInvalid())
  4865. return nullptr;
  4866. return new (Context)
  4867. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  4868. }
  4869. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  4870. SourceLocation StartLoc,
  4871. SourceLocation LParenLoc,
  4872. SourceLocation EndLoc) {
  4873. // OpenMP [2.7.1, loop construct, Description]
  4874. // OpenMP [2.8.1, simd construct, Description]
  4875. // OpenMP [2.9.6, distribute construct, Description]
  4876. // The parameter of the collapse clause must be a constant
  4877. // positive integer expression.
  4878. ExprResult NumForLoopsResult =
  4879. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  4880. if (NumForLoopsResult.isInvalid())
  4881. return nullptr;
  4882. return new (Context)
  4883. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  4884. }
  4885. OMPClause *Sema::ActOnOpenMPSimpleClause(
  4886. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  4887. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  4888. OMPClause *Res = nullptr;
  4889. switch (Kind) {
  4890. case OMPC_default:
  4891. Res =
  4892. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  4893. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  4894. break;
  4895. case OMPC_proc_bind:
  4896. Res = ActOnOpenMPProcBindClause(
  4897. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  4898. LParenLoc, EndLoc);
  4899. break;
  4900. case OMPC_if:
  4901. case OMPC_final:
  4902. case OMPC_num_threads:
  4903. case OMPC_safelen:
  4904. case OMPC_collapse:
  4905. case OMPC_schedule:
  4906. case OMPC_private:
  4907. case OMPC_firstprivate:
  4908. case OMPC_lastprivate:
  4909. case OMPC_shared:
  4910. case OMPC_reduction:
  4911. case OMPC_linear:
  4912. case OMPC_aligned:
  4913. case OMPC_copyin:
  4914. case OMPC_copyprivate:
  4915. case OMPC_ordered:
  4916. case OMPC_nowait:
  4917. case OMPC_untied:
  4918. case OMPC_mergeable:
  4919. case OMPC_threadprivate:
  4920. case OMPC_flush:
  4921. case OMPC_read:
  4922. case OMPC_write:
  4923. case OMPC_update:
  4924. case OMPC_capture:
  4925. case OMPC_seq_cst:
  4926. case OMPC_depend:
  4927. case OMPC_unknown:
  4928. llvm_unreachable("Clause is not allowed.");
  4929. }
  4930. return Res;
  4931. }
  4932. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  4933. SourceLocation KindKwLoc,
  4934. SourceLocation StartLoc,
  4935. SourceLocation LParenLoc,
  4936. SourceLocation EndLoc) {
  4937. if (Kind == OMPC_DEFAULT_unknown) {
  4938. std::string Values;
  4939. static_assert(OMPC_DEFAULT_unknown > 0,
  4940. "OMPC_DEFAULT_unknown not greater than 0");
  4941. std::string Sep(", ");
  4942. for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
  4943. Values += "'";
  4944. Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
  4945. Values += "'";
  4946. switch (i) {
  4947. case OMPC_DEFAULT_unknown - 2:
  4948. Values += " or ";
  4949. break;
  4950. case OMPC_DEFAULT_unknown - 1:
  4951. break;
  4952. default:
  4953. Values += Sep;
  4954. break;
  4955. }
  4956. }
  4957. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  4958. << Values << getOpenMPClauseName(OMPC_default);
  4959. return nullptr;
  4960. }
  4961. switch (Kind) {
  4962. case OMPC_DEFAULT_none:
  4963. DSAStack->setDefaultDSANone(KindKwLoc);
  4964. break;
  4965. case OMPC_DEFAULT_shared:
  4966. DSAStack->setDefaultDSAShared(KindKwLoc);
  4967. break;
  4968. case OMPC_DEFAULT_unknown:
  4969. llvm_unreachable("Clause kind is not allowed.");
  4970. break;
  4971. }
  4972. return new (Context)
  4973. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  4974. }
  4975. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  4976. SourceLocation KindKwLoc,
  4977. SourceLocation StartLoc,
  4978. SourceLocation LParenLoc,
  4979. SourceLocation EndLoc) {
  4980. if (Kind == OMPC_PROC_BIND_unknown) {
  4981. std::string Values;
  4982. std::string Sep(", ");
  4983. for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
  4984. Values += "'";
  4985. Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
  4986. Values += "'";
  4987. switch (i) {
  4988. case OMPC_PROC_BIND_unknown - 2:
  4989. Values += " or ";
  4990. break;
  4991. case OMPC_PROC_BIND_unknown - 1:
  4992. break;
  4993. default:
  4994. Values += Sep;
  4995. break;
  4996. }
  4997. }
  4998. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  4999. << Values << getOpenMPClauseName(OMPC_proc_bind);
  5000. return nullptr;
  5001. }
  5002. return new (Context)
  5003. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  5004. }
  5005. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  5006. OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
  5007. SourceLocation StartLoc, SourceLocation LParenLoc,
  5008. SourceLocation ArgumentLoc, SourceLocation CommaLoc,
  5009. SourceLocation EndLoc) {
  5010. OMPClause *Res = nullptr;
  5011. switch (Kind) {
  5012. case OMPC_schedule:
  5013. Res = ActOnOpenMPScheduleClause(
  5014. static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
  5015. LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
  5016. break;
  5017. case OMPC_if:
  5018. case OMPC_final:
  5019. case OMPC_num_threads:
  5020. case OMPC_safelen:
  5021. case OMPC_collapse:
  5022. case OMPC_default:
  5023. case OMPC_proc_bind:
  5024. case OMPC_private:
  5025. case OMPC_firstprivate:
  5026. case OMPC_lastprivate:
  5027. case OMPC_shared:
  5028. case OMPC_reduction:
  5029. case OMPC_linear:
  5030. case OMPC_aligned:
  5031. case OMPC_copyin:
  5032. case OMPC_copyprivate:
  5033. case OMPC_ordered:
  5034. case OMPC_nowait:
  5035. case OMPC_untied:
  5036. case OMPC_mergeable:
  5037. case OMPC_threadprivate:
  5038. case OMPC_flush:
  5039. case OMPC_read:
  5040. case OMPC_write:
  5041. case OMPC_update:
  5042. case OMPC_capture:
  5043. case OMPC_seq_cst:
  5044. case OMPC_depend:
  5045. case OMPC_unknown:
  5046. llvm_unreachable("Clause is not allowed.");
  5047. }
  5048. return Res;
  5049. }
  5050. OMPClause *Sema::ActOnOpenMPScheduleClause(
  5051. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  5052. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  5053. SourceLocation EndLoc) {
  5054. if (Kind == OMPC_SCHEDULE_unknown) {
  5055. std::string Values;
  5056. std::string Sep(", ");
  5057. for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
  5058. Values += "'";
  5059. Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
  5060. Values += "'";
  5061. switch (i) {
  5062. case OMPC_SCHEDULE_unknown - 2:
  5063. Values += " or ";
  5064. break;
  5065. case OMPC_SCHEDULE_unknown - 1:
  5066. break;
  5067. default:
  5068. Values += Sep;
  5069. break;
  5070. }
  5071. }
  5072. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  5073. << Values << getOpenMPClauseName(OMPC_schedule);
  5074. return nullptr;
  5075. }
  5076. Expr *ValExpr = ChunkSize;
  5077. Expr *HelperValExpr = nullptr;
  5078. if (ChunkSize) {
  5079. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  5080. !ChunkSize->isInstantiationDependent() &&
  5081. !ChunkSize->containsUnexpandedParameterPack()) {
  5082. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  5083. ExprResult Val =
  5084. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  5085. if (Val.isInvalid())
  5086. return nullptr;
  5087. ValExpr = Val.get();
  5088. // OpenMP [2.7.1, Restrictions]
  5089. // chunk_size must be a loop invariant integer expression with a positive
  5090. // value.
  5091. llvm::APSInt Result;
  5092. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  5093. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  5094. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  5095. << "schedule" << ChunkSize->getSourceRange();
  5096. return nullptr;
  5097. }
  5098. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
  5099. auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
  5100. ChunkSize->getType(), ".chunk.");
  5101. auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
  5102. ChunkSize->getExprLoc(),
  5103. /*RefersToCapture=*/true);
  5104. HelperValExpr = ImpVarRef;
  5105. }
  5106. }
  5107. }
  5108. return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
  5109. EndLoc, Kind, ValExpr, HelperValExpr);
  5110. }
  5111. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  5112. SourceLocation StartLoc,
  5113. SourceLocation EndLoc) {
  5114. OMPClause *Res = nullptr;
  5115. switch (Kind) {
  5116. case OMPC_ordered:
  5117. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  5118. break;
  5119. case OMPC_nowait:
  5120. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  5121. break;
  5122. case OMPC_untied:
  5123. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  5124. break;
  5125. case OMPC_mergeable:
  5126. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  5127. break;
  5128. case OMPC_read:
  5129. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  5130. break;
  5131. case OMPC_write:
  5132. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  5133. break;
  5134. case OMPC_update:
  5135. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  5136. break;
  5137. case OMPC_capture:
  5138. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  5139. break;
  5140. case OMPC_seq_cst:
  5141. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  5142. break;
  5143. case OMPC_if:
  5144. case OMPC_final:
  5145. case OMPC_num_threads:
  5146. case OMPC_safelen:
  5147. case OMPC_collapse:
  5148. case OMPC_schedule:
  5149. case OMPC_private:
  5150. case OMPC_firstprivate:
  5151. case OMPC_lastprivate:
  5152. case OMPC_shared:
  5153. case OMPC_reduction:
  5154. case OMPC_linear:
  5155. case OMPC_aligned:
  5156. case OMPC_copyin:
  5157. case OMPC_copyprivate:
  5158. case OMPC_default:
  5159. case OMPC_proc_bind:
  5160. case OMPC_threadprivate:
  5161. case OMPC_flush:
  5162. case OMPC_depend:
  5163. case OMPC_unknown:
  5164. llvm_unreachable("Clause is not allowed.");
  5165. }
  5166. return Res;
  5167. }
  5168. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  5169. SourceLocation EndLoc) {
  5170. DSAStack->setOrderedRegion();
  5171. return new (Context) OMPOrderedClause(StartLoc, EndLoc);
  5172. }
  5173. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  5174. SourceLocation EndLoc) {
  5175. DSAStack->setNowaitRegion();
  5176. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  5177. }
  5178. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  5179. SourceLocation EndLoc) {
  5180. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  5181. }
  5182. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  5183. SourceLocation EndLoc) {
  5184. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  5185. }
  5186. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  5187. SourceLocation EndLoc) {
  5188. return new (Context) OMPReadClause(StartLoc, EndLoc);
  5189. }
  5190. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  5191. SourceLocation EndLoc) {
  5192. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  5193. }
  5194. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  5195. SourceLocation EndLoc) {
  5196. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  5197. }
  5198. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  5199. SourceLocation EndLoc) {
  5200. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  5201. }
  5202. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  5203. SourceLocation EndLoc) {
  5204. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  5205. }
  5206. OMPClause *Sema::ActOnOpenMPVarListClause(
  5207. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  5208. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  5209. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  5210. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  5211. SourceLocation DepLoc) {
  5212. OMPClause *Res = nullptr;
  5213. switch (Kind) {
  5214. case OMPC_private:
  5215. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  5216. break;
  5217. case OMPC_firstprivate:
  5218. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  5219. break;
  5220. case OMPC_lastprivate:
  5221. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  5222. break;
  5223. case OMPC_shared:
  5224. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  5225. break;
  5226. case OMPC_reduction:
  5227. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  5228. EndLoc, ReductionIdScopeSpec, ReductionId);
  5229. break;
  5230. case OMPC_linear:
  5231. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  5232. ColonLoc, EndLoc);
  5233. break;
  5234. case OMPC_aligned:
  5235. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  5236. ColonLoc, EndLoc);
  5237. break;
  5238. case OMPC_copyin:
  5239. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  5240. break;
  5241. case OMPC_copyprivate:
  5242. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  5243. break;
  5244. case OMPC_flush:
  5245. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  5246. break;
  5247. case OMPC_depend:
  5248. Res = ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList, StartLoc,
  5249. LParenLoc, EndLoc);
  5250. break;
  5251. case OMPC_if:
  5252. case OMPC_final:
  5253. case OMPC_num_threads:
  5254. case OMPC_safelen:
  5255. case OMPC_collapse:
  5256. case OMPC_default:
  5257. case OMPC_proc_bind:
  5258. case OMPC_schedule:
  5259. case OMPC_ordered:
  5260. case OMPC_nowait:
  5261. case OMPC_untied:
  5262. case OMPC_mergeable:
  5263. case OMPC_threadprivate:
  5264. case OMPC_read:
  5265. case OMPC_write:
  5266. case OMPC_update:
  5267. case OMPC_capture:
  5268. case OMPC_seq_cst:
  5269. case OMPC_unknown:
  5270. llvm_unreachable("Clause is not allowed.");
  5271. }
  5272. return Res;
  5273. }
  5274. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  5275. SourceLocation StartLoc,
  5276. SourceLocation LParenLoc,
  5277. SourceLocation EndLoc) {
  5278. SmallVector<Expr *, 8> Vars;
  5279. SmallVector<Expr *, 8> PrivateCopies;
  5280. for (auto &RefExpr : VarList) {
  5281. assert(RefExpr && "NULL expr in OpenMP private clause.");
  5282. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5283. // It will be analyzed later.
  5284. Vars.push_back(RefExpr);
  5285. PrivateCopies.push_back(nullptr);
  5286. continue;
  5287. }
  5288. SourceLocation ELoc = RefExpr->getExprLoc();
  5289. // OpenMP [2.1, C/C++]
  5290. // A list item is a variable name.
  5291. // OpenMP [2.9.3.3, Restrictions, p.1]
  5292. // A variable that is part of another variable (as an array or
  5293. // structure element) cannot appear in a private clause.
  5294. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  5295. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5296. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  5297. continue;
  5298. }
  5299. Decl *D = DE->getDecl();
  5300. VarDecl *VD = cast<VarDecl>(D);
  5301. QualType Type = VD->getType();
  5302. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  5303. // It will be analyzed later.
  5304. Vars.push_back(DE);
  5305. PrivateCopies.push_back(nullptr);
  5306. continue;
  5307. }
  5308. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  5309. // A variable that appears in a private clause must not have an incomplete
  5310. // type or a reference type.
  5311. if (RequireCompleteType(ELoc, Type,
  5312. diag::err_omp_private_incomplete_type)) {
  5313. continue;
  5314. }
  5315. if (Type->isReferenceType()) {
  5316. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  5317. << getOpenMPClauseName(OMPC_private) << Type;
  5318. bool IsDecl =
  5319. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5320. Diag(VD->getLocation(),
  5321. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5322. << VD;
  5323. continue;
  5324. }
  5325. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  5326. // in a Construct]
  5327. // Variables with the predetermined data-sharing attributes may not be
  5328. // listed in data-sharing attributes clauses, except for the cases
  5329. // listed below. For these exceptions only, listing a predetermined
  5330. // variable in a data-sharing attribute clause is allowed and overrides
  5331. // the variable's predetermined data-sharing attributes.
  5332. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  5333. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  5334. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  5335. << getOpenMPClauseName(OMPC_private);
  5336. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5337. continue;
  5338. }
  5339. // Variably modified types are not supported for tasks.
  5340. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  5341. DSAStack->getCurrentDirective() == OMPD_task) {
  5342. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  5343. << getOpenMPClauseName(OMPC_private) << Type
  5344. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  5345. bool IsDecl =
  5346. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5347. Diag(VD->getLocation(),
  5348. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5349. << VD;
  5350. continue;
  5351. }
  5352. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  5353. // A variable of class type (or array thereof) that appears in a private
  5354. // clause requires an accessible, unambiguous default constructor for the
  5355. // class type.
  5356. // Generate helper private variable and initialize it with the default
  5357. // value. The address of the original variable is replaced by the address of
  5358. // the new private variable in CodeGen. This new variable is not added to
  5359. // IdResolver, so the code in the OpenMP region uses original variable for
  5360. // proper diagnostics.
  5361. Type = Type.getUnqualifiedType();
  5362. auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
  5363. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
  5364. if (VDPrivate->isInvalidDecl())
  5365. continue;
  5366. auto VDPrivateRefExpr = buildDeclRefExpr(
  5367. *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  5368. DSAStack->addDSA(VD, DE, OMPC_private);
  5369. Vars.push_back(DE);
  5370. PrivateCopies.push_back(VDPrivateRefExpr);
  5371. }
  5372. if (Vars.empty())
  5373. return nullptr;
  5374. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  5375. PrivateCopies);
  5376. }
  5377. namespace {
  5378. class DiagsUninitializedSeveretyRAII {
  5379. private:
  5380. DiagnosticsEngine &Diags;
  5381. SourceLocation SavedLoc;
  5382. bool IsIgnored;
  5383. public:
  5384. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  5385. bool IsIgnored)
  5386. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  5387. if (!IsIgnored) {
  5388. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  5389. /*Map*/ diag::Severity::Ignored, Loc);
  5390. }
  5391. }
  5392. ~DiagsUninitializedSeveretyRAII() {
  5393. if (!IsIgnored)
  5394. Diags.popMappings(SavedLoc);
  5395. }
  5396. };
  5397. }
  5398. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  5399. SourceLocation StartLoc,
  5400. SourceLocation LParenLoc,
  5401. SourceLocation EndLoc) {
  5402. SmallVector<Expr *, 8> Vars;
  5403. SmallVector<Expr *, 8> PrivateCopies;
  5404. SmallVector<Expr *, 8> Inits;
  5405. bool IsImplicitClause =
  5406. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  5407. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  5408. for (auto &RefExpr : VarList) {
  5409. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  5410. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5411. // It will be analyzed later.
  5412. Vars.push_back(RefExpr);
  5413. PrivateCopies.push_back(nullptr);
  5414. Inits.push_back(nullptr);
  5415. continue;
  5416. }
  5417. SourceLocation ELoc =
  5418. IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
  5419. // OpenMP [2.1, C/C++]
  5420. // A list item is a variable name.
  5421. // OpenMP [2.9.3.3, Restrictions, p.1]
  5422. // A variable that is part of another variable (as an array or
  5423. // structure element) cannot appear in a private clause.
  5424. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  5425. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5426. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  5427. continue;
  5428. }
  5429. Decl *D = DE->getDecl();
  5430. VarDecl *VD = cast<VarDecl>(D);
  5431. QualType Type = VD->getType();
  5432. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  5433. // It will be analyzed later.
  5434. Vars.push_back(DE);
  5435. PrivateCopies.push_back(nullptr);
  5436. Inits.push_back(nullptr);
  5437. continue;
  5438. }
  5439. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  5440. // A variable that appears in a private clause must not have an incomplete
  5441. // type or a reference type.
  5442. if (RequireCompleteType(ELoc, Type,
  5443. diag::err_omp_firstprivate_incomplete_type)) {
  5444. continue;
  5445. }
  5446. if (Type->isReferenceType()) {
  5447. if (IsImplicitClause) {
  5448. Diag(ImplicitClauseLoc,
  5449. diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
  5450. << Type;
  5451. Diag(RefExpr->getExprLoc(), diag::note_used_here);
  5452. } else {
  5453. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  5454. << getOpenMPClauseName(OMPC_firstprivate) << Type;
  5455. }
  5456. bool IsDecl =
  5457. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5458. Diag(VD->getLocation(),
  5459. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5460. << VD;
  5461. continue;
  5462. }
  5463. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  5464. // A variable of class type (or array thereof) that appears in a private
  5465. // clause requires an accessible, unambiguous copy constructor for the
  5466. // class type.
  5467. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  5468. // If an implicit firstprivate variable found it was checked already.
  5469. if (!IsImplicitClause) {
  5470. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  5471. bool IsConstant = ElemType.isConstant(Context);
  5472. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  5473. // A list item that specifies a given variable may not appear in more
  5474. // than one clause on the same directive, except that a variable may be
  5475. // specified in both firstprivate and lastprivate clauses.
  5476. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  5477. DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
  5478. Diag(ELoc, diag::err_omp_wrong_dsa)
  5479. << getOpenMPClauseName(DVar.CKind)
  5480. << getOpenMPClauseName(OMPC_firstprivate);
  5481. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5482. continue;
  5483. }
  5484. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  5485. // in a Construct]
  5486. // Variables with the predetermined data-sharing attributes may not be
  5487. // listed in data-sharing attributes clauses, except for the cases
  5488. // listed below. For these exceptions only, listing a predetermined
  5489. // variable in a data-sharing attribute clause is allowed and overrides
  5490. // the variable's predetermined data-sharing attributes.
  5491. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  5492. // in a Construct, C/C++, p.2]
  5493. // Variables with const-qualified type having no mutable member may be
  5494. // listed in a firstprivate clause, even if they are static data members.
  5495. if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
  5496. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  5497. Diag(ELoc, diag::err_omp_wrong_dsa)
  5498. << getOpenMPClauseName(DVar.CKind)
  5499. << getOpenMPClauseName(OMPC_firstprivate);
  5500. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5501. continue;
  5502. }
  5503. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  5504. // OpenMP [2.9.3.4, Restrictions, p.2]
  5505. // A list item that is private within a parallel region must not appear
  5506. // in a firstprivate clause on a worksharing construct if any of the
  5507. // worksharing regions arising from the worksharing construct ever bind
  5508. // to any of the parallel regions arising from the parallel construct.
  5509. if (isOpenMPWorksharingDirective(CurrDir) &&
  5510. !isOpenMPParallelDirective(CurrDir)) {
  5511. DVar = DSAStack->getImplicitDSA(VD, true);
  5512. if (DVar.CKind != OMPC_shared &&
  5513. (isOpenMPParallelDirective(DVar.DKind) ||
  5514. DVar.DKind == OMPD_unknown)) {
  5515. Diag(ELoc, diag::err_omp_required_access)
  5516. << getOpenMPClauseName(OMPC_firstprivate)
  5517. << getOpenMPClauseName(OMPC_shared);
  5518. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5519. continue;
  5520. }
  5521. }
  5522. // OpenMP [2.9.3.4, Restrictions, p.3]
  5523. // A list item that appears in a reduction clause of a parallel construct
  5524. // must not appear in a firstprivate clause on a worksharing or task
  5525. // construct if any of the worksharing or task regions arising from the
  5526. // worksharing or task construct ever bind to any of the parallel regions
  5527. // arising from the parallel construct.
  5528. // OpenMP [2.9.3.4, Restrictions, p.4]
  5529. // A list item that appears in a reduction clause in worksharing
  5530. // construct must not appear in a firstprivate clause in a task construct
  5531. // encountered during execution of any of the worksharing regions arising
  5532. // from the worksharing construct.
  5533. if (CurrDir == OMPD_task) {
  5534. DVar =
  5535. DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  5536. [](OpenMPDirectiveKind K) -> bool {
  5537. return isOpenMPParallelDirective(K) ||
  5538. isOpenMPWorksharingDirective(K);
  5539. },
  5540. false);
  5541. if (DVar.CKind == OMPC_reduction &&
  5542. (isOpenMPParallelDirective(DVar.DKind) ||
  5543. isOpenMPWorksharingDirective(DVar.DKind))) {
  5544. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  5545. << getOpenMPDirectiveName(DVar.DKind);
  5546. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5547. continue;
  5548. }
  5549. }
  5550. }
  5551. // Variably modified types are not supported for tasks.
  5552. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  5553. DSAStack->getCurrentDirective() == OMPD_task) {
  5554. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  5555. << getOpenMPClauseName(OMPC_firstprivate) << Type
  5556. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  5557. bool IsDecl =
  5558. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5559. Diag(VD->getLocation(),
  5560. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5561. << VD;
  5562. continue;
  5563. }
  5564. Type = Type.getUnqualifiedType();
  5565. auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
  5566. // Generate helper private variable and initialize it with the value of the
  5567. // original variable. The address of the original variable is replaced by
  5568. // the address of the new private variable in the CodeGen. This new variable
  5569. // is not added to IdResolver, so the code in the OpenMP region uses
  5570. // original variable for proper diagnostics and variable capturing.
  5571. Expr *VDInitRefExpr = nullptr;
  5572. // For arrays generate initializer for single element and replace it by the
  5573. // original array element in CodeGen.
  5574. if (Type->isArrayType()) {
  5575. auto VDInit =
  5576. buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
  5577. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  5578. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  5579. ElemType = ElemType.getUnqualifiedType();
  5580. auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
  5581. ".firstprivate.temp");
  5582. InitializedEntity Entity =
  5583. InitializedEntity::InitializeVariable(VDInitTemp);
  5584. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  5585. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  5586. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  5587. if (Result.isInvalid())
  5588. VDPrivate->setInvalidDecl();
  5589. else
  5590. VDPrivate->setInit(Result.getAs<Expr>());
  5591. } else {
  5592. auto *VDInit =
  5593. buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
  5594. VDInitRefExpr =
  5595. buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
  5596. AddInitializerToDecl(VDPrivate,
  5597. DefaultLvalueConversion(VDInitRefExpr).get(),
  5598. /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
  5599. }
  5600. if (VDPrivate->isInvalidDecl()) {
  5601. if (IsImplicitClause) {
  5602. Diag(DE->getExprLoc(),
  5603. diag::note_omp_task_predetermined_firstprivate_here);
  5604. }
  5605. continue;
  5606. }
  5607. CurContext->addDecl(VDPrivate);
  5608. auto VDPrivateRefExpr = buildDeclRefExpr(
  5609. *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  5610. DSAStack->addDSA(VD, DE, OMPC_firstprivate);
  5611. Vars.push_back(DE);
  5612. PrivateCopies.push_back(VDPrivateRefExpr);
  5613. Inits.push_back(VDInitRefExpr);
  5614. }
  5615. if (Vars.empty())
  5616. return nullptr;
  5617. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  5618. Vars, PrivateCopies, Inits);
  5619. }
  5620. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  5621. SourceLocation StartLoc,
  5622. SourceLocation LParenLoc,
  5623. SourceLocation EndLoc) {
  5624. SmallVector<Expr *, 8> Vars;
  5625. SmallVector<Expr *, 8> SrcExprs;
  5626. SmallVector<Expr *, 8> DstExprs;
  5627. SmallVector<Expr *, 8> AssignmentOps;
  5628. for (auto &RefExpr : VarList) {
  5629. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  5630. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5631. // It will be analyzed later.
  5632. Vars.push_back(RefExpr);
  5633. SrcExprs.push_back(nullptr);
  5634. DstExprs.push_back(nullptr);
  5635. AssignmentOps.push_back(nullptr);
  5636. continue;
  5637. }
  5638. SourceLocation ELoc = RefExpr->getExprLoc();
  5639. // OpenMP [2.1, C/C++]
  5640. // A list item is a variable name.
  5641. // OpenMP [2.14.3.5, Restrictions, p.1]
  5642. // A variable that is part of another variable (as an array or structure
  5643. // element) cannot appear in a lastprivate clause.
  5644. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  5645. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5646. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  5647. continue;
  5648. }
  5649. Decl *D = DE->getDecl();
  5650. VarDecl *VD = cast<VarDecl>(D);
  5651. QualType Type = VD->getType();
  5652. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  5653. // It will be analyzed later.
  5654. Vars.push_back(DE);
  5655. SrcExprs.push_back(nullptr);
  5656. DstExprs.push_back(nullptr);
  5657. AssignmentOps.push_back(nullptr);
  5658. continue;
  5659. }
  5660. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  5661. // A variable that appears in a lastprivate clause must not have an
  5662. // incomplete type or a reference type.
  5663. if (RequireCompleteType(ELoc, Type,
  5664. diag::err_omp_lastprivate_incomplete_type)) {
  5665. continue;
  5666. }
  5667. if (Type->isReferenceType()) {
  5668. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  5669. << getOpenMPClauseName(OMPC_lastprivate) << Type;
  5670. bool IsDecl =
  5671. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5672. Diag(VD->getLocation(),
  5673. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5674. << VD;
  5675. continue;
  5676. }
  5677. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  5678. // in a Construct]
  5679. // Variables with the predetermined data-sharing attributes may not be
  5680. // listed in data-sharing attributes clauses, except for the cases
  5681. // listed below.
  5682. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  5683. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  5684. DVar.CKind != OMPC_firstprivate &&
  5685. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  5686. Diag(ELoc, diag::err_omp_wrong_dsa)
  5687. << getOpenMPClauseName(DVar.CKind)
  5688. << getOpenMPClauseName(OMPC_lastprivate);
  5689. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5690. continue;
  5691. }
  5692. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  5693. // OpenMP [2.14.3.5, Restrictions, p.2]
  5694. // A list item that is private within a parallel region, or that appears in
  5695. // the reduction clause of a parallel construct, must not appear in a
  5696. // lastprivate clause on a worksharing construct if any of the corresponding
  5697. // worksharing regions ever binds to any of the corresponding parallel
  5698. // regions.
  5699. DSAStackTy::DSAVarData TopDVar = DVar;
  5700. if (isOpenMPWorksharingDirective(CurrDir) &&
  5701. !isOpenMPParallelDirective(CurrDir)) {
  5702. DVar = DSAStack->getImplicitDSA(VD, true);
  5703. if (DVar.CKind != OMPC_shared) {
  5704. Diag(ELoc, diag::err_omp_required_access)
  5705. << getOpenMPClauseName(OMPC_lastprivate)
  5706. << getOpenMPClauseName(OMPC_shared);
  5707. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5708. continue;
  5709. }
  5710. }
  5711. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  5712. // A variable of class type (or array thereof) that appears in a
  5713. // lastprivate clause requires an accessible, unambiguous default
  5714. // constructor for the class type, unless the list item is also specified
  5715. // in a firstprivate clause.
  5716. // A variable of class type (or array thereof) that appears in a
  5717. // lastprivate clause requires an accessible, unambiguous copy assignment
  5718. // operator for the class type.
  5719. Type = Context.getBaseElementType(Type).getNonReferenceType();
  5720. auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
  5721. Type.getUnqualifiedType(), ".lastprivate.src");
  5722. auto *PseudoSrcExpr = buildDeclRefExpr(
  5723. *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
  5724. auto *DstVD =
  5725. buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
  5726. auto *PseudoDstExpr =
  5727. buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
  5728. // For arrays generate assignment operation for single element and replace
  5729. // it by the original array element in CodeGen.
  5730. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  5731. PseudoDstExpr, PseudoSrcExpr);
  5732. if (AssignmentOp.isInvalid())
  5733. continue;
  5734. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  5735. /*DiscardedValue=*/true);
  5736. if (AssignmentOp.isInvalid())
  5737. continue;
  5738. if (TopDVar.CKind != OMPC_firstprivate)
  5739. DSAStack->addDSA(VD, DE, OMPC_lastprivate);
  5740. Vars.push_back(DE);
  5741. SrcExprs.push_back(PseudoSrcExpr);
  5742. DstExprs.push_back(PseudoDstExpr);
  5743. AssignmentOps.push_back(AssignmentOp.get());
  5744. }
  5745. if (Vars.empty())
  5746. return nullptr;
  5747. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  5748. Vars, SrcExprs, DstExprs, AssignmentOps);
  5749. }
  5750. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  5751. SourceLocation StartLoc,
  5752. SourceLocation LParenLoc,
  5753. SourceLocation EndLoc) {
  5754. SmallVector<Expr *, 8> Vars;
  5755. for (auto &RefExpr : VarList) {
  5756. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  5757. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5758. // It will be analyzed later.
  5759. Vars.push_back(RefExpr);
  5760. continue;
  5761. }
  5762. SourceLocation ELoc = RefExpr->getExprLoc();
  5763. // OpenMP [2.1, C/C++]
  5764. // A list item is a variable name.
  5765. // OpenMP [2.14.3.2, Restrictions, p.1]
  5766. // A variable that is part of another variable (as an array or structure
  5767. // element) cannot appear in a shared unless it is a static data member
  5768. // of a C++ class.
  5769. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  5770. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5771. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  5772. continue;
  5773. }
  5774. Decl *D = DE->getDecl();
  5775. VarDecl *VD = cast<VarDecl>(D);
  5776. QualType Type = VD->getType();
  5777. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  5778. // It will be analyzed later.
  5779. Vars.push_back(DE);
  5780. continue;
  5781. }
  5782. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  5783. // in a Construct]
  5784. // Variables with the predetermined data-sharing attributes may not be
  5785. // listed in data-sharing attributes clauses, except for the cases
  5786. // listed below. For these exceptions only, listing a predetermined
  5787. // variable in a data-sharing attribute clause is allowed and overrides
  5788. // the variable's predetermined data-sharing attributes.
  5789. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  5790. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  5791. DVar.RefExpr) {
  5792. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  5793. << getOpenMPClauseName(OMPC_shared);
  5794. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5795. continue;
  5796. }
  5797. DSAStack->addDSA(VD, DE, OMPC_shared);
  5798. Vars.push_back(DE);
  5799. }
  5800. if (Vars.empty())
  5801. return nullptr;
  5802. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  5803. }
  5804. namespace {
  5805. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  5806. DSAStackTy *Stack;
  5807. public:
  5808. bool VisitDeclRefExpr(DeclRefExpr *E) {
  5809. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  5810. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  5811. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  5812. return false;
  5813. if (DVar.CKind != OMPC_unknown)
  5814. return true;
  5815. DSAStackTy::DSAVarData DVarPrivate =
  5816. Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
  5817. if (DVarPrivate.CKind != OMPC_unknown)
  5818. return true;
  5819. return false;
  5820. }
  5821. return false;
  5822. }
  5823. bool VisitStmt(Stmt *S) {
  5824. for (auto Child : S->children()) {
  5825. if (Child && Visit(Child))
  5826. return true;
  5827. }
  5828. return false;
  5829. }
  5830. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  5831. };
  5832. } // namespace
  5833. OMPClause *Sema::ActOnOpenMPReductionClause(
  5834. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  5835. SourceLocation ColonLoc, SourceLocation EndLoc,
  5836. CXXScopeSpec &ReductionIdScopeSpec,
  5837. const DeclarationNameInfo &ReductionId) {
  5838. // TODO: Allow scope specification search when 'declare reduction' is
  5839. // supported.
  5840. assert(ReductionIdScopeSpec.isEmpty() &&
  5841. "No support for scoped reduction identifiers yet.");
  5842. auto DN = ReductionId.getName();
  5843. auto OOK = DN.getCXXOverloadedOperator();
  5844. BinaryOperatorKind BOK = BO_Comma;
  5845. // OpenMP [2.14.3.6, reduction clause]
  5846. // C
  5847. // reduction-identifier is either an identifier or one of the following
  5848. // operators: +, -, *, &, |, ^, && and ||
  5849. // C++
  5850. // reduction-identifier is either an id-expression or one of the following
  5851. // operators: +, -, *, &, |, ^, && and ||
  5852. // FIXME: Only 'min' and 'max' identifiers are supported for now.
  5853. switch (OOK) {
  5854. case OO_Plus:
  5855. case OO_Minus:
  5856. BOK = BO_Add;
  5857. break;
  5858. case OO_Star:
  5859. BOK = BO_Mul;
  5860. break;
  5861. case OO_Amp:
  5862. BOK = BO_And;
  5863. break;
  5864. case OO_Pipe:
  5865. BOK = BO_Or;
  5866. break;
  5867. case OO_Caret:
  5868. BOK = BO_Xor;
  5869. break;
  5870. case OO_AmpAmp:
  5871. BOK = BO_LAnd;
  5872. break;
  5873. case OO_PipePipe:
  5874. BOK = BO_LOr;
  5875. break;
  5876. case OO_New:
  5877. case OO_Delete:
  5878. case OO_Array_New:
  5879. case OO_Array_Delete:
  5880. case OO_Slash:
  5881. case OO_Percent:
  5882. case OO_Tilde:
  5883. case OO_Exclaim:
  5884. case OO_Equal:
  5885. case OO_Less:
  5886. case OO_Greater:
  5887. case OO_LessEqual:
  5888. case OO_GreaterEqual:
  5889. case OO_PlusEqual:
  5890. case OO_MinusEqual:
  5891. case OO_StarEqual:
  5892. case OO_SlashEqual:
  5893. case OO_PercentEqual:
  5894. case OO_CaretEqual:
  5895. case OO_AmpEqual:
  5896. case OO_PipeEqual:
  5897. case OO_LessLess:
  5898. case OO_GreaterGreater:
  5899. case OO_LessLessEqual:
  5900. case OO_GreaterGreaterEqual:
  5901. case OO_EqualEqual:
  5902. case OO_ExclaimEqual:
  5903. case OO_PlusPlus:
  5904. case OO_MinusMinus:
  5905. case OO_Comma:
  5906. case OO_ArrowStar:
  5907. case OO_Arrow:
  5908. case OO_Call:
  5909. case OO_Subscript:
  5910. case OO_Conditional:
  5911. case NUM_OVERLOADED_OPERATORS:
  5912. llvm_unreachable("Unexpected reduction identifier");
  5913. case OO_None:
  5914. if (auto II = DN.getAsIdentifierInfo()) {
  5915. if (II->isStr("max"))
  5916. BOK = BO_GT;
  5917. else if (II->isStr("min"))
  5918. BOK = BO_LT;
  5919. }
  5920. break;
  5921. }
  5922. SourceRange ReductionIdRange;
  5923. if (ReductionIdScopeSpec.isValid()) {
  5924. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  5925. }
  5926. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  5927. if (BOK == BO_Comma) {
  5928. // Not allowed reduction identifier is found.
  5929. Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
  5930. << ReductionIdRange;
  5931. return nullptr;
  5932. }
  5933. SmallVector<Expr *, 8> Vars;
  5934. SmallVector<Expr *, 8> LHSs;
  5935. SmallVector<Expr *, 8> RHSs;
  5936. SmallVector<Expr *, 8> ReductionOps;
  5937. for (auto RefExpr : VarList) {
  5938. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  5939. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5940. // It will be analyzed later.
  5941. Vars.push_back(RefExpr);
  5942. LHSs.push_back(nullptr);
  5943. RHSs.push_back(nullptr);
  5944. ReductionOps.push_back(nullptr);
  5945. continue;
  5946. }
  5947. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  5948. RefExpr->isInstantiationDependent() ||
  5949. RefExpr->containsUnexpandedParameterPack()) {
  5950. // It will be analyzed later.
  5951. Vars.push_back(RefExpr);
  5952. LHSs.push_back(nullptr);
  5953. RHSs.push_back(nullptr);
  5954. ReductionOps.push_back(nullptr);
  5955. continue;
  5956. }
  5957. auto ELoc = RefExpr->getExprLoc();
  5958. auto ERange = RefExpr->getSourceRange();
  5959. // OpenMP [2.1, C/C++]
  5960. // A list item is a variable or array section, subject to the restrictions
  5961. // specified in Section 2.4 on page 42 and in each of the sections
  5962. // describing clauses and directives for which a list appears.
  5963. // OpenMP [2.14.3.3, Restrictions, p.1]
  5964. // A variable that is part of another variable (as an array or
  5965. // structure element) cannot appear in a private clause.
  5966. auto DE = dyn_cast<DeclRefExpr>(RefExpr);
  5967. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5968. Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
  5969. continue;
  5970. }
  5971. auto D = DE->getDecl();
  5972. auto VD = cast<VarDecl>(D);
  5973. auto Type = VD->getType();
  5974. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  5975. // A variable that appears in a private clause must not have an incomplete
  5976. // type or a reference type.
  5977. if (RequireCompleteType(ELoc, Type,
  5978. diag::err_omp_reduction_incomplete_type))
  5979. continue;
  5980. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  5981. // Arrays may not appear in a reduction clause.
  5982. if (Type.getNonReferenceType()->isArrayType()) {
  5983. Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
  5984. bool IsDecl =
  5985. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5986. Diag(VD->getLocation(),
  5987. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5988. << VD;
  5989. continue;
  5990. }
  5991. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  5992. // A list item that appears in a reduction clause must not be
  5993. // const-qualified.
  5994. if (Type.getNonReferenceType().isConstant(Context)) {
  5995. Diag(ELoc, diag::err_omp_const_variable)
  5996. << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
  5997. bool IsDecl =
  5998. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5999. Diag(VD->getLocation(),
  6000. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6001. << VD;
  6002. continue;
  6003. }
  6004. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  6005. // If a list-item is a reference type then it must bind to the same object
  6006. // for all threads of the team.
  6007. VarDecl *VDDef = VD->getDefinition();
  6008. if (Type->isReferenceType() && VDDef) {
  6009. DSARefChecker Check(DSAStack);
  6010. if (Check.Visit(VDDef->getInit())) {
  6011. Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
  6012. Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  6013. continue;
  6014. }
  6015. }
  6016. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  6017. // The type of a list item that appears in a reduction clause must be valid
  6018. // for the reduction-identifier. For a max or min reduction in C, the type
  6019. // of the list item must be an allowed arithmetic data type: char, int,
  6020. // float, double, or _Bool, possibly modified with long, short, signed, or
  6021. // unsigned. For a max or min reduction in C++, the type of the list item
  6022. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  6023. // double, or bool, possibly modified with long, short, signed, or unsigned.
  6024. if ((BOK == BO_GT || BOK == BO_LT) &&
  6025. !(Type->isScalarType() ||
  6026. (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  6027. Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  6028. << getLangOpts().CPlusPlus;
  6029. bool IsDecl =
  6030. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6031. Diag(VD->getLocation(),
  6032. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6033. << VD;
  6034. continue;
  6035. }
  6036. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  6037. !getLangOpts().CPlusPlus && Type->isFloatingType()) {
  6038. Diag(ELoc, diag::err_omp_clause_floating_type_arg);
  6039. bool IsDecl =
  6040. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6041. Diag(VD->getLocation(),
  6042. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6043. << VD;
  6044. continue;
  6045. }
  6046. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  6047. // in a Construct]
  6048. // Variables with the predetermined data-sharing attributes may not be
  6049. // listed in data-sharing attributes clauses, except for the cases
  6050. // listed below. For these exceptions only, listing a predetermined
  6051. // variable in a data-sharing attribute clause is allowed and overrides
  6052. // the variable's predetermined data-sharing attributes.
  6053. // OpenMP [2.14.3.6, Restrictions, p.3]
  6054. // Any number of reduction clauses can be specified on the directive,
  6055. // but a list item can appear only once in the reduction clauses for that
  6056. // directive.
  6057. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  6058. if (DVar.CKind == OMPC_reduction) {
  6059. Diag(ELoc, diag::err_omp_once_referenced)
  6060. << getOpenMPClauseName(OMPC_reduction);
  6061. if (DVar.RefExpr) {
  6062. Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  6063. }
  6064. } else if (DVar.CKind != OMPC_unknown) {
  6065. Diag(ELoc, diag::err_omp_wrong_dsa)
  6066. << getOpenMPClauseName(DVar.CKind)
  6067. << getOpenMPClauseName(OMPC_reduction);
  6068. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6069. continue;
  6070. }
  6071. // OpenMP [2.14.3.6, Restrictions, p.1]
  6072. // A list item that appears in a reduction clause of a worksharing
  6073. // construct must be shared in the parallel regions to which any of the
  6074. // worksharing regions arising from the worksharing construct bind.
  6075. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  6076. if (isOpenMPWorksharingDirective(CurrDir) &&
  6077. !isOpenMPParallelDirective(CurrDir)) {
  6078. DVar = DSAStack->getImplicitDSA(VD, true);
  6079. if (DVar.CKind != OMPC_shared) {
  6080. Diag(ELoc, diag::err_omp_required_access)
  6081. << getOpenMPClauseName(OMPC_reduction)
  6082. << getOpenMPClauseName(OMPC_shared);
  6083. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6084. continue;
  6085. }
  6086. }
  6087. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  6088. auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
  6089. auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
  6090. // Add initializer for private variable.
  6091. Expr *Init = nullptr;
  6092. switch (BOK) {
  6093. case BO_Add:
  6094. case BO_Xor:
  6095. case BO_Or:
  6096. case BO_LOr:
  6097. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  6098. if (Type->isScalarType() || Type->isAnyComplexType()) {
  6099. Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  6100. }
  6101. break;
  6102. case BO_Mul:
  6103. case BO_LAnd:
  6104. if (Type->isScalarType() || Type->isAnyComplexType()) {
  6105. // '*' and '&&' reduction ops - initializer is '1'.
  6106. Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  6107. }
  6108. break;
  6109. case BO_And: {
  6110. // '&' reduction op - initializer is '~0'.
  6111. QualType OrigType = Type;
  6112. if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
  6113. Type = ComplexTy->getElementType();
  6114. }
  6115. if (Type->isRealFloatingType()) {
  6116. llvm::APFloat InitValue =
  6117. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  6118. /*isIEEE=*/true);
  6119. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  6120. Type, ELoc);
  6121. } else if (Type->isScalarType()) {
  6122. auto Size = Context.getTypeSize(Type);
  6123. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  6124. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  6125. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  6126. }
  6127. if (Init && OrigType->isAnyComplexType()) {
  6128. // Init = 0xFFFF + 0xFFFFi;
  6129. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  6130. Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  6131. }
  6132. Type = OrigType;
  6133. break;
  6134. }
  6135. case BO_LT:
  6136. case BO_GT: {
  6137. // 'min' reduction op - initializer is 'Largest representable number in
  6138. // the reduction list item type'.
  6139. // 'max' reduction op - initializer is 'Least representable number in
  6140. // the reduction list item type'.
  6141. if (Type->isIntegerType() || Type->isPointerType()) {
  6142. bool IsSigned = Type->hasSignedIntegerRepresentation();
  6143. auto Size = Context.getTypeSize(Type);
  6144. QualType IntTy =
  6145. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  6146. llvm::APInt InitValue =
  6147. (BOK != BO_LT)
  6148. ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  6149. : llvm::APInt::getMinValue(Size)
  6150. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  6151. : llvm::APInt::getMaxValue(Size);
  6152. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  6153. if (Type->isPointerType()) {
  6154. // Cast to pointer type.
  6155. auto CastExpr = BuildCStyleCastExpr(
  6156. SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
  6157. SourceLocation(), Init);
  6158. if (CastExpr.isInvalid())
  6159. continue;
  6160. Init = CastExpr.get();
  6161. }
  6162. } else if (Type->isRealFloatingType()) {
  6163. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  6164. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  6165. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  6166. Type, ELoc);
  6167. }
  6168. break;
  6169. }
  6170. case BO_PtrMemD:
  6171. case BO_PtrMemI:
  6172. case BO_MulAssign:
  6173. case BO_Div:
  6174. case BO_Rem:
  6175. case BO_Sub:
  6176. case BO_Shl:
  6177. case BO_Shr:
  6178. case BO_LE:
  6179. case BO_GE:
  6180. case BO_EQ:
  6181. case BO_NE:
  6182. case BO_AndAssign:
  6183. case BO_XorAssign:
  6184. case BO_OrAssign:
  6185. case BO_Assign:
  6186. case BO_AddAssign:
  6187. case BO_SubAssign:
  6188. case BO_DivAssign:
  6189. case BO_RemAssign:
  6190. case BO_ShlAssign:
  6191. case BO_ShrAssign:
  6192. case BO_Comma:
  6193. llvm_unreachable("Unexpected reduction operation");
  6194. }
  6195. if (Init) {
  6196. AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
  6197. /*TypeMayContainAuto=*/false);
  6198. } else {
  6199. ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
  6200. }
  6201. if (!RHSVD->hasInit()) {
  6202. Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
  6203. << ReductionIdRange;
  6204. bool IsDecl =
  6205. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6206. Diag(VD->getLocation(),
  6207. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6208. << VD;
  6209. continue;
  6210. }
  6211. auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
  6212. auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
  6213. ExprResult ReductionOp =
  6214. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
  6215. LHSDRE, RHSDRE);
  6216. if (ReductionOp.isUsable()) {
  6217. if (BOK != BO_LT && BOK != BO_GT) {
  6218. ReductionOp =
  6219. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
  6220. BO_Assign, LHSDRE, ReductionOp.get());
  6221. } else {
  6222. auto *ConditionalOp = new (Context) ConditionalOperator(
  6223. ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
  6224. RHSDRE, Type, VK_LValue, OK_Ordinary);
  6225. ReductionOp =
  6226. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
  6227. BO_Assign, LHSDRE, ConditionalOp);
  6228. }
  6229. if (ReductionOp.isUsable()) {
  6230. ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
  6231. }
  6232. }
  6233. if (ReductionOp.isInvalid())
  6234. continue;
  6235. DSAStack->addDSA(VD, DE, OMPC_reduction);
  6236. Vars.push_back(DE);
  6237. LHSs.push_back(LHSDRE);
  6238. RHSs.push_back(RHSDRE);
  6239. ReductionOps.push_back(ReductionOp.get());
  6240. }
  6241. if (Vars.empty())
  6242. return nullptr;
  6243. return OMPReductionClause::Create(
  6244. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
  6245. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
  6246. RHSs, ReductionOps);
  6247. }
  6248. OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
  6249. SourceLocation StartLoc,
  6250. SourceLocation LParenLoc,
  6251. SourceLocation ColonLoc,
  6252. SourceLocation EndLoc) {
  6253. SmallVector<Expr *, 8> Vars;
  6254. SmallVector<Expr *, 8> Inits;
  6255. for (auto &RefExpr : VarList) {
  6256. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  6257. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6258. // It will be analyzed later.
  6259. Vars.push_back(RefExpr);
  6260. Inits.push_back(nullptr);
  6261. continue;
  6262. }
  6263. // OpenMP [2.14.3.7, linear clause]
  6264. // A list item that appears in a linear clause is subject to the private
  6265. // clause semantics described in Section 2.14.3.3 on page 159 except as
  6266. // noted. In addition, the value of the new list item on each iteration
  6267. // of the associated loop(s) corresponds to the value of the original
  6268. // list item before entering the construct plus the logical number of
  6269. // the iteration times linear-step.
  6270. SourceLocation ELoc = RefExpr->getExprLoc();
  6271. // OpenMP [2.1, C/C++]
  6272. // A list item is a variable name.
  6273. // OpenMP [2.14.3.3, Restrictions, p.1]
  6274. // A variable that is part of another variable (as an array or
  6275. // structure element) cannot appear in a private clause.
  6276. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6277. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6278. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  6279. continue;
  6280. }
  6281. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  6282. // OpenMP [2.14.3.7, linear clause]
  6283. // A list-item cannot appear in more than one linear clause.
  6284. // A list-item that appears in a linear clause cannot appear in any
  6285. // other data-sharing attribute clause.
  6286. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  6287. if (DVar.RefExpr) {
  6288. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  6289. << getOpenMPClauseName(OMPC_linear);
  6290. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6291. continue;
  6292. }
  6293. QualType QType = VD->getType();
  6294. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  6295. // It will be analyzed later.
  6296. Vars.push_back(DE);
  6297. Inits.push_back(nullptr);
  6298. continue;
  6299. }
  6300. // A variable must not have an incomplete type or a reference type.
  6301. if (RequireCompleteType(ELoc, QType,
  6302. diag::err_omp_linear_incomplete_type)) {
  6303. continue;
  6304. }
  6305. if (QType->isReferenceType()) {
  6306. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  6307. << getOpenMPClauseName(OMPC_linear) << QType;
  6308. bool IsDecl =
  6309. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6310. Diag(VD->getLocation(),
  6311. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6312. << VD;
  6313. continue;
  6314. }
  6315. // A list item must not be const-qualified.
  6316. if (QType.isConstant(Context)) {
  6317. Diag(ELoc, diag::err_omp_const_variable)
  6318. << getOpenMPClauseName(OMPC_linear);
  6319. bool IsDecl =
  6320. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6321. Diag(VD->getLocation(),
  6322. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6323. << VD;
  6324. continue;
  6325. }
  6326. // A list item must be of integral or pointer type.
  6327. QType = QType.getUnqualifiedType().getCanonicalType();
  6328. const Type *Ty = QType.getTypePtrOrNull();
  6329. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  6330. !Ty->isPointerType())) {
  6331. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
  6332. bool IsDecl =
  6333. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6334. Diag(VD->getLocation(),
  6335. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6336. << VD;
  6337. continue;
  6338. }
  6339. // Build var to save initial value.
  6340. VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
  6341. AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
  6342. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  6343. auto InitRef = buildDeclRefExpr(
  6344. *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  6345. DSAStack->addDSA(VD, DE, OMPC_linear);
  6346. Vars.push_back(DE);
  6347. Inits.push_back(InitRef);
  6348. }
  6349. if (Vars.empty())
  6350. return nullptr;
  6351. Expr *StepExpr = Step;
  6352. Expr *CalcStepExpr = nullptr;
  6353. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  6354. !Step->isInstantiationDependent() &&
  6355. !Step->containsUnexpandedParameterPack()) {
  6356. SourceLocation StepLoc = Step->getLocStart();
  6357. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  6358. if (Val.isInvalid())
  6359. return nullptr;
  6360. StepExpr = Val.get();
  6361. // Build var to save the step value.
  6362. VarDecl *SaveVar =
  6363. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  6364. ExprResult SaveRef =
  6365. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  6366. ExprResult CalcStep =
  6367. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  6368. // Warn about zero linear step (it would be probably better specified as
  6369. // making corresponding variables 'const').
  6370. llvm::APSInt Result;
  6371. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  6372. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  6373. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  6374. << (Vars.size() > 1);
  6375. if (!IsConstant && CalcStep.isUsable()) {
  6376. // Calculate the step beforehand instead of doing this on each iteration.
  6377. // (This is not used if the number of iterations may be kfold-ed).
  6378. CalcStepExpr = CalcStep.get();
  6379. }
  6380. }
  6381. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
  6382. Vars, Inits, StepExpr, CalcStepExpr);
  6383. }
  6384. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  6385. Expr *NumIterations, Sema &SemaRef,
  6386. Scope *S) {
  6387. // Walk the vars and build update/final expressions for the CodeGen.
  6388. SmallVector<Expr *, 8> Updates;
  6389. SmallVector<Expr *, 8> Finals;
  6390. Expr *Step = Clause.getStep();
  6391. Expr *CalcStep = Clause.getCalcStep();
  6392. // OpenMP [2.14.3.7, linear clause]
  6393. // If linear-step is not specified it is assumed to be 1.
  6394. if (Step == nullptr)
  6395. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  6396. else if (CalcStep)
  6397. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  6398. bool HasErrors = false;
  6399. auto CurInit = Clause.inits().begin();
  6400. for (auto &RefExpr : Clause.varlists()) {
  6401. Expr *InitExpr = *CurInit;
  6402. // Build privatized reference to the current linear var.
  6403. auto DE = cast<DeclRefExpr>(RefExpr);
  6404. auto PrivateRef =
  6405. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  6406. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  6407. /*RefersToCapture=*/true);
  6408. // Build update: Var = InitExpr + IV * Step
  6409. ExprResult Update =
  6410. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
  6411. InitExpr, IV, Step, /* Subtract */ false);
  6412. Update = SemaRef.ActOnFinishFullExpr(Update.get());
  6413. // Build final: Var = InitExpr + NumIterations * Step
  6414. ExprResult Final =
  6415. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
  6416. InitExpr, NumIterations, Step, /* Subtract */ false);
  6417. Final = SemaRef.ActOnFinishFullExpr(Final.get());
  6418. if (!Update.isUsable() || !Final.isUsable()) {
  6419. Updates.push_back(nullptr);
  6420. Finals.push_back(nullptr);
  6421. HasErrors = true;
  6422. } else {
  6423. Updates.push_back(Update.get());
  6424. Finals.push_back(Final.get());
  6425. }
  6426. ++CurInit;
  6427. }
  6428. Clause.setUpdates(Updates);
  6429. Clause.setFinals(Finals);
  6430. return HasErrors;
  6431. }
  6432. OMPClause *Sema::ActOnOpenMPAlignedClause(
  6433. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  6434. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  6435. SmallVector<Expr *, 8> Vars;
  6436. for (auto &RefExpr : VarList) {
  6437. assert(RefExpr && "NULL expr in OpenMP aligned clause.");
  6438. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6439. // It will be analyzed later.
  6440. Vars.push_back(RefExpr);
  6441. continue;
  6442. }
  6443. SourceLocation ELoc = RefExpr->getExprLoc();
  6444. // OpenMP [2.1, C/C++]
  6445. // A list item is a variable name.
  6446. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6447. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6448. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  6449. continue;
  6450. }
  6451. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  6452. // OpenMP [2.8.1, simd construct, Restrictions]
  6453. // The type of list items appearing in the aligned clause must be
  6454. // array, pointer, reference to array, or reference to pointer.
  6455. QualType QType = VD->getType();
  6456. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  6457. const Type *Ty = QType.getTypePtrOrNull();
  6458. if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
  6459. !Ty->isPointerType())) {
  6460. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  6461. << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
  6462. bool IsDecl =
  6463. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6464. Diag(VD->getLocation(),
  6465. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6466. << VD;
  6467. continue;
  6468. }
  6469. // OpenMP [2.8.1, simd construct, Restrictions]
  6470. // A list-item cannot appear in more than one aligned clause.
  6471. if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
  6472. Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
  6473. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  6474. << getOpenMPClauseName(OMPC_aligned);
  6475. continue;
  6476. }
  6477. Vars.push_back(DE);
  6478. }
  6479. // OpenMP [2.8.1, simd construct, Description]
  6480. // The parameter of the aligned clause, alignment, must be a constant
  6481. // positive integer expression.
  6482. // If no optional parameter is specified, implementation-defined default
  6483. // alignments for SIMD instructions on the target platforms are assumed.
  6484. if (Alignment != nullptr) {
  6485. ExprResult AlignResult =
  6486. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  6487. if (AlignResult.isInvalid())
  6488. return nullptr;
  6489. Alignment = AlignResult.get();
  6490. }
  6491. if (Vars.empty())
  6492. return nullptr;
  6493. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  6494. EndLoc, Vars, Alignment);
  6495. }
  6496. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  6497. SourceLocation StartLoc,
  6498. SourceLocation LParenLoc,
  6499. SourceLocation EndLoc) {
  6500. SmallVector<Expr *, 8> Vars;
  6501. SmallVector<Expr *, 8> SrcExprs;
  6502. SmallVector<Expr *, 8> DstExprs;
  6503. SmallVector<Expr *, 8> AssignmentOps;
  6504. for (auto &RefExpr : VarList) {
  6505. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  6506. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6507. // It will be analyzed later.
  6508. Vars.push_back(RefExpr);
  6509. SrcExprs.push_back(nullptr);
  6510. DstExprs.push_back(nullptr);
  6511. AssignmentOps.push_back(nullptr);
  6512. continue;
  6513. }
  6514. SourceLocation ELoc = RefExpr->getExprLoc();
  6515. // OpenMP [2.1, C/C++]
  6516. // A list item is a variable name.
  6517. // OpenMP [2.14.4.1, Restrictions, p.1]
  6518. // A list item that appears in a copyin clause must be threadprivate.
  6519. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6520. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6521. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  6522. continue;
  6523. }
  6524. Decl *D = DE->getDecl();
  6525. VarDecl *VD = cast<VarDecl>(D);
  6526. QualType Type = VD->getType();
  6527. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  6528. // It will be analyzed later.
  6529. Vars.push_back(DE);
  6530. SrcExprs.push_back(nullptr);
  6531. DstExprs.push_back(nullptr);
  6532. AssignmentOps.push_back(nullptr);
  6533. continue;
  6534. }
  6535. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  6536. // A list item that appears in a copyin clause must be threadprivate.
  6537. if (!DSAStack->isThreadPrivate(VD)) {
  6538. Diag(ELoc, diag::err_omp_required_access)
  6539. << getOpenMPClauseName(OMPC_copyin)
  6540. << getOpenMPDirectiveName(OMPD_threadprivate);
  6541. continue;
  6542. }
  6543. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  6544. // A variable of class type (or array thereof) that appears in a
  6545. // copyin clause requires an accessible, unambiguous copy assignment
  6546. // operator for the class type.
  6547. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  6548. auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
  6549. ElemType.getUnqualifiedType(), ".copyin.src");
  6550. auto *PseudoSrcExpr = buildDeclRefExpr(
  6551. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  6552. auto *DstVD =
  6553. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
  6554. auto *PseudoDstExpr =
  6555. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  6556. // For arrays generate assignment operation for single element and replace
  6557. // it by the original array element in CodeGen.
  6558. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  6559. PseudoDstExpr, PseudoSrcExpr);
  6560. if (AssignmentOp.isInvalid())
  6561. continue;
  6562. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  6563. /*DiscardedValue=*/true);
  6564. if (AssignmentOp.isInvalid())
  6565. continue;
  6566. DSAStack->addDSA(VD, DE, OMPC_copyin);
  6567. Vars.push_back(DE);
  6568. SrcExprs.push_back(PseudoSrcExpr);
  6569. DstExprs.push_back(PseudoDstExpr);
  6570. AssignmentOps.push_back(AssignmentOp.get());
  6571. }
  6572. if (Vars.empty())
  6573. return nullptr;
  6574. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  6575. SrcExprs, DstExprs, AssignmentOps);
  6576. }
  6577. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  6578. SourceLocation StartLoc,
  6579. SourceLocation LParenLoc,
  6580. SourceLocation EndLoc) {
  6581. SmallVector<Expr *, 8> Vars;
  6582. SmallVector<Expr *, 8> SrcExprs;
  6583. SmallVector<Expr *, 8> DstExprs;
  6584. SmallVector<Expr *, 8> AssignmentOps;
  6585. for (auto &RefExpr : VarList) {
  6586. assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
  6587. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6588. // It will be analyzed later.
  6589. Vars.push_back(RefExpr);
  6590. SrcExprs.push_back(nullptr);
  6591. DstExprs.push_back(nullptr);
  6592. AssignmentOps.push_back(nullptr);
  6593. continue;
  6594. }
  6595. SourceLocation ELoc = RefExpr->getExprLoc();
  6596. // OpenMP [2.1, C/C++]
  6597. // A list item is a variable name.
  6598. // OpenMP [2.14.4.1, Restrictions, p.1]
  6599. // A list item that appears in a copyin clause must be threadprivate.
  6600. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6601. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6602. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  6603. continue;
  6604. }
  6605. Decl *D = DE->getDecl();
  6606. VarDecl *VD = cast<VarDecl>(D);
  6607. QualType Type = VD->getType();
  6608. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  6609. // It will be analyzed later.
  6610. Vars.push_back(DE);
  6611. SrcExprs.push_back(nullptr);
  6612. DstExprs.push_back(nullptr);
  6613. AssignmentOps.push_back(nullptr);
  6614. continue;
  6615. }
  6616. // OpenMP [2.14.4.2, Restrictions, p.2]
  6617. // A list item that appears in a copyprivate clause may not appear in a
  6618. // private or firstprivate clause on the single construct.
  6619. if (!DSAStack->isThreadPrivate(VD)) {
  6620. auto DVar = DSAStack->getTopDSA(VD, false);
  6621. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  6622. DVar.RefExpr) {
  6623. Diag(ELoc, diag::err_omp_wrong_dsa)
  6624. << getOpenMPClauseName(DVar.CKind)
  6625. << getOpenMPClauseName(OMPC_copyprivate);
  6626. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6627. continue;
  6628. }
  6629. // OpenMP [2.11.4.2, Restrictions, p.1]
  6630. // All list items that appear in a copyprivate clause must be either
  6631. // threadprivate or private in the enclosing context.
  6632. if (DVar.CKind == OMPC_unknown) {
  6633. DVar = DSAStack->getImplicitDSA(VD, false);
  6634. if (DVar.CKind == OMPC_shared) {
  6635. Diag(ELoc, diag::err_omp_required_access)
  6636. << getOpenMPClauseName(OMPC_copyprivate)
  6637. << "threadprivate or private in the enclosing context";
  6638. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6639. continue;
  6640. }
  6641. }
  6642. }
  6643. // Variably modified types are not supported.
  6644. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  6645. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  6646. << getOpenMPClauseName(OMPC_copyprivate) << Type
  6647. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  6648. bool IsDecl =
  6649. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6650. Diag(VD->getLocation(),
  6651. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6652. << VD;
  6653. continue;
  6654. }
  6655. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  6656. // A variable of class type (or array thereof) that appears in a
  6657. // copyin clause requires an accessible, unambiguous copy assignment
  6658. // operator for the class type.
  6659. Type = Context.getBaseElementType(Type).getUnqualifiedType();
  6660. auto *SrcVD =
  6661. buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
  6662. auto *PseudoSrcExpr =
  6663. buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
  6664. auto *DstVD =
  6665. buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
  6666. auto *PseudoDstExpr =
  6667. buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
  6668. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  6669. PseudoDstExpr, PseudoSrcExpr);
  6670. if (AssignmentOp.isInvalid())
  6671. continue;
  6672. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  6673. /*DiscardedValue=*/true);
  6674. if (AssignmentOp.isInvalid())
  6675. continue;
  6676. // No need to mark vars as copyprivate, they are already threadprivate or
  6677. // implicitly private.
  6678. Vars.push_back(DE);
  6679. SrcExprs.push_back(PseudoSrcExpr);
  6680. DstExprs.push_back(PseudoDstExpr);
  6681. AssignmentOps.push_back(AssignmentOp.get());
  6682. }
  6683. if (Vars.empty())
  6684. return nullptr;
  6685. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  6686. Vars, SrcExprs, DstExprs, AssignmentOps);
  6687. }
  6688. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  6689. SourceLocation StartLoc,
  6690. SourceLocation LParenLoc,
  6691. SourceLocation EndLoc) {
  6692. if (VarList.empty())
  6693. return nullptr;
  6694. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  6695. }
  6696. OMPClause *
  6697. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  6698. SourceLocation DepLoc, SourceLocation ColonLoc,
  6699. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  6700. SourceLocation LParenLoc, SourceLocation EndLoc) {
  6701. if (DepKind == OMPC_DEPEND_unknown) {
  6702. std::string Values;
  6703. std::string Sep(", ");
  6704. for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
  6705. Values += "'";
  6706. Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
  6707. Values += "'";
  6708. switch (i) {
  6709. case OMPC_DEPEND_unknown - 2:
  6710. Values += " or ";
  6711. break;
  6712. case OMPC_DEPEND_unknown - 1:
  6713. break;
  6714. default:
  6715. Values += Sep;
  6716. break;
  6717. }
  6718. }
  6719. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  6720. << Values << getOpenMPClauseName(OMPC_depend);
  6721. return nullptr;
  6722. }
  6723. SmallVector<Expr *, 8> Vars;
  6724. for (auto &RefExpr : VarList) {
  6725. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  6726. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6727. // It will be analyzed later.
  6728. Vars.push_back(RefExpr);
  6729. continue;
  6730. }
  6731. SourceLocation ELoc = RefExpr->getExprLoc();
  6732. // OpenMP [2.11.1.1, Restrictions, p.3]
  6733. // A variable that is part of another variable (such as a field of a
  6734. // structure) but is not an array element or an array section cannot appear
  6735. // in a depend clause.
  6736. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  6737. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
  6738. ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  6739. if (!RefExpr->IgnoreParenImpCasts()->isLValue() || (!ASE && !DE) ||
  6740. (DE && !isa<VarDecl>(DE->getDecl())) ||
  6741. (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
  6742. !ASE->getBase()->getType()->isArrayType())) {
  6743. Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
  6744. << RefExpr->getSourceRange();
  6745. continue;
  6746. }
  6747. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  6748. }
  6749. if (Vars.empty())
  6750. return nullptr;
  6751. return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
  6752. DepLoc, ColonLoc, Vars);
  6753. }
  6754. #endif // HLSL Change